"""services/leave_approval.py

Conversational leave approval (FR-07.4) - lets a MANAGER approve one
specific, named team member's pending leave request from chat, behind the
explicit confirmation step FR-08.3 requires.

FR-07.4, verbatim: "Managers shall be able to approve a specific request
conversationally (e.g. 'Approve these two requests') with an explicit
confirmation step; the action shall be logged."

FR-08.3, verbatim: "Any action that changes system state (...manager
approval/override) shall require an explicit user confirmation step before
execution; the assistant shall never execute such an action silently."

The whole module is built around that second sentence. Everything is
arranged so that "executed silently" is not a state this code can reach:

  * There is exactly ONE call site for erp_client.approve_leave_request, in
    _execute_approval, and the only path into it starts from a stored
    awaiting_confirmation state that a PREVIOUS turn wrote.
  * That state can only be written by _build_confirmation, which returns
    without calling erp-api at all.
  * The confirming turn is matched by explicit patterns, never by an LLM
    judgement - the extraction call in this file only decides WHICH request
    a manager is talking about, never whether they said yes. A model that
    misreads "not yet" cannot approve anything; the worst it can do is fail
    to recognise a target and ask.

Strict scope boundary (per the story)
-------------------------------------
IN:  approving ONE specific, named pending leave request, on confirmation;
     the confirmation summary; the audit log entry.
OUT: finding/viewing the request first (that is FR-07.3,
     services/individual_report.py); bulk approval across several requests
     (FR-07.5, a separate story - refused here by name); rejection/denial.

Rejection
---------
Rejection WAS out of scope while erp-api had no route for it. It now has
POST /api/v1/ai/leave/requests/{id}/reject, so a rejection is executed rather
than refused - behind the same confirmation discipline as an approval, with
one difference: the confirming reply is the REASON, not a "yes". erp-api
requires a rejection_reason and the employee reads it, so it is the one field
this flow must never invent, and a written sentence is stronger evidence of
intent than a yes-word anyway.

Backing endpoint
----------------
POST /api/v1/ai/leave/requests/{id}/approve (LIVE). Team scope is erp-api's
call, not ours: it resolves the request within the caller's own hierarchy and
refuses anything outside it with "Pending leave request was not found in your
team." We surface that verbatim - it is the same answer for out-of-team and
no-longer-pending, so it confirms nothing about who exists where.

KNOWN GAP: the confirmation summary must carry Request Type (Leave /
Regularization). erp-api's pending-leave rows are leave requests only - there
is no regularization request in this contract - so the field renders as
"Leave" and _request_type() is the one place to widen when erp-api starts
returning regularizations.
"""

import logging
import os
import re
from datetime import date

from langgraph.types import StreamWriter

import services.access_notice as access_notice
import services.ai_service as ai_service
import services.audit_log_service as audit_log_service
import services.date_query_resolver as date_query_resolver
import services.erp_client as erp_client
import services.individual_report as individual_report
import services.leave_action_service as leave_action_service
import services.leave_slot_service as leave_slot_service
from services.nlp_service import fold_smart_punctuation
from services.individual_report import MANAGER_UNKNOWN, _match_selection, _today_in_app_timezone
from services.complex_manager_router import route_complex_manager_task

logger = logging.getLogger(__name__)

APPROVAL_INTENT = "manager_leave_approval"

ACTION_APPROVE = "approve"
ACTION_REJECT = "reject"

# Whether a manager can REJECT a leave request from the assistant.
#
# The story this flow was built against says approve is the only action the
# assistant offers; QA raised the reject option as a defect against it. The
# reject path itself is real and works (erp-api has POST .../reject, and
# _build_confirmation arms a card that collects the reason erp-api requires),
# so it is gated rather than deleted — a product decision reversed by one env
# var, not by restoring a few hundred lines from git history.
#
# Default OFF to match the story. Set LEAVE_REJECTION_ENABLED=true to restore
# it; tests that cover the reject path enable it explicitly.
LEAVE_REJECTION_ENABLED = os.getenv("LEAVE_REJECTION_ENABLED", "false").strip().lower() in ("1", "true", "yes", "on")

# Said when a manager asks to reject while the flow is approve-only. It names
# where the action DOES live rather than dead-ending: erp-api can still reject,
# and the Leave Approvals screen is where that is done.
REJECTION_UNAVAILABLE_MESSAGE = (
    "I can only approve leave requests here. To reject one, please use the "
    "Leave Approvals page in your dashboard."
)

# Discriminator on the shared manager-action card - see
# resolve_pending_approval_intent. Kept as a constant so this feature and
# regularisation_approval.py's CARD_KIND cannot drift into agreeing.
CARD_KIND = "leave"

#: Rides on every `done` payload this node emits. True only when the turn
#: CALLED THE APPROVAL OFF - the manager declined the confirmation card, or
#: asked to cancel the approval outright - so the client can render that
#: outcome differently from an ordinary answer. False on everything else,
#: including the approval actually going through, so the key is always
#: present and a client never has to treat "missing" as a third state.
#:
CANCEL_APPROVE_FLAG = "cancel_approve_leave_request"

# Same reasoning as individual_report.NOT_A_MANAGER_MESSAGE: this is "your
# role cannot do this", never "that employee is off-limits to you".
NOT_A_MANAGER_MESSAGE = (
    "Approving leave requests is available to managers only - this isn't "
    "something I can do for your role."
)

# FR-07.5's scope, refused by name rather than by silently approving the
# first of several.
# The dashboard route a bulk instruction is sent to (FR-07.5).
BULK_APPROVALS_INTENT = "bulk_approvals"

BULK_MESSAGE = (
    "I can only approve one request at a time here, and I haven't changed "
    "anything. Tell me which single request to approve - for example "
    "'approve John's leave request' - and I'll show you the details to "
    "confirm first."
)

# erp-api's own wording for a request outside the caller's hierarchy, reused
# for every "that isn't yours to approve" exit so the answer is identical
# whether the request belongs to another team, was already actioned, or never
# existed - it must not become a way to probe who reports to whom.
NOT_IN_YOUR_TEAM_MESSAGE = "Pending leave request was not found in your team."

# erp-api validates rejection_reason at 3-500 characters. Mirrored here so a
# one-word reply is answered immediately rather than after a round trip that
# comes back with the same complaint.
_MIN_REJECTION_REASON = 3

_ERP_TIMEOUT_MESSAGE = "I couldn't reach the HR system in time - please try again in a moment."
_ERP_UNAVAILABLE_MESSAGE = "I'm unable to reach the HR system right now - please try again shortly."


# A Laravel VALIDATOR complaint, as opposed to a business rule. "The browser id
# field is required." is a bug in THIS service's request, not an answer a
# manager can act on, and reading it back to them is both confusing and a small
# leak of erp-api's request shape. Business refusals ("Attendance is locked for
# this date. Contact HR.") must never match this.
_VALIDATION_MESSAGE = re.compile(
    r"^\s*the\s+.+?\bfield\b.*?\b(is required|must|may not|has already)\b",
    re.IGNORECASE,
)

_MALFORMED_REQUEST_MESSAGE = (
    "I couldn't complete that approval - the HR system rejected the request. "
    "Please approve it in the HR portal instead."
)


def _refusal_sentence(erp_message: str | None, fallback: str) -> str:
    """erp-api's own refusal, punctuated so it reads as its own sentence.

    The rule it enforced is written for a form field and arrives without a
    full stop ("Cannot approve this as leave count exceed remaining leave for
    this user"), so appending the reassurance produced one run-on sentence:
    "...for this user Nothing has been changed." The manager's answer is
    erp-api's wording verbatim - only the terminator is added.

    The one message NOT passed through is a validator complaint: that says this
    service sent a malformed request, so it is logged for us and the manager is
    told plainly that the approval did not happen.
    """
    raw = (erp_message or "").strip()
    if raw and _VALIDATION_MESSAGE.match(raw):
        logger.error(
            "[Approval] erp-api rejected the request as INVALID, not refused: %r. "
            "This is a malformed request from this service, not a business rule.",
            raw,
        )
        raw = _MALFORMED_REQUEST_MESSAGE

    text = raw or fallback.strip()
    if text and text[-1] not in ".!?":
        text += "."
    return f"{text} Nothing has been changed."


# The confirming turn is matched HERE, by pattern, and nowhere else - see the
# module docstring. Kept deliberately narrow: these are ways of saying "yes,
# do it", not ways of sounding agreeable. "sounds good", "thanks", "great"
# are absent on purpose; an approval is not something to infer from politeness.
#
# An explicit instruction counts wherever it appears in the message.
_EXPLICIT_CONFIRM_PATTERNS: list[re.Pattern] = [
    re.compile(r"\b(confirm|confirmed|confirming)\b", re.IGNORECASE),
    re.compile(r"\b(go\s+ahead|proceed|do\s+it|please\s+do)\b", re.IGNORECASE),
    re.compile(r"\bapprove\s+(it|this|that|them)\b", re.IGNORECASE),
]

# A bare yes-word, on the other hand, only counts when it is the WHOLE
# message. "okay" opening a sentence that then asks for something else
# ("okay but first, what's his balance?") is not a confirmation, and treating
# it as one would approve a request while answering a different question -
# precisely the silent execution FR-08.3 rules out. So the yes-word must be
# followed by nothing but politeness.
_LEADING_AFFIRMATIVE = re.compile(r"^\s*(y|yes|yeah|yep|yup|ok|okay|sure|correct)\b", re.IGNORECASE)
_AFFIRMATIVE_TAIL = re.compile(
    r"^(?:[\s,.!?\-]|please|thanks|thank\s+you|sure|correct|that'?s\s+right|"
    r"go\s+ahead|do\s+it|approve\s+it|confirm(?:ed)?|proceed|submit\s+it|it|this|that)*$",
    re.IGNORECASE,
)

# Checked BEFORE the affirmatives, so a message carrying both ("no, don't
# approve it") lands on the safe side. A decline never changes system state,
# so there is no cost to it winning a tie.
_DECLINE_PATTERNS: list[re.Pattern] = [
    re.compile(r"^\s*(n|no|nope|nah)\b", re.IGNORECASE),
    re.compile(r"\b(cancel|never\s*mind|nevermind|forget\s+it)\b", re.IGNORECASE),
    re.compile(r"\bdon'?t\s+(approve|do|submit)\b", re.IGNORECASE),
    re.compile(r"\b(hold\s+off|not\s+yet|not\s+now|leave\s+it\s+pending|wait)\b", re.IGNORECASE),
    re.compile(r"\bstop\b", re.IGNORECASE),
]

# "Is this message trying to act on a request at all" - used only to decide
# whether an unclear reply mid-confirmation should be re-read as a NEW
# instruction ("approve Priya's instead") rather than answered as a yes/no.
# VERBS only: the noun "approval" belongs to questions about how approvals
# work, which this feature has no business intercepting.
_ACTION_VERB_PATTERN = re.compile(
    r"\b(approve|approved|approving|reject|rejected|rejecting|deny|denied|decline)\b",
    re.IGNORECASE,
)

# A question is never a confirmation. Without this, "did you approve it
# already?" matches the "approve it" instruction pattern and executes the
# approval it was asking about - the exact silent execution FR-08.3 forbids,
# arrived at from a message that asked for nothing.
_QUESTION_OPENERS = re.compile(
    r"^\s*(did|do|does|can|could|will|would|should|have|has|had|is|are|was|were|"
    r"what|why|how|when|who|whose|which|any)\b",
    re.IGNORECASE,
)


# A reply that NAMES A REQUEST OF ITS OWN - "go ahead and approve Priya's
# request", "proceed with request 61", "confirm approving geo4's leave" - is a
# re-aimed INSTRUCTION, not a confirmation of the card on screen.
#
# Without this, the confirm words above win: _EXPLICIT_CONFIRM_PATTERNS match
# "go ahead" / "proceed" / "confirm" ANYWHERE in the message, so the
# PREVIOUSLY armed request is executed while the newly named one is never
# even read. Live repro: with B Geo's card armed, "go ahead and approve C
# Geo's leave request" approved B GEO's request and reported it as a success
# naming B Geo. That is FR-08.3's silent execution, on the wrong employee.
#
# The bare yes-word path already enforces this discipline through
# _AFFIRMATIVE_TAIL ("yes, approve Priya's instead" is correctly not a
# confirmation); this is the same rule for the explicit-instruction path.
#
# Erring toward "it named something, re-read it" is free: a re-aimed
# instruction can only ever produce another confirmation card, never an
# execution. The cost of the opposite mistake is approving the wrong person's
# leave. Pronoun objects are excluded on purpose - "approve it" / "approve
# this request" name nothing new and ARE confirmations of what is on screen.
_NAMES_A_TARGET = re.compile(
    # an action verb whose object is not a pronoun: "approve Priya's",
    # "approve B Geo", "approve request 61"
    r"\b(?:approve|approving|reject|rejecting|deny|denying|decline)\s+"
    r"(?!(?:it|this|that|them|these|those)\b)[\w#'-]"
    # a possessive saying whose request it is: "Priya's leave", "B Geo's request"
    r"|\b(?!(?:it|this|that|there|here)\b)[a-z][\w.-]*(?:'s|s')\s+"
    r"(?:leave|request|application|absence)\b"
    # an explicit identifier: "request 61", "employee 3736", "#61"
    r"|\b(?:request|application|employee|emp)\s*#?\s*\d+\b"
    r"|#\s*\d+\b",
    re.IGNORECASE,
)


def _is_question(query: str) -> bool:
    return "?" in query or bool(_QUESTION_OPENERS.match(query))


def _is_declining(query: str) -> bool:
    return any(p.search(query) for p in _DECLINE_PATTERNS)


def names_a_target(query: str) -> bool:
    """True when the message names a request or person of its own, rather
    than only answering the question already on screen."""
    return bool(_NAMES_A_TARGET.search(query))


def _is_affirmative(query: str) -> bool:
    if _is_declining(query) or _is_question(query):
        return False
    # Checked BEFORE the confirm words, not after: a message carrying both an
    # instruction word and a target of its own is the re-aim, and the target
    # is the part that decides WHAT would be acted on.
    if names_a_target(query):
        return False
    if any(p.search(query) for p in _EXPLICIT_CONFIRM_PATTERNS):
        return True
    match = _LEADING_AFFIRMATIVE.match(query)
    return bool(match and _AFFIRMATIVE_TAIL.match(query[match.end():]))


def mentions_action(query: str) -> bool:
    return bool(_ACTION_VERB_PATTERN.search(query))


#: A message that is ONLY a request number - "310", "#310", "request 310".
_BARE_REQUEST_ID = re.compile(
    r"^\s*(?:(?:leave\s+)?(?:request|application|lr)\s*[-#]?\s*)?#?\s*\d{1,10}\s*$",
    re.IGNORECASE,
)


def _names_a_leave_type(query: str) -> bool:
    """True when the message names a leave type and little else."""
    try:
        return bool(leave_action_service._extract_leave_type_filters(query or ""))
    except Exception:
        return False


#: "cancel", "stop", "call off" - calling the action off rather than doing it.
_STAND_DOWN_VERBS = re.compile(
    r"\b(cancel|cancelled|canceling|cancelling|stop|abort|call\s+off|drop|forget|"
    r"withdraw|undo|nevermind|never\s+mind)\b", re.IGNORECASE)

#: Words that make it the CALLER's own leave, which is a different feature.
#: Hindi/Hinglish included - QA: a manager's first message "meri leave cancel
#: kr do" ("cancel my leave") was read as calling off an approval for an
#: employee named "Meri Leave Cancel Kr Do", because only the English words
#: were listed and the rest of the sentence looked like a name.
_SELF_REFERENCE = re.compile(
    r"\b(my|me|mine|myself|i|our|ours|us|"
    r"meri|mera|mere|mujhe|mujhko|main|mai|mein|apni|apna|apne|hamari|humari|hamara|humara)\b",
    re.IGNORECASE)

#: Stripped before asking whether what remains is a person.
_STAND_DOWN_FILLER = re.compile(
    r"\b(cancel|cancelled|canceling|cancelling|stop|abort|call|off|drop|forget|"
    r"withdraw|undo|nevermind|never|mind|the|this|that|a|an|of|for|to|please|"
    r"approval|approving|approve|request|requests|leave|leaves|application|"
    r"flow|process|it|"
    # Hinglish verb helpers ("cancel kar do", "cancel kr dijiye"): part of
    # the instruction, never part of a name.
    r"kar|kr|karo|kro|krdo|kardo|do|de|dena|dijiye|dijie|please|pls|plz)\b", re.IGNORECASE)


def is_cancel_approval_instruction(query: str) -> bool:
    """True for "cancel a khan test" - calling OFF an approval for somebody
    else, not cancelling the caller's own leave.

    Reported: after standing an approval down with "no", the manager typed
    "cancel a khan test" and was shown their OWN five leave requests, with
    "which one would you like to cancel?". The message names a TEAM MEMBER,
    so answering it with the caller's own leave list is the wrong person's
    data entirely - and cancelling one of those would have been a real,
    unintended change.

    Deliberately narrow. A cancel verb alone is not enough: the message must
    name somebody, and must not refer to the caller ("cancel MY leave" is the
    caller's own flow and stays there).
    """
    text = fold_smart_punctuation((query or "").lower())
    if not text or not _STAND_DOWN_VERBS.search(text):
        return False
    if _SELF_REFERENCE.search(text):
        return False
    # "cancel and approve request 61" cancels THIS one and asks for another -
    # a re-aim, not a stand-down. A message carrying an action verb of its
    # own, or naming a request of its own, is telling us what to do next
    # rather than to stop; both belong to the re-aim path below.
    if _APPROVE_VERB_PATTERN.search(text) or _REJECT_VERB_PATTERN.search(text):
        return False
    if names_a_target(text):
        return False
    remainder = re.sub(r"\s+", " ", _STAND_DOWN_FILLER.sub(" ", text)).strip()
    if not remainder:
        return False
    from services.classify_node import _is_bare_person_fragment
    return _is_bare_person_fragment(remainder, False)


#: Everything that can precede the name in "cancel the approval for A Khan
#: Test". Stripped from the FRONT only - deleting these words wherever they
#: appear turned "a khan test" into "Khan Test", because the "A" that starts
#: that name is also an article.
_STAND_DOWN_PREFIX = re.compile(
    r"^\s*(?:please\s+|can\s+you\s+|could\s+you\s+)?"
    r"(?:cancel|cancelled|canceling|cancelling|stop|abort|call\s+off|drop|"
    r"forget|withdraw|undo|nevermind|never\s+mind)\s+"
    r"(?:the\s+|this\s+|that\s+)?"
    r"(?:approval|approving|approve|request|requests|leave|leaves|application|"
    r"flow|process)?\s*"
    r"(?:for\s+|of\s+)?",
    re.IGNORECASE)


def _stood_down_subject(query: str) -> str:
    """The person named in a "cancel <name>" instruction, title-cased for the
    reply. Empty when the message named nobody recognisable."""
    text = fold_smart_punctuation((query or "").strip())
    return re.sub(r"\s+", " ", _STAND_DOWN_PREFIX.sub("", text, count=1)).strip().title()


def _looks_like_a_search_reply(query: str) -> bool:
    """True when the message is a DATE or a LEAVE TYPE - something to look up
    among the pending requests rather than an answer to the card.

    Reported: with an approve card on screen the manager typed "21 Sept 2026".
    Neither a request ID nor a name, so it was not recognised as a re-aim and
    went to general classification - where the chat model wrote a
    confirmation card in prose ("Shall I approve this Casual Leave request?")
    with no intent behind it, nothing armed, and nothing fetched. A "yes"
    after that would have found no card at all.
    """
    text = (query or "").strip()
    if not text or _is_question(text) or _is_declining(text) or _is_affirmative(text):
        return False
    if _explicit_dates(text.lower()):
        return True
    return _names_a_leave_type(text)


def _looks_like_a_target_reply(query: str) -> bool:
    """True when the whole message is just a request ID or just a person's
    name - no verb, no question, nothing else.

    This is what a manager types to re-aim a card that is already showing:
    "310", or "abc testing". Neither carries an action verb, so neither is
    caught by mentions_action or names_a_target, and both used to fall
    through to general classification - where the chat model answered from
    conversation history and nothing was looked up.
    """
    text = (query or "").strip()
    if not text or _is_question(text) or _is_declining(text) or _is_affirmative(text):
        return False
    if _BARE_REQUEST_ID.match(text):
        return True
    # A bare name, judged the same way classify_node judges one - so "yes",
    # "thanks" and a bare date are excluded there rather than restated here.
    #
    # Imported at call time, not at module load: classify_node imports THIS
    # module (for resolve_pending_approval_intent), so the reverse import has
    # to stay out of the import graph.
    from services.classify_node import _is_bare_person_fragment
    return _is_bare_person_fragment(text, False)


# Split out of _ACTION_VERB_PATTERN so a confirming turn can tell "approve"
# from "reject" - saying the OTHER word than the card proposes is never a
# confirmation of it.
_APPROVE_VERB_PATTERN = re.compile(r"\b(approve|approved|approving)\b", re.IGNORECASE)
_REJECT_VERB_PATTERN = re.compile(
    r"\b(reject|rejected|rejecting|deny|denied|decline|declined)\b", re.IGNORECASE)


#: Words that carry no target of their own. "approve the request" and
#: "Approve Request" (the card's own button label) point at whatever is on
#: screen, so what is left after removing these is what decides whether some
#: OTHER request was named.
_GENERIC_TARGET_WORDS = frozenset({
    "approve", "approved", "approving", "reject", "rejected", "rejecting",
    "deny", "denied", "decline", "declined", "confirm", "confirmed", "proceed",
    "submit", "go", "ahead", "do", "please", "thanks", "thank", "you",
    "yes", "yeah", "yep", "yup", "ok", "okay", "sure", "correct", "right",
    "request", "requests", "leave", "leaves", "application", "applications",
    "absence", "one", "this", "that", "it", "them", "the", "a", "an",
    "his", "her", "their", "its", "s", "for", "of", "and", "now", "pending",
})

#: A STANDALONE number. The "3" inside an employee code like "geo3" is not a
#: request id, and reading it as one sent "approve geo3" off to look for
#: request 3 instead of confirming the card on screen.
_STANDALONE_NUMBER = re.compile(r"(?<![a-z0-9])(\d{1,10})(?![a-z0-9])", re.IGNORECASE)

_WORD = re.compile(r"[a-z][a-z'.-]*", re.IGNORECASE)


def _identifies_another_request(query: str, pending: dict) -> bool:
    """True only when the message points at a CONCRETE request that is not
    the one on the card.

    Ordered by how decisive each signal is:

      * a standalone number - the card's own id means "this one", any other
        number means a different request and must never be confirmed by
        mistake;
      * the card's own employee, by full name or code - "this one";
      * anything substantive left once the instruction and filler words are
        removed - somebody else ("approve Priya's instead").

    A name that is merely SIMILAR ("Ayush Chandra" against a card for "Ayush
    Jio") falls into that last case and counts as another request, because
    the full name is what tells them apart.
    """
    card = pending.get("card") or {}
    text = (query or "").lower()

    numbers = {int(n) for n in _STANDALONE_NUMBER.findall(text)}
    if numbers:
        request_id = pending.get("leave_request_id")
        return request_id is None or int(request_id) not in numbers

    for key in ("employee_name", "employee_number"):
        value = str(card.get(key) or "").strip().lower()
        if value and value in text:
            return False

    return any(word not in _GENERIC_TARGET_WORDS
               for word in _WORD.findall(text))


def _names_this_card(query: str, pending: dict) -> bool:
    """True when the target this message names IS the request already on the
    card. Thin inverse of _identifies_another_request, kept as its own name
    because that is how the call site reads."""
    card = pending.get("card") or {}
    text = (query or "").lower()

    if _identifies_another_request(query, pending):
        return False

    for key in ("employee_name", "employee_number"):
        value = str(card.get(key) or "").strip().lower()
        if value and value in text:
            return True
    return False


def _asks_the_opposite_action(query: str, pending: dict) -> bool:
    """True when the message names the action OPPOSITE to the card's own -
    "reject" against an approve card, or "approve" against a reject one.

    Saying the opposite is never a confirmation of what is showing, and it is
    not merely neutral either: it says the manager does not want the action
    they were being asked to confirm. A question that mentions the other verb
    ("what happens if I reject?") is excluded - it asks, it does not decide.
    """
    if _is_question(query):
        return False
    action = pending.get("action") or ACTION_APPROVE
    says_approve = bool(_APPROVE_VERB_PATTERN.search(query))
    says_reject = bool(_REJECT_VERB_PATTERN.search(query))
    return says_reject if action == ACTION_APPROVE else says_approve


def _confirms_the_card_on_screen(query: str, pending: dict) -> bool:
    """True when the message repeats the card's own instruction rather than
    re-aiming at something else - "approve", "yes approve", "yes approve 265"
    against a card that is already proposing to approve 265.

    Reported bug: the card for request 265 was raised by "yes approve 265",
    and confirming it the same way showed the card AGAIN, forever.
    _is_affirmative refuses any message that names a target, so that the
    re-aim in "yes, approve Priya's instead" is never mistaken for a yes -
    right in general, but it cannot tell a re-aim from a manager restating
    the request they are already looking at.

    This stays narrow. It requires an explicit verb MATCHING the card's own
    action, so nothing executes off a bare noun; a question or a decline
    still wins; and a target that is not this card's falls through to be
    re-read as a fresh instruction, which can only ever raise another card.
    """
    if _is_declining(query) or _is_question(query):
        return False

    action = pending.get("action") or ACTION_APPROVE
    says_approve = bool(_APPROVE_VERB_PATTERN.search(query))
    says_reject = bool(_REJECT_VERB_PATTERN.search(query))
    wanted, opposite = ((says_approve, says_reject) if action == ACTION_APPROVE
                        else (says_reject, says_approve))
    if not wanted or opposite:
        return False

    # Anything that does not point at a DIFFERENT request is about the one on
    # screen - including the card's own button label ("Approve", "Approve
    # Request"), a bare "approve", and the manager restating the request they
    # are already looking at ("yes approve 265", "approve geo3").
    return not _identifies_another_request(query, pending)


# -- Rendering ---------------------------------------------------------------

def _request_type(leave: dict) -> str:
    """AC1/AC2's "Request Type (Leave/Regularization)". erp-api's pending
    rows are leave requests only - see the module docstring's KNOWN GAP.
    Kept as a function so the day regularizations appear on this endpoint,
    this is the single place that has to learn about them."""
    return "Leave"


def _date_range(leave: dict) -> str:
    from_date = leave.get("from_date")
    to_date = leave.get("to_date")
    if from_date and to_date and from_date != to_date:
        return f"{from_date} to {to_date}"
    return from_date or to_date or "-"


def _impacted_days(leave: dict):
    """erp-api returns leave_count as a STRING ("1") on the pending rows.
    Rendered as-is rather than coerced: a manager confirming an action must
    see the system's own number, not this service's interpretation of it."""
    return leave.get("leave_count")


def _confirmation_card(leave: dict, action: str) -> dict:
    """The structured summary AC1/AC2 require, in one place, so the SSE event
    and the text reply cannot drift apart - they are built from this same
    dict. Every AC-required field is present as its own key even when erp-api
    left it empty, so a client rendering the card never has to guess whether
    a missing key means "no value" or "field not implemented"."""
    return {
        "action": action,
        "action_type": "Approve" if action == ACTION_APPROVE else action.title(),
        "leave_request_id": leave.get("id"),
        "employee_id": leave.get("employee_id"),
        "employee_name": leave.get("employee_name"),
        "employee_number": leave.get("employee_number"),
        "request_type": _request_type(leave),
        "leave_type": leave.get("leave_type"),
        "session_type": leave.get("session_type"),
        "from_date": leave.get("from_date"),
        "to_date": leave.get("to_date"),
        "date_range": _date_range(leave),
        "impacted_days": _impacted_days(leave),
        "reason": leave.get("reason"),
        "applied_date": leave.get("applied_date"),
        "requires_confirmation": True,
    }


def _render_confirmation(card: dict) -> str:
    """The accessible text equivalent of the card - the same AC-required
    fields, in the same order, for a plain-text client."""
    request_type_line = f"- Request Type: {card.get('request_type')}"
    if card.get("leave_type"):
        request_type_line += f" ({card['leave_type']})"
    impacted = card.get("impacted_days")
    lines = [
        "Please confirm this action:",
        f"- Employee: {_employee_label(card, default='-')}",
        request_type_line,
        f"- Date Range: {card.get('date_range')}",
        f"- Impacted Days: {impacted if impacted is not None else '-'}",
        f"- Action: {card.get('action_type')}",
    ]
    if card.get("session_type"):
        lines.append(f"- Session: {card['session_type']}")
    if card.get("reason"):
        lines.append(f"- Employee's reason: {card['reason']}")
    lines.append("")
    if card.get("action") == ACTION_REJECT:
        # The ask is for a REASON, not a yes/no - erp-api records it and the
        # employee sees it, so it is the one field this flow must not invent.
        lines.append("Reply with the reason for rejecting it, and I'll submit the "
                     'rejection. Reply "no" to leave it pending instead.')
    else:
        lines.append('Shall I approve it? Reply "yes" to approve, or "no" to leave it pending.')
    return "\n".join(lines)


def _employee_label(*sources, default: str = "That team member") -> str:
    """"Ayush Jio (geo3)" - the resolved name WITH the identifier it was
    resolved from, taken from the first source that carries each.

    A manager who typed "geo3" and is answered about "Ayush Jio" has no way
    to tell whether the right person was resolved. erp-api's ?employee_name=
    search matches the NAME field only, so an employee NUMBER is resolved
    against the team roster by _resolve_target rather than by erp-api - the
    swap from what was typed to what is shown is entirely ours, so it is
    ours to show its working for. Carrying both makes it checkable at a
    glance, which matters most on the text a manager reads before confirming
    a state change.

    Sources are read in order and accept either spelling erp-api uses:
    leave rows say employee_name/employee_number, the /leave/pending/teams
    employee sibling says name/emp_no.
    """
    name = number = None
    for source in sources:
        source = source or {}
        name = name or source.get("employee_name") or source.get("name")
        number = number or source.get("employee_number") or source.get("emp_no")
    if name and number:
        return f"{name} ({number})"
    return name or number or default


def _cell(value) -> str:
    """One table cell. A pipe inside a value would end the column early and
    break every row after it, so the one character markdown reserves here is
    escaped - erp-api's leave_type text is free-form and is not this
    renderer's to trust."""
    return str(value if value not in (None, "") else "-").replace("|", "\\|")


def _render_choice(leaves: list, employee_label: str) -> str:
    """More than one pending request for the resolved employee, and nothing
    in the message says which.

    Rendered as a markdown table (the chat UI renders plain markdown). At
    nine rows the previous bullet list was a wall of text a manager had to
    read linearly to compare dates - which is exactly the comparison this
    question asks them to make. Columns line the values up instead.

    Every row still leads with its request ID, and the closing line shows how
    to use one, because naming an ID is the only reply that resolves this
    unambiguously - nothing here ever guesses, since guessing approves the
    wrong request.
    """
    lines = [
        f"{employee_label} has {len(leaves)} pending leave requests. "
        f"Which one should I approve?",
        "",
        "| Request | Leave Type | Dates | Days |",
        "| --- | --- | --- | --- |",
    ]
    for leave in leaves:
        lines.append(
            f"| #{_cell(leave.get('id'))} | {_cell(leave.get('leave_type') or 'Leave')} "
            f"| {_cell(_date_range(leave))} | {_cell(_impacted_days(leave))} |"
        )
    first_id = leaves[0].get("id") if leaves else None
    lines.append("")
    lines.append(
        f'Reply with the request number - for example "approve request {first_id}".'
        if first_id is not None else
        "Reply with the request number you'd like me to approve."
    )
    return "\n".join(lines)


def _explicit_dates(text: str) -> list:
    """Every calendar date named outright in `text` ("16 sep", "2026-09-16",
    "16/09"). Reuses the attendance family's own resolver so a date means the
    same thing here as everywhere else; never raises."""
    try:
        return date_query_resolver._find_all_explicit_dates(text, _today_in_app_timezone())
    except Exception:
        return []


def _covers_date(leave: dict, when) -> bool:
    """True when `when` falls inside this request's own range."""
    try:
        start = date.fromisoformat(str(leave.get("from_date")))
        end = date.fromisoformat(str(leave.get("to_date") or leave.get("from_date")))
    except (TypeError, ValueError):
        return False
    return start <= when <= end


def _mentions_leave_type(text: str, leave: dict) -> bool:
    """True when `text` names this request's leave type - "short leave" and a
    bare "short" alike, since the trailing "leave" adds nothing."""
    label = str(leave.get("leave_type") or "").strip().lower()
    slug = str(leave.get("leave_type_slug") or "").replace("_", " ").strip().lower()
    for candidate in (label, slug):
        if not candidate:
            continue
        if candidate in text:
            return True
        head = candidate.replace("leave", "").strip()
        if head and re.search(r"\b" + re.escape(head) + r"\b", text):
            return True
    return False


def _mentions_day_count(text: str, leave: dict) -> bool:
    """True when `text` says how many days ("2 days"), matching this row."""
    count = str(leave.get("leave_count") or "").strip()
    if not count:
        return False
    return bool(re.search(r"\b" + re.escape(count) + r"\s*day", text))


def _ordinal_index(text: str):
    """"the second one" -> 1. Word forms ONLY: the table shows request IDs,
    not positions, so a bare digit is an ID (or nothing), never a row number."""
    for table in (individual_report._ORDINAL_WORDS, individual_report._CARDINAL_WORDS):
        hits = [(word, index) for word, index in table.items()
                if re.search(r"\b" + re.escape(word) + r"\b", text)]
        if hits:
            return max(hits, key=lambda hit: len(hit[0]))[1]
    return None


def _match_leave_choice(query: str, leaves: list):
    """Resolve a reply to the "which of these requests?" table against the
    rows that were offered. Returns the chosen row, or None to re-offer.

    Reported: the table was shown for A Khan Test's two pending requests, the
    manager replied "310" - its request ID, printed in the table's first
    column - and the turn fell through to general chat, which echoed
    "Approve request 310." and did nothing.

    Tiers, most specific first. Every tier refuses to guess: one that matches
    two rows resolves nothing and the table is simply re-offered, because the
    cost of guessing is approving the wrong person's leave.

      1. request ID     "310", "#310", "approve request 310"
      2. date           "16 sep", "2026-09-16", "16/09"
      3. leave type     "short leave", "casual", "sick"
      4. day count      "2 days"
      5. position       "the second one" (words only - see _ordinal_index)
    """
    text = (query or "").strip().lower()
    if not text or not leaves:
        return None

    numbers = {int(n) for n in _STANDALONE_NUMBER.findall(text)}
    if numbers:
        by_id = [lv for lv in leaves if lv.get("id") in numbers]
        if len(by_id) == 1:
            return by_id[0]

    for dates in ([d for d in _explicit_dates(text)],):
        if dates:
            by_date = [lv for lv in leaves
                       if any(_covers_date(lv, when) for when in dates)]
            if len(by_date) == 1:
                return by_date[0]

    by_type = [lv for lv in leaves if _mentions_leave_type(text, lv)]
    if len(by_type) == 1:
        return by_type[0]

    by_days = [lv for lv in leaves if _mentions_day_count(text, lv)]
    if len(by_days) == 1:
        return by_days[0]

    index = _ordinal_index(text)
    if index is not None and 0 <= index < len(leaves):
        return leaves[index]

    return None


def _offer_leave_choice(leaves, label, fields, company_id, conversation_id, _finish,
                        preface: str = ""):
    """Show the "which of these requests?" table AND remember it.

    `preface` leads the message when the table is being shown AGAIN after a
    reply that named something not on it, so the manager is told why they are
    seeing it a second time.

    The remembering is the point. Showing the table used to store nothing, so
    the manager's answer arrived with no record that a question had been
    asked: "310" was classified as a general HR message and answered by the
    chat model, which echoed "Approve request 310." and approved nothing.

    Same shape as every other question this node asks (awaiting_confirmation,
    awaiting_rejection_reason, awaiting_employee_selection) - the ask writes
    the state its answer resolves against.
    """
    stored = leave_slot_service.set_manager_action(company_id, conversation_id, {
        "kind": CARD_KIND,
        "step": "awaiting_leave_choice",
        "action": fields.get("action") or ACTION_APPROVE,
        "leaves": list(leaves),
        "requested_query": fields.get("requested_query"),
    })
    message = _render_choice(leaves, label)
    if preface:
        message = f"{preface}\n\n{message}"
    if not stored:
        # The table is on screen with nothing to resolve a reply against.
        # Say so, rather than let the next message fall through and be
        # answered by generic chat - which is exactly what went wrong.
        message += ("\n\nPlease include the request number in your reply - "
                    "I can't hold this shortlist right now.")
    return _finish(message, extra_data=_choice_data(leaves))


def _choice_data(leaves: list) -> dict:
    """The same shortlist as structured rows, so a client can draw its own
    table instead of parsing the markdown one. Mirrors the shape the
    employee-selection step already returns (action_required plus the rows),
    and is purely additive: a client that ignores it still has the text.
    """
    return {
        "action_required": "select_leave_request",
        "leaves": [
            {
                "leave_request_id": lv.get("id"),
                "employee_id": lv.get("employee_id"),
                "employee_name": lv.get("employee_name"),
                "employee_number": lv.get("employee_number"),
                "leave_type": lv.get("leave_type"),
                "session_type": lv.get("session_type"),
                "from_date": lv.get("from_date"),
                "to_date": lv.get("to_date"),
                "date_range": _date_range(lv),
                "impacted_days": _impacted_days(lv),
                "reason": lv.get("reason"),
            }
            for lv in leaves
        ],
    }


# -- Mid-flow entry point (called from classify_node) -------------------------

def resolve_pending_approval_intent(company_id, conversation_id: str, query: str):
    """APPROVAL_INTENT when this turn is answering a confirmation this
    conversation is already waiting on - otherwise None.

    classify_node's single entry point into this feature's state, mirroring
    individual_report.resolve_pending_selection_intent: the state read and
    the matching rule stay owned by the feature rather than being reassembled
    at the call site.

    Hijacks narrowly. A bare "yes" has to land here (nothing else in the
    conversation can interpret it), and so does an explicit change of
    instruction. A manager who changes the subject entirely gets a normal
    answer, and the pending card simply expires with its TTL - which is why
    this returns None rather than "not confirmed" for anything unrecognised.
    """
    state = leave_slot_service.get_manager_action(company_id, conversation_id) or {}
    # regularisation_approval.py stores its own confirmation card under the
    # same manager-action key (one pending confirmation per conversation is
    # the intended behaviour). The kind tag is what keeps a bare "yes"
    # resolving against the card that is actually showing - without it, a yes
    # aimed at a regularization card would be handled here and approve a
    # LEAVE request the manager never saw. Absent means leave: cards written
    # before this tag existed are this feature's.
    if state.get("kind", CARD_KIND) != CARD_KIND:
        return None
    step = state.get("step")
    if step == "awaiting_confirmation":
        if _is_affirmative(query) or _is_declining(query):
            return APPROVAL_INTENT
        # A re-aimed instruction ("approve Priya's instead", "proceed with
        # request 61") belongs here - names_a_target catches the ones that
        # carry no action verb of their own, which would otherwise fall
        # through to normal classification and leave the manager's re-aim
        # answered as some other kind of question.
        # A QUESTION that happens to use the same verb ("what's the approval
        # process?", "did you approve it?") does not - it gets a normal
        # answer, and the card keeps waiting.
        if (mentions_action(query) or names_a_target(query)) and not _is_question(query):
            return APPROVAL_INTENT
        # A bare request ID or a bare name, with no verb at all, while the
        # card is on screen. Both are the manager pointing at a DIFFERENT
        # request - "310", "abc testing" - and both used to fall through to
        # general classification, where the chat model answered from context
        # and nothing was looked up. Re-aiming is this node's job; it keeps
        # the same intent and simply resolves the new target.
        if _looks_like_a_target_reply(query):
            return APPROVAL_INTENT
        # A DATE or a LEAVE TYPE, which names no request directly but picks
        # one out of the pending list - "21 Sept 2026", "casual leave". Same
        # re-aim, resolved by searching rather than by matching a name.
        if _looks_like_a_search_reply(query):
            return APPROVAL_INTENT
        return None
    if step == "awaiting_rejection_reason":
        # The whole message is the reason, so almost anything belongs here -
        # but NOT a question ("what happens if I reject?") and NOT a re-aim at
        # another request, which stay with normal classification exactly as
        # they do on the approve card. A decline still lands here so the node
        # can clear the card and say nothing changed.
        if _is_declining(query):
            return APPROVAL_INTENT
        if _is_question(query) or names_a_target(query):
            return None
        return APPROVAL_INTENT if query.strip() else None
    if step == "awaiting_employee_selection":
        if _match_selection(query, state.get("candidates") or []):
            return APPROVAL_INTENT
        return None
    if step == "awaiting_leave_choice":
        # The answer to the "which of these requests?" table.
        if _match_leave_choice(query, state.get("leaves") or []):
            return APPROVAL_INTENT
        # A reply that TRIED to pick one and named something not on the list -
        # a request number none of them have, or a date or type none of them
        # match. Still an answer to this question, so it belongs here.
        #
        # Reported: the table offered #326 and #324, the manager typed
        # "2222", and the turn fell through to general chat - which wrote
        # "I couldn't find pending request #2222 ... Available pending
        # requests are: ..." as prose, with no intent and no card behind it.
        # Plausible, and entirely improvised.
        #
        # A NAME is deliberately NOT included: at this table a name means
        # "show me that person instead", which is a re-aim and is handled
        # further down as a fresh instruction.
        if _BARE_REQUEST_ID.match((query or "").strip()) or _looks_like_a_search_reply(query):
            return APPROVAL_INTENT
        return None
    if step == "awaiting_approval_target":
        # The node asked "which request?" and this turn is the answer, so the
        # whole message is the target - a name, a code, or a request ID. It
        # cannot be matched against a candidate list the way a selection
        # reply can, because no list was offered; there is only the question.
        #
        # A question of their own ("what happens if I reject?") still gets a
        # normal answer and leaves the ask standing.
        if _is_question(query):
            return None
        return APPROVAL_INTENT if query.strip() else None
    return None


# -- Node --------------------------------------------------------------------

async def leave_approval_node(state: dict, writer: StreamWriter) -> dict:
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    query = state.get("query", "")
    usage_events = list(state.get("usage_events", []))

    def _finish(message: str, finish_intent: str = None, extra_data: dict = None,
                cancelled: bool = False) -> dict:
        data = {"answer": message}
        if extra_data:
            data.update(extra_data)
        # Set AFTER extra_data so the flag always reflects this call, never a
        # stale copy carried along in a card payload.
        data[CANCEL_APPROVE_FLAG] = bool(cancelled)
        writer({"type": "done", "intent": finish_intent or APPROVAL_INTENT, "is_hr": True,
                "data": data, "message": message, "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    def _refuse(message: str, finish_intent: str = None, extra_data: dict = None) -> dict:
        """Every "I'm not doing that" exit. It CLEARS any pending
        confirmation on the way out, which is the whole reason this is one
        function: leaving a stale approval card alive after refusing a
        different instruction is how a later bare "yes" ends up approving
        something the manager had already moved on from."""
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        return _finish(message, finish_intent=finish_intent, extra_data=extra_data)

    # -- Gate: is the caller a manager? --------------------------------------
    # Same tri-state contract as individual_report_node, resolved by
    # hr_graph.manager_gate_node ahead of classification. The fallback is not
    # dead code: this node stays callable on its own, and a permission gate
    # that passes when its input is missing is the wrong failure mode - the
    # more so here, where passing it means changing another employee's record.
    resolved = state.get("is_manager")
    if resolved is None and not state.get("is_manager_jwt"):
        try:
            context_result = await erp_client.get_leave_context(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
            )
        except erp_client.ErpApiTimeout:
            return _finish("I couldn't verify your access in time - please try again in a moment.")
        except erp_client.ErpApiUnavailable:
            return _finish(_ERP_UNAVAILABLE_MESSAGE)
        resolved = (context_result["body"].get("data") or {}).get("is_manager", False)
    elif resolved is None:
        resolved = True

    if resolved == MANAGER_UNKNOWN:
        return _finish("I couldn't verify your access in time - please try again in a moment.")
    if not resolved:
        return _refuse(NOT_A_MANAGER_MESSAGE, finish_intent=access_notice.RESTRICTED_INTENT,
                       extra_data=access_notice.refuse(writer, "leave_approval", NOT_A_MANAGER_MESSAGE))

    pending = leave_slot_service.get_manager_action(company_id, conversation_id) or {}
    # A card belonging to the regularization flow is not this node's to read,
    # answer, or clear - same reasoning as the kind check in
    # resolve_pending_approval_intent above.
    if pending and pending.get("kind", CARD_KIND) != CARD_KIND:
        pending = {}

    # -- The rejection REASON turn (FR-08.3) --------------------------------
    # Armed by a reject card. The reason is the confirmation: it is explicit,
    # deliberate, and erp-api stores it for the employee to read. A decline
    # still wins, and anything that re-aims at another request falls through
    # to be re-read as a fresh instruction below.
    if pending.get("step") == "awaiting_rejection_reason":
        if _is_declining(query) and not names_a_target(query):
            leave_slot_service.clear_manager_action(company_id, conversation_id)
            card = pending.get("card") or {}
            employee = card.get("employee_name")
            whose = f"{employee}'s" if employee else "that"
            return _finish(
                f"No problem - I've left {whose} request pending. Nothing has been changed.",
                cancelled=True,
            )
        if not names_a_target(query) and not _is_question(query):
            reason = query.strip()
            if len(reason) < _MIN_REJECTION_REASON:
                # erp-api enforces this too; asking here keeps the card armed
                # instead of spending a call to be told the same thing.
                return _finish(
                    "Please give me a bit more detail for the rejection - the employee "
                    "sees this reason. Reply with the reason, or \"no\" to leave the "
                    "request pending."
                )
            return await _execute_rejection(
                pending, reason, bearer_token, company_id, conversation_id, writer, _finish,
            )

    # -- The confirming turn (FR-08.3) --------------------------------------
    if pending.get("step") == "awaiting_confirmation":
        if _is_affirmative(query) or _confirms_the_card_on_screen(query, pending):
            return await _execute_approval(
                pending, query, bearer_token, company_id, conversation_id, writer, _finish,
            )
        # A decline wins UNLESS the message names a request of its own - the
        # same discriminator _is_affirmative uses, so both branches answer one
        # question: "is this about the card on screen, or about something
        # else?". "no, approve Priya's instead" declines AND re-aims, and the
        # re-aim is the part that needs acting on; "don't approve it" names
        # nothing new and is simply a no.
        #
        # This was previously gated on `not mentions_action(query)`, which
        # matched the bare verb: "don't approve it" contains "approve", so the
        # explicit refusal was re-read as a fresh instruction and answered
        # with the SAME confirmation card, re-armed. Nothing executed, but the
        # manager said don't and was asked to confirm again.
        if _is_declining(query) and not names_a_target(query):
            leave_slot_service.clear_manager_action(company_id, conversation_id)
            card = pending.get("card") or {}
            employee = card.get("employee_name")
            whose = f"{employee}'s" if employee else "that"
            return _finish(
                f"No problem - I've left {whose} request pending. Nothing has been changed.",
                cancelled=True,
            )
        # The OPPOSITE action, aimed at the card on screen: "reject", "deny",
        # "decline it" while an APPROVE card is waiting.
        #
        # Live hazard this closes. That message used to fall through to be
        # re-read as a fresh instruction, which rebuilt the SAME approve card
        # and left it armed - so the manager said "reject" and the very next
        # "yes" approved the request. Verified: approve 310 -> "reject" ->
        # "yes" executed the approval.
        #
        # Saying the opposite action is at minimum "not this approval", so
        # the card is stood down here. What the turn then does is left to the
        # normal path below: with rejection enabled it arms a reject card,
        # and with it disabled it says where rejection lives. Either way
        # there is no longer an approve card behind it collecting a "yes".
        if _asks_the_opposite_action(query, pending):
            logger.info("[LeaveApproval] opposite action asked for at the card - "
                        "standing the pending %s down", pending.get("action"))
            leave_slot_service.clear_manager_action(company_id, conversation_id)
            pending = {}

        # Neither a yes nor a plain no. Anything else is re-read as a fresh
        # instruction ("approve Priya's instead") below, which can only ever
        # produce another confirmation card - never an execution.

    # -- "cancel a khan test" - call the approval off ------------------------
    # Answered here, not by the caller's own cancel-leave flow, and it never
    # cancels a leave: calling an APPROVAL off just leaves the request as it
    # was. Says so plainly, naming the person, so a manager who expected
    # something to happen to that request is not left guessing.
    if is_cancel_approval_instruction(query):
        card = pending.get("card") or {}
        subject = card.get("employee_name")
        if not subject:
            # Nothing pending from this conversation - name whoever the
            # message itself named, so the reply is still about them.
            subject = _stood_down_subject(query)
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        whose = f"{subject}'s" if subject else "that"
        logger.info("[LeaveApproval] approval called off for %r", subject)
        return _finish(
            f"No problem - I've stopped the approval. {whose} leave request is "
            f"unchanged and still pending.",
            finish_intent="leave_approval_stood_down",
            cancelled=True,
        )

    # -- Which request? ------------------------------------------------------
    today = _today_in_app_timezone()

    # The reply to the "which of these requests?" table. Resolved straight to
    # the chosen row - it is one of the rows already fetched and shown, so
    # there is nothing left to look up and no reason to ask erp-api again.
    if pending.get("step") == "awaiting_leave_choice":
        offered = pending.get("leaves") or []
        chosen = _match_leave_choice(query, offered)
        if chosen is not None:
            return _build_confirmation(
                chosen, pending.get("requested_query") or query,
                company_id, conversation_id, writer, _finish,
                action=pending.get("action") or ACTION_APPROVE,
            )
        # Named a request that is not on this table. Say so and show the
        # table again, as a real card - rather than letting the turn fall
        # through to general chat, which improvised the same answer as prose
        # with nothing behind it.
        if offered and _BARE_REQUEST_ID.match((query or "").strip()):
            asked_for = re.sub(r"\D", "", query)
            label = _employee_label(offered[0])
            # The plain name for the possessive - _employee_label carries the
            # employee number too ("Rudraveer (FNF-004)"), which reads badly
            # with an apostrophe hung off the bracket.
            whose = offered[0].get("employee_name") or label
            logger.info("[LeaveApproval] request #%s is not on the offered shortlist",
                        asked_for)
            return _offer_leave_choice(
                offered, label,
                {"action": pending.get("action") or ACTION_APPROVE,
                 "requested_query": pending.get("requested_query")},
                company_id, conversation_id, _finish,
                preface=(f"Request #{asked_for} isn't one of {whose}'s pending "
                         f"requests."),
            )

    selected_candidate = None
    if pending.get("step") == "awaiting_employee_selection":
        selected_candidate = _match_selection(query, pending.get("candidates") or [])

    # The reply to "which request would you like me to approve?". Read here,
    # deterministically, rather than by sending the bare answer back through
    # extract_leave_approval_fields - which is what produced the reported loop.
    #
    # That extractor only ever sees the message text, never the question it is
    # answering, and is asked for "the team member whose request is being
    # acted on". A bare "A Khan Test" carries no action verb and no target
    # wording, so it comes back employee_name=None - landing straight back on
    # the same ask. The manager retyped the name three times and got the
    # identical sentence three times.
    #
    # It also fails CLOSED in the same direction: every exception in there
    # returns the empty field set, so while the LLM is rate-limited the ask
    # can never be answered by anybody at all. Reading the answer here takes
    # the LLM out of the one turn that has to work.
    target_reply_fields = None
    if selected_candidate is None and pending.get("step") == "awaiting_approval_target":
        target_reply_fields = _fields_from_target_reply(query, pending)

    # A bare ID or bare name typed AT the confirmation card - "310", "abc
    # testing" - re-aims it. Read here rather than through the LLM extractor
    # for the same reason the other answer turns are: the extractor sees the
    # message without the card it is answering, and returns its empty field
    # set on any failure, which lands back on the same prompt.
    if (selected_candidate is None and target_reply_fields is None
            and pending.get("step") == "awaiting_confirmation"
            and _looks_like_a_target_reply(query)):
        logger.info("[LeaveApproval] re-aiming the pending card at %r", query[:60])
        target_reply_fields = _fields_from_target_reply(query, pending)

    # A DATE or LEAVE TYPE at the card ("21 Sept 2026", "casual leave").
    # Neither names a request outright, so it is SEARCHED for among the
    # pending requests instead - this employee's first, then the wider team.
    if (selected_candidate is None and target_reply_fields is None
            and pending.get("step") in ("awaiting_confirmation", "awaiting_approval_target")
            and _looks_like_a_search_reply(query)):
        found, error_response = await _search_pending_for_reply(
            query, pending, bearer_token, company_id, conversation_id, writer, _finish)
        if error_response is not None:
            return error_response
        if found is not None:
            return _build_confirmation(
                found, query, company_id, conversation_id, writer, _finish,
                action=pending.get("action") or ACTION_APPROVE,
            )

    if target_reply_fields is not None:
        fields = target_reply_fields
        requested_query = pending.get("requested_query") or query
    elif selected_candidate is not None:
        # The selection reply names a person, not an action - the action and
        # the original wording are replayed from the state written when the
        # cards were shown, so answering "the second one" doesn't lose what
        # was being asked.
        fields = {"action": pending.get("action") or ACTION_APPROVE,
                  "leave_request_id": None,
                  "employee_id": selected_candidate.get("employee_id"),
                  "employee_name": None, "uses_pronoun": False, "targets_multiple": False}
        requested_query = pending.get("requested_query") or query
    else:
        fields, extraction_usage = await ai_service.extract_leave_approval_fields(query, today)
        if extraction_usage:
            usage_events.append({"source": "leave_approval_extraction", "usage": extraction_usage})
        requested_query = query

    # Rejection is now a real path: erp-api gained POST .../reject, so the
    # blanket refusal that used to sit here (there was no endpoint to call)
    # would now be declining something the system can actually do. The action
    # is carried through resolution and arms a REJECT card, which asks for the
    # reason erp-api requires rather than a yes.
    requested_action = ACTION_REJECT if fields.get("action") == ACTION_REJECT else ACTION_APPROVE
    if selected_candidate is not None or target_reply_fields is not None:
        requested_action = pending.get("action") or requested_action

    # Approve-only mode (the default — see LEAVE_REJECTION_ENABLED). Checked
    # here rather than at the card or the erp-api call because this is the one
    # place every route converges on: a fresh "reject X's leave", a reply that
    # lands on an armed reject card, and a re-aim from approve to reject all
    # pass through this line. Gating further downstream would leave one of
    # those three able to reject anyway.
    #
    # The pending card is cleared first: leaving a reject card armed after
    # declining it is how a later bare "yes" acts on something the manager was
    # just told could not be done here.
    if requested_action == ACTION_REJECT and not LEAVE_REJECTION_ENABLED:
        logger.info("[LeaveApproval] rejection requested but LEAVE_REJECTION_ENABLED is off")
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        return _finish(REJECTION_UNAVAILABLE_MESSAGE,
                       finish_intent="leave_approval_restricted")

    # FR-07.5 - bulk belongs on the dashboard, and this is where the manager
    # is sent there.
    #
    # It used to answer with BULK_MESSAGE alone: "I can only approve one at a
    # time", with no way forward. The Bulk Approvals page exists for exactly
    # this, so the same navigation card the complex-manager route builds is
    # returned instead - the manager gets a link rather than a dead end.
    #
    # Done HERE rather than only in classify_node so the outcome is the same
    # whichever way the turn arrived: the deterministic bulk hook, the LLM
    # picking manager_leave_approval, or a reply landing on a pending
    # approval card. The refusal still CLEARS that pending card first - a
    # stale card left armed is how a later bare "yes" approves something the
    # manager had moved on from.
    if fields.get("targets_multiple"):
        logger.info("[LeaveApproval] bulk action requested - routing to the Bulk Approvals page")
        leave_slot_service.clear_manager_action(company_id, conversation_id)

        navigation = route_complex_manager_task(BULK_APPROVALS_INTENT)
        if navigation:
            writer({"type": "navigation_card", "data": navigation})
            return _finish(navigation["message"],
                           finish_intent=BULK_APPROVALS_INTENT,
                           extra_data={"navigation": navigation})

        # No configured route (should not happen - the intent is in the
        # router's own config). Never invent a destination; say the original
        # thing instead.
        return _finish(BULK_MESSAGE, finish_intent="leave_approval_bulk_unsupported")

    writer({"type": "fetching_leave_approval",
            "message": "Looking up that leave request..."})
    target, error_response = await _resolve_target(
        fields, query, pending, bearer_token, company_id, conversation_id, writer, _finish,
    )
    if error_response is not None:
        return error_response

    # -- Build the confirmation card and STOP (AC1, AC3) ---------------------
    return _build_confirmation(
        target, requested_query, company_id, conversation_id, writer, _finish,
        action=requested_action,
    )


#: "61", "#61", "request 61", "leave request #61", "LR-61" - a request the
#: manager identified by number rather than by whose it is.
_TARGET_REPLY_REQUEST_ID = re.compile(
    r"^(?:(?:leave\s+)?(?:request|application|lr)\s*[-#]?\s*)?#?\s*(\d{1,10})\s*$",
    re.IGNORECASE,
)


def _fields_from_target_reply(query: str, pending: dict) -> dict:
    """The answer to "which request?", as the field set the rest of this
    module already knows how to resolve.

    The whole message IS the target - that is what was asked for - so it is
    taken as the employee name unless it reads as a bare request ID.

    The ACTION comes from the stored state, never from the reply: the manager
    said "approve" on the turn that raised the question, and should not have
    to say it again to answer it.
    """
    text = (query or "").strip()
    match = _TARGET_REPLY_REQUEST_ID.match(text)
    request_id = int(match.group(1)) if match else None
    return {
        "action": pending.get("action") or ACTION_APPROVE,
        "leave_request_id": request_id,
        "employee_id": None,
        "employee_name": None if request_id else (text or None),
        "uses_pronoun": False,
        "targets_multiple": False,
    }


async def _search_pending_for_reply(query, pending, bearer_token, company_id,
                                    conversation_id, writer, _finish):
    """(leave_row, error_response) for a DATE or LEAVE TYPE typed at a card.

    Searched, not guessed. The reply names no request directly, so the
    pending list is what decides which one it means:

      1. the card's own employee first - "21 Sept 2026" after a card for
         Rudraveer almost always means Rudraveer's request on that date, and
         scoping there keeps an identical date on somebody else's request
         from making it ambiguous;
      2. then the whole team, for "approve the sick leave one" style replies
         that move to a different person entirely.

    Ambiguity is never resolved by picking: two matches re-offer the choice
    table, and none says so plainly. _match_leave_choice does the matching,
    so a date, a type, a day count and an ordinal all mean here exactly what
    they mean when answering that table.
    """
    card = pending.get("card") or {}
    scopes = []
    if card.get("employee_id"):
        scopes.append({"employee_id": card["employee_id"]})
    scopes.append({})   # team-wide

    seen_rows = []
    for scope in scopes:
        try:
            result = await erp_client.get_team_pending_leaves(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
                **scope,
            )
        except erp_client.ErpApiTimeout:
            return None, _finish(_ERP_TIMEOUT_MESSAGE)
        except erp_client.ErpApiUnavailable:
            return None, _finish(_ERP_UNAVAILABLE_MESSAGE)
        if result.get("http_status") == 403:
            continue

        data = (result.get("body") or {}).get("data") or {}
        rows = data.get("leaves") or []
        if not rows:
            continue
        seen_rows = rows

        chosen = _match_leave_choice(query, rows)
        if chosen is not None:
            logger.info("[LeaveApproval] %r resolved to request #%s from the pending list",
                        query[:40], chosen.get("id"))
            return chosen, None

    # Nothing matched anywhere. Say so against the list that was searched,
    # rather than leaving the manager with a card they did not ask about.
    if seen_rows:
        label = _employee_label(seen_rows[0]) if len(
            {r.get("employee_id") for r in seen_rows}) == 1 else "Your team"
        return None, _offer_leave_choice(
            seen_rows, label, {"action": pending.get("action") or ACTION_APPROVE},
            company_id, conversation_id, _finish)
    return None, _finish(
        "I couldn't find a pending leave request matching that. "
        "Tell me the request number, or the team member's name."
    )


async def _resolve_target(fields, query, pending, bearer_token, company_id,
                          conversation_id, writer, _finish):
    """(leave_row, error_response) - exactly one of the two is not None.

    Resolution order is narrowest-first: an explicit request ID beats an
    employee, an employee beats "it". Anything that stays ambiguous ASKS;
    nothing here picks a request on the manager's behalf, because the cost of
    guessing is approving the wrong person's leave.

    Recursive on the single-name-match path, which is why the progress event
    is the CALLER's to emit: from in here it would fire twice for one lookup.
    """
    request_id = fields.get("leave_request_id")
    employee_id = fields.get("employee_id")
    employee_name = fields.get("employee_name")

    # "approve it" / "approve his request" - resolve against the request this
    # conversation was just looking at (FR-07.3's lookup, which is the story
    # this one follows). Only ever ONE remembered request is acted on; a
    # remembered list of several is disambiguated, not picked from.
    if not request_id and not employee_id and not employee_name:
        report_state = leave_slot_service.get_report_state(company_id, conversation_id) or {}
        remembered = report_state.get("last_leave_requests") or []
        if len(remembered) == 1:
            return remembered[0], None
        if len(remembered) > 1:
            # "approve casual leave" names WHICH of the remembered requests
            # is meant, the same way it does for a single employee's list
            # further down - so narrow before asking the manager to pick
            # something already on their screen.
            #
            # Guarded on the rows all belonging to ONE person, which the
            # per-employee branch gets for free and this one does not: a
            # remembered TEAM list spans people, and picking the only casual
            # leave out of it would choose an employee the manager never
            # named. That is the one mistake this module is built to avoid,
            # so a mixed list is disambiguated rather than narrowed.
            owners = {str(lv.get("employee_id") or lv.get("employee_name") or "")
                      for lv in remembered}
            if len(owners) == 1:
                by_type = [lv for lv in remembered
                           if _mentions_leave_type(query.lower(), lv)]
                if len(by_type) == 1:
                    logger.info("[LeaveApproval] narrowed %d remembered requests to #%s "
                                "by leave type", len(remembered), by_type[0].get("id"))
                    return by_type[0], None
            label = _employee_label(remembered[0])
            return None, _offer_leave_choice(
                remembered, label, fields, company_id, conversation_id, _finish)
        last_employee = report_state.get("last_employee") or {}
        if last_employee.get("employee_id"):
            employee_id = last_employee["employee_id"]
        else:
            # Record the ask, so the manager's next message is read as its
            # ANSWER rather than as a fresh, target-less instruction. Without
            # this the reply had nothing to attach to and the same question
            # came straight back, indefinitely.
            leave_slot_service.set_manager_action(company_id, conversation_id, {
                "kind": CARD_KIND,
                "step": "awaiting_approval_target",
                "action": fields.get("action") or ACTION_APPROVE,
                "requested_query": query,
            })
            return None, _finish(
                "Which request would you like me to approve? Tell me the team "
                "member's name, or the request ID."
            )

    try:
        result = await erp_client.get_team_pending_leaves(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
            employee_id=employee_id, employee_name=employee_name,
        )
    except erp_client.ErpApiTimeout:
        return None, _finish(_ERP_TIMEOUT_MESSAGE)
    except erp_client.ErpApiUnavailable:
        return None, _finish(_ERP_UNAVAILABLE_MESSAGE)

    if result.get("http_status") == 403:
        return None, _finish(NOT_IN_YOUR_TEAM_MESSAGE)

    body = result.get("body") or {}
    data = body.get("data") or {}

    if data.get("action_required") == "select_employee":
        candidates = data.get("employees") or []
        roster = list(candidates)
        unmatched_term = False
        if data.get("search_matched") is False and candidates:
            # erp-api's ?employee_name= search matches the NAME field only, so
            # an employee NUMBER ("geo3") comes back search_matched=false even
            # when that person is squarely on the caller's team - the roster
            # attached to the no-match contains them, listed under their
            # employee_name ("Ayush Jio"). Without this, "approve geo3's leave
            # request" is refused as out-of-team for a request the manager
            # plainly owns. Same resolution individual_report.py already does
            # on the read path, reused rather than restated so both features
            # agree on what "geo3" refers to.
            #
            # This cannot widen scope: the roster IS erp-api's statement of
            # the caller's permitted set, so narrowing it can only ever land
            # inside that set, and the narrowed rows still go back through a
            # fresh employee_id lookup below (and, on approval, erp-api's own
            # team check) rather than being trusted from here.
            candidates = individual_report._resolve_from_roster(employee_name, candidates)
            if candidates:
                logger.info("[LeaveApproval] resolved %r from team roster (%d match(es))",
                            employee_name, len(candidates))
            else:
                # Nothing on the roster reads like the term - not even
                # approximately (see _nearest_roster_matches). Offer the team
                # instead of dead-ending.
                #
                # This used to answer NOT_IN_YOUR_TEAM_MESSAGE, on the
                # reasoning that showing the roster would reveal whether a
                # named person exists in scope. It reveals nothing of the
                # kind: erp-api returns search_matched=false WITH the same
                # roster for gibberish, for a typo, and for a real employee
                # outside the team alike, so all three still look identical
                # from outside. individual_report.py's read path already made
                # exactly this call, for exactly this reason; this aligns the
                # approve path with it rather than leaving one feature
                # helpful and the other a dead end.
                #
                # It matters most for a typo: "approve akhan" for "A Khan
                # Test" was simply refused, with nothing to act on next.
                logger.info("[LeaveApproval] %r matched nobody - offering the team roster",
                            employee_name)
                candidates = roster
                unmatched_term = True
        if not candidates:
            return None, _finish(NOT_IN_YOUR_TEAM_MESSAGE)
        if unmatched_term:
            # Never auto-resolve an UNMATCHED term, even onto a one-person
            # team: that would act on somebody the manager never named.
            stored = leave_slot_service.set_manager_action(company_id, conversation_id, {
                "kind": CARD_KIND,
                "step": "awaiting_employee_selection",
                "action": fields.get("action") or ACTION_APPROVE,
                "candidates": candidates,
                "requested_query": query,
            })
            writer({"type": "employee_selection",
                    "data": {"action_required": "select_employee",
                             "search_matched": False, "employees": candidates}})
            message = individual_report._render_selection_prompt(candidates,
                                                                 unmatched_term=True)
            if not stored:
                message += ("\n\nPlease include their full name or employee ID in your reply - "
                            "I can't hold the shortlist right now.")
            return None, _finish(message, extra_data={"action_required": "select_employee",
                                                      "search_matched": False,
                                                      "employees": candidates})
        if len(candidates) == 1:
            # A name search that unambiguously hit ONE person still comes
            # back as the "select one" shape rather than the record - the
            # same erp-api behaviour individual_report.py handles. Re-resolve
            # by the id instead of bouncing a one-item menu back.
            return await _resolve_target(
                {**fields, "employee_id": candidates[0].get("employee_id"), "employee_name": None},
                query, pending, bearer_token, company_id, conversation_id, writer, _finish,
            )
        stored = leave_slot_service.set_manager_action(company_id, conversation_id, {
            "step": "awaiting_employee_selection",
            "action": ACTION_APPROVE,
            "candidates": candidates,
            "requested_query": query,
        })
        writer({"type": "employee_selection",
                "data": {"action_required": "select_employee", "employees": candidates}})
        message = individual_report._render_selection_prompt(candidates)
        if not stored:
            message += ("\n\nPlease include their full name or employee ID in your reply - "
                        "I can't hold the shortlist right now.")
        return None, _finish(message, extra_data={"action_required": "select_employee",
                                                  "employees": candidates})

    leaves = data.get("leaves") or []

    if request_id is not None:
        # An explicit ID is checked against the caller's OWN pending list
        # rather than posted straight to erp-api. Both would be refused by
        # erp-api's team check, but only this order lets the confirmation
        # card show real details before anything is executed - and AC1 needs
        # those details.
        match = next((lv for lv in leaves if str(lv.get("id")) == str(request_id)), None)
        if match is None:
            return None, _finish(NOT_IN_YOUR_TEAM_MESSAGE)
        return match, None

    if not leaves:
        label = _employee_label(data.get("employee"), {"name": employee_name})
        return None, _finish(f"{label} has no pending leave requests to approve.")

    if len(leaves) > 1:
        # A leave TYPE named in the instruction narrows it before anyone is
        # asked to choose. "approve abc testing sick leave" says which of
        # their requests is meant, so asking "which one?" would be asking for
        # something already on the screen.
        #
        # Only when it leaves exactly ONE: naming a type that still matches
        # two requests has not resolved anything, and the table is the right
        # answer to that.
        by_type = [lv for lv in leaves if _mentions_leave_type(query.lower(), lv)]
        if len(by_type) == 1:
            logger.info("[LeaveApproval] narrowed %d pending requests to #%s by leave type",
                        len(leaves), by_type[0].get("id"))
            return by_type[0], None

        label = _employee_label(leaves[0], data.get("employee"))
        return None, _offer_leave_choice(
            leaves, label, fields, company_id, conversation_id, _finish)

    return leaves[0], None


def _build_confirmation(leave, requested_query, company_id, conversation_id, writer, _finish,
                        action=ACTION_APPROVE):
    """Shows the summary and STOPS. No erp-api write happens on this turn -
    that is AC3, and it is a property of this function returning before any
    such call exists on the path, not of a flag checked later.

    Both decisions arm through here, so "nothing executes on the turn that
    proposes it" holds for reject exactly as it does for approve.
    """
    is_reject = action == ACTION_REJECT
    card = _confirmation_card(leave, action)

    stored = leave_slot_service.set_manager_action(company_id, conversation_id, {
        "kind": CARD_KIND,
        # Reject waits for a REASON, not a yes: erp-api requires one, and the
        # reason doubles as the explicit confirmation FR-08.3 wants. A written
        # sentence is stronger evidence of intent than "yes" and cannot be
        # produced by reflex.
        "step": "awaiting_rejection_reason" if is_reject else "awaiting_confirmation",
        "action": action,
        "leave_request_id": leave.get("id"),
        "card": card,
        "requested_query": requested_query,
    })
    if not stored:
        # Without the stored action there is nothing for the reply to resolve
        # against, and re-deriving it from the confirming message is exactly
        # what FR-08.3 forbids ("yes" names no request). Say so instead of
        # showing a card whose confirmation would silently do nothing.
        return _finish(
            "I can't hold this action long enough to confirm it right now - "
            f"please {action} this request in the HR portal instead. Nothing has been changed.",
            finish_intent="leave_approval_unavailable",
        )

    writer({"type": "leave_approval_confirmation", "data": card})
    return _finish(_render_confirmation(card), extra_data=card)


async def _execute_rejection(pending, rejection_reason, bearer_token, company_id,
                             conversation_id, writer, _finish):
    """The second path that changes state, reachable only from a stored
    awaiting_rejection_reason written by a previous turn.

    Mirrors _execute_approval deliberately - same clear-before-write ordering,
    same audit-on-every-outcome, same catch-all - so the two decisions cannot
    drift into different safety properties.
    """
    card = pending.get("card") or {}
    leave_request_id = pending.get("leave_request_id")

    if leave_request_id is None:
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        return _finish("I've lost track of which request that was - could you name it again? "
                       "Nothing has been changed.")

    cleared = leave_slot_service.clear_manager_action(company_id, conversation_id)
    if not cleared:
        cleared = leave_slot_service.clear_manager_action(company_id, conversation_id)
    if not cleared:
        logger.error(
            "[LeaveApproval] could not clear pending action before rejecting "
            "(leave_request_id=%s, conversation_id=%s) - refusing rather than "
            "risking a repeatable rejection", leave_request_id, conversation_id,
        )
        return _finish(
            "I can't safely confirm this action right now - please reject this "
            "request in the HR portal instead. Nothing has been changed.",
            finish_intent="leave_approval_unavailable",
        )

    writer({"type": "submitting_leave_approval", "message": "Rejecting that leave request..."})

    async def _log(executed, erp_status, erp_message, approver=None):
        await audit_log_service.log_leave_approval(
            action=ACTION_REJECT,
            leave_request_id=leave_request_id,
            executed=executed,
            confirmation_query=rejection_reason,
            requested_query=pending.get("requested_query"),
            employee_id=card.get("employee_id"),
            employee_name=card.get("employee_name"),
            approver_id=(approver or {}).get("id"),
            approver_name=(approver or {}).get("name"),
            erp_status=erp_status,
            erp_message=erp_message,
            company_id=company_id,
            conversation_id=conversation_id,
        )

    try:
        result = await erp_client.reject_leave_request(
            bearer_token, leave_request_id, rejection_reason,
            company_id=company_id, conversation_id=conversation_id,
        )
    except erp_client.ErpApiTimeout:
        await _log(False, None, "erp-api timeout - outcome unknown")
        return _finish("I couldn't reach the HR system in time to reject this. "
                       "Please check the request in the HR portal before trying again.")
    except erp_client.ErpApiUnavailable:
        await _log(False, None, "erp-api unavailable")
        return _finish(_ERP_UNAVAILABLE_MESSAGE)
    except Exception as e:
        logger.exception(
            "[LeaveApproval] unexpected error rejecting leave_request_id=%s: %s",
            leave_request_id, e,
        )
        await _log(False, None, f"unexpected error - outcome unknown: {type(e).__name__}: {e}")
        return _finish(
            "Something went wrong while I was rejecting that, and I can't tell "
            "whether it went through. Please check the request in the HR portal "
            "before trying again.",
            finish_intent="leave_approval_failed",
        )

    body = result.get("body") or {}
    http_status = result.get("http_status")
    erp_message = body.get("message")

    if not body.get("success", False):
        await _log(False, http_status, erp_message)
        logger.info("[LeaveApproval] erp-api refused rejection | status=%s | message=%s",
                    http_status, erp_message)
        return _finish(
            _refusal_sentence(erp_message, NOT_IN_YOUR_TEAM_MESSAGE),
            finish_intent="leave_approval_failed",
        )

    rejected = body.get("data") or {}
    await _log(True, http_status, erp_message, approver=rejected.get("decided_by")
               or rejected.get("approved_by") or {})

    employee = rejected.get("employee_name") or card.get("employee_name") or "That team member"
    leave_type = rejected.get("leave_type") or card.get("leave_type") or "leave"
    span = _date_range(rejected) if rejected.get("from_date") else card.get("date_range")
    message = (
        f"Rejected - {employee}'s {leave_type} request ({span}) is now "
        f"{rejected.get('status_name') or 'rejected'}. The reason was recorded and "
        f"the action has been logged."
    )

    writer({"type": "leave_approval_success", "data": {**rejected, "message": message}})

    return _finish(message, finish_intent="leave_approval_success", extra_data=rejected)


async def _execute_approval(pending, confirmation_query, bearer_token, company_id,
                            conversation_id, writer, _finish):
    """The ONLY path that changes state, reachable only from a stored
    awaiting_confirmation written by a previous turn."""
    card = pending.get("card") or {}
    leave_request_id = pending.get("leave_request_id")

    # Defensive: a state without an id cannot identify what to approve, and
    # the one thing that must never happen here is approving something else.
    if leave_request_id is None:
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        return _finish("I've lost track of which request that was - could you name it again? "
                       "Nothing has been changed.")

    # Cleared BEFORE the call, not after: if the approval succeeds and the
    # clear then fails, the state still says awaiting_confirmation and the
    # manager's next "yes" re-approves. Clearing first makes the failure mode
    # a second "yes" that finds nothing pending (harmless) instead of a
    # duplicate write.
    cleared = leave_slot_service.clear_manager_action(company_id, conversation_id)
    if not cleared:
        cleared = leave_slot_service.clear_manager_action(company_id, conversation_id)
    if not cleared:
        logger.error(
            "[LeaveApproval] could not clear pending action before executing "
            "(leave_request_id=%s, conversation_id=%s) - refusing rather than "
            "risking a repeatable approval", leave_request_id, conversation_id,
        )
        return _finish(
            "I can't safely confirm this action right now - please approve this "
            "request in the HR portal instead. Nothing has been changed.",
            finish_intent="leave_approval_unavailable",
        )

    writer({"type": "submitting_leave_approval", "message": "Approving that leave request..."})

    async def _log(executed, erp_status, erp_message, approver=None):
        await audit_log_service.log_leave_approval(
            action=ACTION_APPROVE,
            leave_request_id=leave_request_id,
            executed=executed,
            confirmation_query=confirmation_query,
            requested_query=pending.get("requested_query"),
            employee_id=card.get("employee_id"),
            employee_name=card.get("employee_name"),
            approver_id=(approver or {}).get("id"),
            approver_name=(approver or {}).get("name"),
            erp_status=erp_status,
            erp_message=erp_message,
            company_id=company_id,
            conversation_id=conversation_id,
        )

    try:
        result = await erp_client.approve_leave_request(
            bearer_token, leave_request_id,
            company_id=company_id, conversation_id=conversation_id,
        )
    except erp_client.ErpApiTimeout:
        # Logged as an attempt, NOT as an outcome: a timeout means erp-api
        # may or may not have applied it, and the audit row says exactly that
        # rather than asserting either way.
        await _log(False, None, "erp-api timeout - outcome unknown")
        return _finish("I couldn't reach the HR system in time to approve this. "
                       "Please check the request in the HR portal before trying again.")
    except erp_client.ErpApiUnavailable:
        await _log(False, None, "erp-api unavailable")
        return _finish(_ERP_UNAVAILABLE_MESSAGE)
    except Exception as e:
        # Deliberately broad, and deliberately here rather than anywhere else
        # in this module. This is the ONE point where the pending card has
        # already been cleared and erp-api may or may not have applied the
        # approval - so an exception escaping from here costs the manager
        # both the answer AND the card: the graph dies, the stream ends with
        # a bare blocked frame carrying no message, and their next "yes" has
        # nothing left to confirm.
        #
        # That is not hypothetical. approve_leave_request passed a kwarg
        # _request did not accept, so every real confirmation raised
        # TypeError right here and reached a manager as a blank failure with
        # no way to tell whether their approval had gone through.
        #
        # Treated exactly like the timeout above, for the same reason: the
        # outcome is genuinely UNKNOWN, the audit row says so rather than
        # asserting either way, and the manager is pointed at the portal to
        # check. Logged with exception() because unlike the two branches
        # above, anything landing here is a bug in this service.
        logger.exception(
            "[LeaveApproval] unexpected error approving leave_request_id=%s: %s",
            leave_request_id, e,
        )
        await _log(False, None, f"unexpected error - outcome unknown: {type(e).__name__}: {e}")
        return _finish(
            "Something went wrong while I was approving that, and I can't tell "
            "whether it went through. Please check the request in the HR portal "
            "before trying again.",
            finish_intent="leave_approval_failed",
        )

    body = result.get("body") or {}
    http_status = result.get("http_status")
    erp_message = body.get("message")

    if not body.get("success", False):
        await _log(False, http_status, erp_message)
        logger.info("[LeaveApproval] erp-api refused approval | status=%s | message=%s",
                    http_status, erp_message)
        return _finish(
            _refusal_sentence(erp_message, NOT_IN_YOUR_TEAM_MESSAGE),
            finish_intent="leave_approval_failed",
        )

    approved = body.get("data") or {}
    await _log(True, http_status, erp_message, approver=approved.get("approved_by") or {})

    employee = approved.get("employee_name") or card.get("employee_name") or "That team member"
    leave_type = approved.get("leave_type") or card.get("leave_type") or "leave"
    span = _date_range(approved) if approved.get("from_date") else card.get("date_range")
    message = (
        f"Approved - {employee}'s {leave_type} request ({span}) is now "
        f"{approved.get('status_name') or 'approved'}. The action has been logged."
    )

    # The sentence travels WITH the event, not only on the done frame. A client
    # rendering a success card off this event would otherwise have to rebuild
    # the wording from the raw erp-api row, and the one that did invented its
    # own fallbacks ("John Doe", a made-up date range) when a field was absent.
    # There is exactly one authoritative sentence for an executed approval and
    # this is it.
    writer({"type": "leave_approval_success", "data": {**approved, "message": message}})

    return _finish(
        message,
        finish_intent="leave_approval_success",
        extra_data=approved,
    )
