from __future__ import annotations

import asyncio
import difflib
import logging
import os
import re
from datetime import date, datetime
from typing import Optional
from zoneinfo import ZoneInfo

from langgraph.types import StreamWriter

from schema.agent import HRState

from services.ai_service import (
    _call_llm,
    _extract_text,
    _safe_json_parse,
    _build_leave_slot_extraction_prompt,
    _build_leave_cancel_extraction_prompt,
    _build_date_range_extraction_prompt,
    _normalize_usage,
    INTENT_MODEL,
    PENDING_LEAVE_DISPLAY_LIMIT,
)
import services.date_resolver as date_resolver
import services.erp_client as erp_client
import services.leave_failure as leave_failure
import services.leave_slot_service as leave_slot_service
import services.leave_disambiguation_state as leave_disambiguation_state
import services.leave_cancel_state as leave_cancel_state
import services.leave_history_clarify_state as leave_history_clarify_state

logger = logging.getLogger(__name__)


def _today() -> date:
    """Company-local calendar date (QUOTA_TIMEZONE env var, same one
    quota_service.py already uses — default UTC) — NOT the server
    process's own system-clock date, which can differ by hours depending
    on where it happens to be hosted (confirmed live: server-local date
    lagged Asia/Kolkata by half a day, corrupting every today/yesterday/
    tomorrow and past/future-date resolution below). Re-reads the env var
    on every call, same as quota_service.py's _get_timezone(), so it stays
    test-friendly and reflects runtime env changes."""
    return datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))).date()


# Alias kept for the deterministic date-override pipeline ported from
# hr_graph.py's since-deleted duplicate leave_action_node (see
# _apply_deterministic_date_overrides/_is_back_date_disallowed below), which
# called this same notion of "today" under this name. Tests that used to
# patch hr_graph._today_in_app_timezone patch this name instead now that the
# real implementation lives here — hr_graph.py itself never had this
# attribute at all.
_today_in_app_timezone = _today


# ── Node 4: Apply-leave / leave-balance (AC#1-#5) ─────────────────────────────
# Reuses erp-api's existing UsersLeaveRepository validation chain unchanged via
# erp_client — this node only orchestrates the conversation, it never
# duplicates a business rule. Slot state (leave_slot_service) is the "maintain
# state across turns" mechanism; classify_node's Fast-path 0.5 routes any
# mid-flow reply straight here without re-classifying.

_HALF_DAY_SLUGS = {"first_half_day", "second_half_day", "half_day"}
_SESSION_TYPE_REQUIRED_LEAVE_TYPES = {"casual_leave", "sick_leave", "earned_leave"}


def _is_single_day(slots: dict) -> bool:
    return bool(slots.get("from_date")) and slots.get("from_date") == slots.get("to_date")


def _compute_requested_days(slots: dict) -> float:
    # A half-day session type only makes sense for a single day — found via
    # live probing: "casual leave from 2026-08-24 to 2026-08-28" (5 days)
    # still asked "full day or half day?", and answering "half day" would
    # have silently collapsed a confirmed 5-day request down to 0.5 days.
    # Guarded here too (not just at the point session_type_slug gets asked
    # for), since a half-day value could otherwise linger from an earlier
    # single-day turn if the user then widens the range.
    if _is_single_day(slots) and slots.get("session_type_slug") in _HALF_DAY_SLUGS:
        return 0.5
    try:
        from datetime import date
        f = date.fromisoformat(slots["from_date"])
        t = date.fromisoformat(slots["to_date"])
        return float((t - f).days + 1)
    except Exception:
        return 1.0


def _dates_overlap(a_from: str, a_to: str, b_from: str, b_to: str) -> bool:
    try:
        from datetime import date
        a_f, a_t = date.fromisoformat(a_from), date.fromisoformat(a_to)
        b_f, b_t = date.fromisoformat(b_from), date.fromisoformat(b_to)
        return a_f <= b_t and b_f <= a_t
    except (TypeError, ValueError):
        return False


async def _find_conflicting_leave(
    erp_client_mod, bearer_token: str, company_id, conversation_id: str,
    from_date: Optional[str], to_date: Optional[str],
) -> Optional[dict]:
    """Looks for an already-submitted leave overlapping these dates —
    erp-api's real apply() call rejects an overlapping date regardless of
    leave TYPE (a Sick Leave request can't coexist with an already-applied
    Earned Leave on the same day, confirmed by a live rejection message).
    Without this, that rejection only ever surfaced AFTER the user had
    already confirmed — the confirmation card would show, the user would
    say yes, and only then would they learn the date was never valid. This
    runs the same check erp-api will run, just earlier, so the conflict is
    caught before asking the user to confirm anything.

    Advisory only, like the balance check beside it — if erp-api can't be
    reached here, this silently returns None and erp-api's own apply() call
    remains the authoritative gate.

    Live bug: get_leave_status's unfiltered response is capped to erp-api's
    own paginate(20) ordered by id (creation order, NOT leave date) — on an
    account with enough history, an older pending leave for the requested
    date can fall off that window and this check sees nothing, letting a
    genuine duplicate sail through to confirmation. For the common single-day
    request, applied_leave_date makes erp-api filter server-side instead of
    relying on the recency window. Left unscoped for a multi-day range —
    passing just one endpoint could filter away a real conflict that only
    overlaps mid-range."""
    if not from_date or not to_date:
        return None
    try:
        result = await erp_client_mod.get_leave_status(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
            applied_leave_date=from_date if from_date == to_date else None,
        )
    except (erp_client_mod.ErpApiTimeout, erp_client_mod.ErpApiUnavailable, erp_client_mod.ErpApiUnauthorized):
        return None

    existing_leaves = result["body"].get("data", {}).get("leaves", [])
    return next(
        (lv for lv in existing_leaves
         if lv.get("status_name") in ("pending", "approved")
         and _dates_overlap(lv.get("from_date"), lv.get("to_date"), from_date, to_date)),
        None,
    )


# ── Deterministic + structured date-resolution pipeline (ported from
# hr_graph.py's since-deleted duplicate leave_action_node) ────────────────
# "do not rely only on the LLM to calculate dates" (date_resolver.py's own
# module docstring) — three tiers, checked in order, each only spending the
# next one's cost when the previous tier found nothing:
#   1. _apply_deterministic_date_overrides — regex-based, via date_resolver's
#      tested primitives. Zero extra LLM cost.
#   2. Tier 2 (wired into leave_action_node's apply branch) — structured
#      tool-calling extraction (services.ai_service.extract_structured_date_
#      fields) feeding date_resolver.resolve_structured_date's pure
#      arithmetic. One extra LLM call, only for phrasing tier 1's regexes
#      don't cover.
#   3. _llm_date_needs_confirmation — refuses to silently trust whatever the
#      plain slot-extraction LLM call guessed when neither tier above ever
#      vetted it.

def _apply_deterministic_date_overrides(query: str, slots: dict, extracted: dict, today) -> bool:
    """Mutates `slots` in place, AFTER the LLM-merge loop in leave_action_node
    has already copied this turn's `extracted` fields in. Overrides
    from_date/to_date wherever date_resolver confidently recognizes a
    relative-date phrase and/or an explicit duration count in the raw
    query — "do not rely only on the LLM to calculate dates" (live bug:
    "next to next Monday" and "20 days leaves from 12th november" both got
    silently mishandled by LLM-only guessing — see date_resolver.py).

    Returns True if date_resolver recognized ANY pattern in the query text
    this turn (whether or not it disagreed with the LLM's own guess), False
    if nothing was recognized at all. Callers use this to tell "the
    deterministic layer independently confirmed this date" apart from "this
    date exists purely because the LLM said so, with zero cross-check" —
    see _llm_date_needs_confirmation, which only ever fires on a False
    return (see that function's docstring for why disagreement alone is
    deliberately NOT the trigger).

    No-ops entirely (leaves slots exactly as the LLM merge left them) for
    any phrasing date_resolver doesn't recognize — this is the
    backward-compatibility contract: existing LLM-only behavior for
    unrecognized phrasing is completely unchanged.

    Precedence when the message ALSO carries a genuine explicit end date
    (extracted.from_date != extracted.to_date, both non-null, from THIS
    turn's own LLM extraction): the explicit range wins over both a
    duration count and the phrase-matched from_date's own implied
    same-day to_date — an explicit two-endpoint range is a strictly more
    precise signal than a spoken, often-approximate count. A
    duration-vs-explicit-range mismatch is logged as a warning, not
    surfaced to the user (no new confirmation turn added for this).

    A genuine two-sided named-month range in the query itself ("October
    first Wednesday to October next Saturday" — see
    date_resolver.resolve_date_range_phrase) takes the HIGHEST precedence
    of all: it overrides both endpoints outright, ahead of even the LLM's
    own range, since two explicit named-month anchors is the most precise
    signal available — and returns immediately, since a duration count
    layered on top of an already-explicit two-sided range would only ever
    conflict with it, never usefully refine it.

    A '<ordinal> week of <Month>' mention ("first week of November") is
    checked next, at the same top precedence tier — a single week mention
    already implies its own from/to span (see
    date_resolver.resolve_week_of_month_phrase), so a trailing "...to end
    of the week" elsewhere in the same message is redundant with it and
    never needs separate parsing.

    If the query ALSO names a specific weekday within that week ("november
    first week coming wednesday" — see date_resolver.weekday_within_span),
    the match is narrowed to that single day instead of the whole 7-day
    span, and control falls through to the same single-anchor + duration
    handling used everywhere else below (so a trailing "for 1 day" still
    applies).

    A bare (no named month) two-sided weekday range ("upcoming Wednesday to
    next Sunday" — see date_resolver.resolve_relative_date_range_phrase) is
    checked next, same precedence tier — resolve_relative_date_phrase alone
    only ever returns its FIRST match by fixed pattern-priority order, not
    by where each phrase sits in the sentence, so a two-sided range needs
    this dedicated resolver instead."""
    from datetime import date, timedelta

    llm_gave_distinct_range = bool(
        extracted.get("from_date") and extracted.get("to_date")
        and extracted["from_date"] != extracted["to_date"]
    )

    range_result = date_resolver.resolve_date_range_phrase(query, today)
    if range_result and range_result[1] is not None:
        first, second = range_result
        slots["from_date"] = first["from_date"]
        slots["to_date"] = second["from_date"]
        logger.info(
            "[Graph] Deterministic date-range override: %r -> %s, %r -> %s",
            first["matched_phrase"], first["from_date"], second["matched_phrase"], second["from_date"],
        )
        return True

    week_result = date_resolver.resolve_week_of_month_phrase(query, today)
    week_narrowed_to_weekday = None
    if week_result:
        first, second = week_result
        week_narrowed_to_weekday = date_resolver.weekday_within_span(
            query, date.fromisoformat(first["from_date"]), date.fromisoformat(second["from_date"]),
        )
        if week_narrowed_to_weekday is None:
            slots["from_date"] = first["from_date"]
            slots["to_date"] = second["from_date"]
            logger.info(
                "[Graph] Deterministic week-of-month range override: %r -> %s..%s",
                first["matched_phrase"], first["from_date"], second["from_date"],
            )
            return True
        logger.info(
            "[Graph] Deterministic week-of-month narrowed to weekday: %r -> %s",
            week_narrowed_to_weekday["matched_phrase"], week_narrowed_to_weekday["from_date"],
        )

    # Live bug: "apply leave for upcoming week" (bare, no weekday) had no
    # deterministic pattern at all and fell through to tier 2's structured
    # extraction, whose schema can only represent a single day, not a week
    # span — it silently guessed a rolling 7-day window instead of the
    # actual next Mon-Sun calendar week. Checked at this same top
    # precedence tier as week-of-month, for the same reason: a bare week
    # mention already implies both endpoints on its own.
    next_calendar_week_result = date_resolver.resolve_next_calendar_week_phrase(query, today)
    if next_calendar_week_result:
        first, second = next_calendar_week_result
        slots["from_date"] = first["from_date"]
        slots["to_date"] = second["from_date"]
        logger.info(
            "[Graph] Deterministic next-calendar-week range override: %r -> %s..%s",
            first["matched_phrase"], first["from_date"], second["from_date"],
        )
        return True

    weekday_range_result = date_resolver.resolve_relative_date_range_phrase(query, today)
    if weekday_range_result and weekday_range_result[1] is not None:
        first, second = weekday_range_result
        slots["from_date"] = first["from_date"]
        slots["to_date"] = second["from_date"]
        logger.info(
            "[Graph] Deterministic weekday-range override: %r -> %s, %r -> %s",
            first["matched_phrase"], first["from_date"], second["matched_phrase"], second["from_date"],
        )
        return True

    # Live bug (found via audit): resolve_next_month_weekday_phrase/
    # resolve_this_month_weekday_phrase/resolve_this_week_weekday_phrase
    # each did a plain .search() — the FIRST match only — so a genuine
    # two-sided range using the SAME construct twice ("Monday of this week
    # to Friday of this week", "first Friday of next month to last Friday
    # of next month", "last Monday this month to last Friday this month")
    # silently collapsed to just the first endpoint, exactly the bug shape
    # already fixed for range_result/weekday_range_result above. Each
    # *_range_phrase helper below is a no-op (returns None) unless its own
    # pattern matches at least once, so checking all three here costs
    # nothing for queries that don't use this construct at all.
    this_week_weekday_range_result = date_resolver.resolve_this_week_weekday_range_phrase(query, today)
    if this_week_weekday_range_result and this_week_weekday_range_result[1] is not None:
        first, second = this_week_weekday_range_result
        slots["from_date"] = first["from_date"]
        slots["to_date"] = second["from_date"]
        logger.info(
            "[Graph] Deterministic this-week-weekday range override: %r -> %s, %r -> %s",
            first["matched_phrase"], first["from_date"], second["matched_phrase"], second["from_date"],
        )
        return True

    next_month_weekday_range_result = date_resolver.resolve_next_month_weekday_range_phrase(query, today)
    if next_month_weekday_range_result and next_month_weekday_range_result[1] is not None:
        first, second = next_month_weekday_range_result
        slots["from_date"] = first["from_date"]
        slots["to_date"] = second["from_date"]
        logger.info(
            "[Graph] Deterministic next-month-weekday range override: %r -> %s, %r -> %s",
            first["matched_phrase"], first["from_date"], second["matched_phrase"], second["from_date"],
        )
        return True

    this_month_weekday_range_result = date_resolver.resolve_this_month_weekday_range_phrase(query, today)
    if this_month_weekday_range_result and this_month_weekday_range_result[1] is not None:
        first, second = this_month_weekday_range_result
        slots["from_date"] = first["from_date"]
        slots["to_date"] = second["from_date"]
        logger.info(
            "[Graph] Deterministic this-month-weekday range override: %r -> %s, %r -> %s",
            first["matched_phrase"], first["from_date"], second["matched_phrase"], second["from_date"],
        )
        return True

    # "<ordinal> week of next month" (bare, or narrowed to a named weekday
    # within it) — same "next month" analogue of week_result above, just
    # anchored to next month instead of a named one. Live bug, found by
    # mining real production queries: this exact construct was retried at
    # least 7 times across different word orders ("next month first week
    # wednesday", "wednesday in the second week of next month", ...) — a
    # strong signal it was never resolving at all and falling through to
    # the ambiguous bare "next month" discard below.
    next_month_week_result = date_resolver.resolve_week_of_next_month_phrase(query, today)
    next_month_week_narrowed_to_weekday = None
    if next_month_week_result:
        nmw_start, nmw_end = next_month_week_result
        next_month_week_narrowed_to_weekday = date_resolver.weekday_within_span(query, nmw_start, nmw_end)
        if next_month_week_narrowed_to_weekday is None:
            slots["from_date"] = nmw_start.isoformat()
            slots["to_date"] = nmw_end.isoformat()
            logger.info(
                "[Graph] Deterministic week-of-next-month range override: %s..%s",
                nmw_start.isoformat(), nmw_end.isoformat(),
            )
            return True
        logger.info(
            "[Graph] Deterministic week-of-next-month narrowed to weekday: %r -> %s",
            next_month_week_narrowed_to_weekday["matched_phrase"], next_month_week_narrowed_to_weekday["from_date"],
        )

    resolved = (
        range_result[0] if range_result
        else weekday_range_result[0] if weekday_range_result
        else this_week_weekday_range_result[0] if this_week_weekday_range_result
        else next_month_weekday_range_result[0] if next_month_weekday_range_result
        else this_month_weekday_range_result[0] if this_month_weekday_range_result
        else week_narrowed_to_weekday if week_narrowed_to_weekday
        else next_month_week_narrowed_to_weekday if next_month_week_narrowed_to_weekday
        else date_resolver.resolve_next_month_weekday_phrase(query, today)
        or date_resolver.resolve_this_month_weekday_phrase(query, today)
        or date_resolver.resolve_this_week_weekday_phrase(query, today)
        or date_resolver.resolve_relative_date_phrase(query, today)
        # Systemic gap found via audit: "in two weeks"/"15 days from now" had
        # no weekday name and none of the fixed qualifier words, so it was
        # invisible to both tier 2's gate and tier 3's cross-check, silently
        # riding on the plain first-pass LLM extraction's own guess. Checked
        # last (lowest precedence) — every resolver above it matches a more
        # specific phrasing.
        or date_resolver.resolve_relative_duration_offset_phrase(query, today)
    )
    # Live bug: bare "next month" (no day, weekday, or ordinal at all — e.g.
    # "apply casual leave for next month") silently resolved to just the 1st
    # of next month via date_resolver._PATTERNS' lowest-priority "next_month"
    # entry, with no indication to the user that a day was ever picked for
    # them. Unlike "tomorrow" or "next Monday", "next month" alone never
    # names a specific day — resolving it at all is itself a guess, which
    # this flow must never do. Always discard this match here and let it
    # fall through to _llm_date_needs_confirmation's ambiguous-phrase safety
    # net instead of confidently returning an unannounced guess.
    if resolved and resolved.get("matched_kind") == "next_month":
        logger.info(
            "[Graph] Discarding bare 'next month' match — no day/weekday named, "
            "genuinely ambiguous which date within the month. query=%r", query,
        )
        resolved = None
    if resolved:
        slots["from_date"] = resolved["from_date"]
        if not llm_gave_distinct_range:
            slots["to_date"] = resolved["from_date"]
        logger.info(
            "[Graph] Deterministic date override: %r -> %s",
            resolved["matched_phrase"], resolved["from_date"],
        )

    # Exclude a resolver's own already-consumed phrase before searching for
    # a separate duration count — otherwise "in two weeks" (already fully
    # resolved above via resolve_relative_duration_offset_phrase, with
    # "two weeks" as PART OF a single-day date reference, not a day count)
    # would ALSO match here as if the user separately said "for two weeks",
    # doubling the offset onto its own from_date (see extract_duration_days'
    # own docstring — same double-counting bug shape already fixed for "a
    # week after next").
    duration_days = date_resolver.extract_duration_days(
        query, exclude=resolved["matched_phrase"] if resolved else None,
    )
    if duration_days and slots.get("from_date"):
        if llm_gave_distinct_range:
            try:
                actual_days = (date.fromisoformat(slots["to_date"]) - date.fromisoformat(slots["from_date"])).days + 1
                if actual_days != duration_days:
                    logger.warning(
                        "[Graph] Duration count (%s day(s)) conflicts with explicit date range "
                        "(%s day(s), %s to %s) — explicit range takes precedence. query=%r",
                        duration_days, actual_days, slots["from_date"], slots["to_date"], query,
                    )
            except (TypeError, ValueError):
                pass
        else:
            try:
                computed_to = date.fromisoformat(slots["from_date"]) + timedelta(days=duration_days - 1)
                slots["to_date"] = computed_to.isoformat()
                logger.info(
                    "[Graph] Deterministic duration override: %s day(s) -> to_date=%s",
                    duration_days, slots["to_date"],
                )
            except (TypeError, ValueError):
                pass

    return bool(resolved)


# ── Confirming an LLM-only date that the deterministic layer never saw ─────
# _apply_deterministic_date_overrides above only ever OVERRIDES a date it
# recognizes — for query text it doesn't recognize at all, it silently
# no-ops, so whatever the LLM guessed stands with zero cross-check. That's
# fine for the common case (an explicit absolute date like "12th November"
# or "2026-09-15" — date_resolver deliberately never touches these, see its
# module docstring, and the LLM is reliable at literal parsing with no
# arithmetic involved). It's NOT fine for genuinely relative phrasing
# date_resolver just doesn't have a pattern for yet ("the Monday after
# next", "wednesday off next week"), where the LLM is doing the same kind
# of multi-step weekday arithmetic it's been repeatedly shown to get wrong
# (see tests/date_extraction_direct_openai_sweep.py — 14/41 real queries
# came back with a date that didn't even match the weekday it claimed).
# Disagreement with the LLM is deliberately NOT the trigger here — this
# only ever fires when date_resolver found nothing at all to disagree with.

_RELATIVE_DATE_QUALIFIER_PATTERN = re.compile(
    r"\b(next|this|coming|upcoming|last|after\s+next|week\s+after|month\s+after|"
    r"quarter|weekend|long\s+weekend)\b",
    re.I,
)


def _find_named_weekday(query: str) -> Optional[str]:
    text = query.lower()
    for name in date_resolver._WEEKDAYS:
        if re.search(rf"\b{name}\b", text):
            return name
    return None


def _query_needs_relative_date_scrutiny(query: str, today: date) -> bool:
    """Shared gate predicate — True if `query` contains any signal that its
    date shouldn't be silently trusted from a bare LLM guess: a named
    weekday, a relative-time qualifier word (next/this/coming/last/
    weekend/quarter/...), a bare duration-offset phrase ("in two weeks",
    "15 days from now"), or a bare ordinal day-of-month that's already
    passed this month with no month name/qualifier to disambiguate it
    ("on 15th" on Aug 27). False for a bare day-number still upcoming this
    month, or one already disambiguated by an explicit month name/
    qualifier — both genuinely unambiguous.

    Replaces two hand-duplicated copies of the weekday/qualifier check
    (this apply-flow's own _looks_like_a_date_query, and the equivalent
    inline expression in _llm_date_needs_confirmation below) — the
    duplication is itself how the duration-offset gap went unnoticed (a
    third clause was only ever added to one copy). `today` is required
    because the bare-day-of-month signal is only ambiguous relative to
    what day it currently is — see date_resolver.
    mentions_ambiguous_bare_day_of_month."""
    return (
        _find_named_weekday(query) is not None
        or _RELATIVE_DATE_QUALIFIER_PATTERN.search(query) is not None
        or date_resolver.mentions_relative_duration_qualifier(query)
        or date_resolver.mentions_ambiguous_bare_day_of_month(query, today) is not None
    )


def _llm_date_needs_confirmation(
    query: str, llm_from_date: Optional[str], llm_to_date: Optional[str],
    det_matched: bool, today,
) -> Optional[dict]:
    """Returns a small report dict describing WHY this turn's date shouldn't
    be silently trusted, or None if it's fine to proceed as-is (either
    date_resolver already vetted it, or there's nothing here worth
    second-guessing). Never mutates anything — the caller decides what to do
    with the result.

    Three distinct reasons, because they need different responses from the
    bot:
      - "invalid": llm_from_date/llm_to_date don't even parse as real
        calendar dates, or to_date is before from_date. Confirming a date
        that doesn't exist ("you mean Feb 30?") makes no sense — the right
        response is to say so plainly and ask again, not offer a yes/no.
      - "past_date": a syntactically valid date, before `today`, that the
        user did NOT type verbatim (llm_from_date doesn't appear literally
        in `query`) AND that date_resolver's own phrase-matcher found no
        recognizable pattern for at all — i.e. a date arrived at by
        inference from something date_resolver has never heard of, rather
        than one the user explicitly typed, or one built from a word
        date_resolver DOES recognize (e.g. "yesterday" — see
        date_resolver.resolve_relative_date_phrase's allow_past guard,
        which deliberately refuses to resolve it for this exact reason).
        Both of those are left to the existing, company-policy-aware
        back-date-disallowed check further downstream — that check already
        knows whether THIS company even disallows back-dated leave, and
        already has a well-tested, specific response for a deliberate past
        request like "yesterday"; duplicating a blanket rejection here
        would both override a company that explicitly permits it AND give
        a worse, less specific answer than the one that already exists.
        This is narrowly about catching a miscalculated reference landing
        in the past BY ACCIDENT, from phrasing date_resolver has no way to
        recognize or correct.
      - "ambiguous_relative_phrase": the query names a weekday or a
        relative-time qualifier (next/this/coming/last/weekend/quarter/...)
        that date_resolver's own patterns didn't recognize — exactly the
        kind of phrasing the diagnostic sweep showed the LLM getting wrong
        on its own, with nothing here to catch it.

    Deliberately does NOT flag a bare absolute date/day-number with no
    weekday or relative qualifier (e.g. "the 5th", "the whole of November")
    — date_resolver not having a pattern for literal date parsing is by
    design (see date_resolver.py's module docstring), not a gap."""
    from datetime import date

    if det_matched or not llm_from_date:
        return None

    try:
        from_d = date.fromisoformat(llm_from_date)
    except (TypeError, ValueError):
        return {"reason": "invalid", "llm_from_date": llm_from_date, "llm_to_date": llm_to_date}

    if llm_to_date:
        try:
            to_d = date.fromisoformat(llm_to_date)
        except (TypeError, ValueError):
            return {"reason": "invalid", "llm_from_date": llm_from_date, "llm_to_date": llm_to_date}
        if to_d < from_d:
            return {"reason": "invalid", "llm_from_date": llm_from_date, "llm_to_date": llm_to_date}

    # "Recognized by text, regardless of the past-date guard" — a query
    # matching one of these was already deliberately considered and either
    # resolved (in which case det_matched above would have already been
    # True and returned None) or explicitly declined ONLY because it
    # resolved to a past date (e.g. "yesterday") — see
    # resolve_relative_date_phrase/resolve_this_month_weekday_phrase's
    # allow_past guard. Either way, this codebase has already made an
    # informed decision about this exact phrasing; neither "past_date" nor
    # "ambiguous_relative_phrase" should second-guess it — both defer
    # entirely to the existing, company-policy-aware back-date-disallowed
    # check downstream. A bare "next_month" match is deliberately excluded
    # here too — see _apply_deterministic_date_overrides — it's genuinely
    # ambiguous, and must fall through to the "ambiguous_relative_phrase"
    # check below instead of being waved through as already-vetted.
    relative_match = date_resolver._match_relative_phrase(query)
    text_recognized = (
        (relative_match is not None and relative_match[0] != "next_month")
        or date_resolver._THIS_MONTH_WEEKDAY_PATTERN.search(query) is not None
        or date_resolver._NEXT_MONTH_WEEKDAY_PATTERN.search(query) is not None
        or date_resolver._THIS_WEEK_WEEKDAY_PATTERN.search(query) is not None
        # A month name PLUS an explicit year ("15th November 2025") is just
        # as deliberate and unambiguous as a literal ISO date typed verbatim
        # — see _roll_apply_dates_forward_if_past, which already treats this
        # exact combination as "the user said precisely what they meant, no
        # inference happened here at all". Without this, an explicit-year
        # date that also happens to be genuinely in the past (unlike the
        # ambiguous no-year case above, which only ever ROLLS forward into
        # the future) fell through to "past_date" purely because the ISO
        # string itself doesn't appear character-for-character in the
        # query — even though the user could not have been clearer about
        # which date they meant. Defers entirely to the existing, company-
        # policy-aware back-date-disallowed check downstream, same as every
        # other already-recognized phrasing above.
        or (
            _MONTH_NAME_TOKEN_PATTERN.search(query) is not None
            and _EXPLICIT_YEAR_IN_QUERY_PATTERN.search(query) is not None
        )
    )
    if text_recognized:
        return None

    if from_d < today and llm_from_date not in query:
        return {"reason": "past_date", "llm_from_date": llm_from_date, "llm_to_date": llm_to_date}

    if _query_needs_relative_date_scrutiny(query, today):
        return {"reason": "ambiguous_relative_phrase", "llm_from_date": llm_from_date, "llm_to_date": llm_to_date}

    return None


def _php_falsy(value) -> bool:
    """Replicates PHP's truthiness for erp-api's leave_settings values
    (stored as strings like "0"/"1", not real booleans) — PHP treats 0,
    "0", "", and null as falsy; everything else (including "1") as truthy.
    Python's own truthiness would get this wrong: the non-empty string "0"
    is truthy in Python but falsy in PHP."""
    if value is None:
        return True
    if isinstance(value, bool):
        return not value
    if isinstance(value, (int, float)):
        return value == 0
    if isinstance(value, str):
        return value in ("", "0")
    return False


async def _is_back_date_disallowed(
    erp_client_mod, bearer_token: str, company_id, conversation_id: str, from_date: Optional[str],
) -> bool:
    """True only if from_date is genuinely in the past AND this company's
    own leave_settings.back_date_leave_allow is disabled ("0") — mirrors
    erp-api's own checkBackDateLeaveAllow(), a per-company toggle (confirmed
    live some companies set it to "1", allowing it), not a universal rule.
    Checked here so the user finds out before confirming instead of after
    erp-api's own apply() call rejects it with "Cannot apply leave for past
    dates". Advisory only, like the conflict/balance checks beside it —
    fails open (False) if erp-api can't be reached or the date can't be
    parsed; erp-api's own apply() call remains the authoritative gate
    regardless."""
    if not from_date:
        return False
    try:
        from datetime import date
        if date.fromisoformat(from_date) >= _today_in_app_timezone():
            return False
    except (TypeError, ValueError):
        return False
    try:
        result = await erp_client_mod.get_leave_balance(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
        )
    except (erp_client_mod.ErpApiTimeout, erp_client_mod.ErpApiUnavailable):
        return False
    settings = result["body"].get("data", {}).get("leave_settings", {})
    return _php_falsy(settings.get("back_date_leave_allow"))


async def _fetch_known_leave_types(
    erp_client_mod, bearer_token: str, company_id, conversation_id: str,
) -> Optional[list[dict]]:
    """This company's REAL configured leave types — {slug, name} — straight
    from erp-api's leave/balance call, the same data the balance branch
    already uses. Live bug: the "what type of leave?" question used to
    always say "casual, sick, earned, or something else?", a hardcoded
    guess — a company that also configures short_leave/comp_off/anything
    custom never had those mentioned anywhere. Sourced from leave_quota's
    keys (authoritative — matches every type the balance card lists,
    including comp_off/leave_without_pay even when leave_settings.leave_type
    omits them) and leave_settings.leave_type only for a nicer display name
    where one happens to exist, falling back to a title-cased slug
    otherwise. Returns None if erp-api can't be reached — the caller falls
    back to the old generic wording rather than breaking."""
    try:
        result = await erp_client_mod.get_leave_balance(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
        )
    except (erp_client_mod.ErpApiTimeout, erp_client_mod.ErpApiUnavailable, erp_client_mod.ErpApiUnauthorized):
        return None
    data = result["body"].get("data", {})
    leave_quota_slugs = list(data.get("leave_quota", {}).keys())
    if not leave_quota_slugs:
        return None
    names_by_slug = {
        t["slug"]: t.get("name")
        for t in data.get("leave_settings", {}).get("leave_type", [])
        if t.get("slug")
    }
    return [
        {"slug": slug, "name": names_by_slug.get(slug) or slug.replace("_", " ").title()}
        for slug in leave_quota_slugs
    ]


async def _fetch_holidays_or_none(erp_client_mod, bearer_token, company_id, conversation_id):
    """The holiday calendar, or None. Never raises.

    Advisory data: if it can't be loaded we say nothing about holidays and let
    erp-api decide, rather than refusing a leave it would have accepted.
    """
    try:
        result = await erp_client_mod.get_leave_holidays(
            bearer_token, company_id=company_id, conversation_id=conversation_id)
        return result.get("body")
    except Exception as e:
        logger.warning(f"[Graph] holiday calendar unavailable: {e}")
        return None


def _holiday_index(holiday_body: Optional[dict]) -> dict:
    """{"2026-07-14": "Good Wednesday"} from the holidays payload."""
    if not isinstance(holiday_body, dict):
        return {}
    data = holiday_body.get("data") or {}
    index = {}
    for entry in data.get("holidays") or []:
        if not isinstance(entry, dict):
            continue
        day = entry.get("holiday_date")
        if isinstance(day, str) and day.strip():
            index[day.strip()] = entry.get("holiday_name") or "Company holiday"
    return index


def _fully_blocked_holidays(holidays: dict, from_date, to_date) -> list:
    """(date, name) pairs when EVERY requested day is a company holiday.

    Deliberately all-or-nothing. A range that merely contains a holiday is not
    blocked — erp-api just doesn't count that day against the leave, so
    refusing the whole request would be wrong. Returns [] whenever the dates
    can't be parsed or the calendar doesn't cover them (a request falling in
    next year's calendar, say): unknown means fall open and let erp-api rule,
    never block on data we don't have.
    """
    if not holidays:
        return []
    try:
        first = date.fromisoformat(from_date)
        last = date.fromisoformat(to_date)
    except (TypeError, ValueError):
        return []
    if last < first:
        return []
    matched = []
    for offset in range((last - first).days + 1):
        day = date.fromordinal(first.toordinal() + offset).isoformat()
        if day not in holidays:
            return []
        matched.append((day, holidays[day]))
    return matched


def _named_holiday_span(holidays: dict, day: str) -> tuple[str, str, str]:
    """Given a day that's a key in `holidays` (an ISO date -> name index),
    returns the maximal run of CONSECUTIVE calendar days carrying the exact
    same holiday name, as (start_iso, end_iso, name) — e.g. a multi-day named
    freeze period erp-api lists as one calendar entry per day. Walks outward
    from `day` in both directions (capped at 60 days each way — long enough
    for any real blackout window, short enough to never spin on bad data).

    Derived entirely from erp-api's own entries, never fabricated: an
    isolated single-day holiday still comes back as (day, day, name) rather
    than being widened into a range it isn't part of. HA-163 Sprint 2 spec's
    "Quarter-End Freeze, 10-18 Aug" example only renders correctly when
    erp-api's calendar actually lists each of those days under that name —
    see the BLOCKED_DATE limitation this supersedes in the test-case doc.
    """
    name = holidays.get(day)
    if not name:
        return day, day, ""
    try:
        d = date.fromisoformat(day)
    except (TypeError, ValueError):
        return day, day, name
    start = d
    for _ in range(60):
        prev = date.fromordinal(start.toordinal() - 1)
        if holidays.get(prev.isoformat()) != name:
            break
        start = prev
    end = d
    for _ in range(60):
        nxt = date.fromordinal(end.toordinal() + 1)
        if holidays.get(nxt.isoformat()) != name:
            break
        end = nxt
    return start.isoformat(), end.isoformat(), name


def _display_date_range_compact(from_iso: str, to_iso: str) -> str:
    """'2026-08-10', '2026-08-18' -> '10 Aug - 18 Aug 2026' — same-year
    contraction as _display_date_range, but without the weekday prefix,
    matching the design's blocked-date wording ("15 Aug 2026 falls in a
    company blackout period (Quarter-End Freeze, 10 Aug - 18 Aug 2026).")."""
    f = date.fromisoformat(from_iso)
    t = date.fromisoformat(to_iso)
    if f.year == t.year:
        return f"{f.strftime('%d %b')} - {t.strftime('%d %b %Y')}"
    return f"{f.strftime('%d %b %Y')} - {t.strftime('%d %b %Y')}"


def _blocked_holiday_message(holidays: dict, blocked: list[tuple[str, str]]) -> str:
    """Human-facing message for a fully-blocked request (HA-163 Sprint 2
    Scenario B). When every matched day shares one holiday name, expands
    outward through the calendar (_named_holiday_span) to describe the FULL
    named block/freeze period — which may extend beyond the requested dates —
    rather than just the day(s) actually requested, matching how a real
    blackout window reads to an employee. Falls back to a plain per-day
    listing when the matched days carry different names (a request spanning
    two unrelated single-day holidays, say)."""
    names = {name for _, name in blocked}
    if len(names) == 1:
        start, end, name = _named_holiday_span(holidays, blocked[0][0])
        if start == end:
            return (f"{_display_date(blocked[0][0])} is a company holiday ({name}). "
                    "Leave cannot be applied for blocked dates.")
        subject = (_display_date(blocked[0][0]) if len(blocked) == 1
                   else _display_date_range_compact(blocked[0][0], blocked[-1][0]))
        range_text = _display_date_range_compact(start, end)
        return (f"{subject} falls in a company blackout period ({name}, {range_text}). "
                "Leave cannot be applied for blocked dates.")
    listed = ", ".join(f"{_display_date(d)} ({n})" for d, n in blocked)
    return f"Every day in this request is a company holiday — {listed}. Leave cannot be applied for blocked dates."


def _insufficient_balance_message(leave_type_slug: str, remaining, requested) -> tuple[str, str]:
    """HA-163 Sprint 2 Scenario A wording: "You have 3 days of Sick Leave
    (SL) available, but this request needs 4 days. Reduce the duration or
    use another type." Returns (message, type_name) — the caller needs
    type_name again for the sub_title and the "Apply for N Days" chip label.
    """
    type_name = leave_type_slug.replace("_", " ").title()
    code = _LEAVE_TYPE_CODES.get(leave_type_slug)
    code_suffix = f" ({code})" if code else ""
    message = (
        f"You have {_pluralize_leave_type(remaining, 'day')} of {type_name}{code_suffix} available, "
        f"but this request needs {_pluralize_leave_type(requested, 'day')}. "
        "Reduce the duration or use another type."
    )
    return message, type_name


def _duplicate_conflict_message(conflict: dict) -> str:
    """"You've already applied for Sick Leave on Thu, 04 Jun 2030 (pending)."
    Uses _display_date_range so this reads the same way every other
    date-bearing message in this file does (cancel preview/success, pending
    cards) — this one previously showed the raw ISO pair ('2030-06-04 to
    2030-06-04') instead of the shared Figma date format."""
    date_label = _display_date_range(conflict.get("from_date"), conflict.get("to_date"))
    return (
        f"You've already applied for {conflict.get('leave_type', 'leave')} on "
        f"{date_label} ({conflict.get('status_name')})."
    )


async def _fetch_balance_or_none(erp_client_mod, bearer_token, company_id, conversation_id):
    """Balance payload, or None. Never raises — see _collect_additional_failures."""
    try:
        result = await erp_client_mod.get_leave_balance(
            bearer_token, company_id=company_id, conversation_id=conversation_id)
        return result.get("body")
    except Exception as e:
        logger.warning(f"[Graph] balance unavailable for failure enrichment: {e}")
        return None


async def _collect_additional_failures(erp_client_mod, bearer_token, company_id,
                                       conversation_id, slots, exclude_code):
    """Further problems with the same request, beyond the one erp-api named.

    Runs ONLY after erp-api has already refused. These findings never gate
    anything: erp-api is the authority on what it will accept, and Helix
    blocking on its own reading risks refusing a leave the ERP would have
    taken. Their whole job is to explain — so an employee isn't sent round the
    loop fixing one problem, resubmitting, and meeting the next one (AC4).

    Anything that won't load is skipped. Enrichment must never turn a clean
    rejection into an error, so every source here fails quietly.
    """
    from_date, to_date = slots.get("from_date"), slots.get("to_date")
    holiday_body, balance_body, conflict = await asyncio.gather(
        _fetch_holidays_or_none(erp_client_mod, bearer_token, company_id, conversation_id),
        _fetch_balance_or_none(erp_client_mod, bearer_token, company_id, conversation_id),
        _find_conflicting_leave(erp_client_mod, bearer_token, company_id,
                                conversation_id, from_date, to_date),
    )

    found = []

    holidays = _holiday_index(holiday_body)
    blocked = _fully_blocked_holidays(holidays, from_date, to_date)
    if blocked:
        found.append(leave_failure.local_failure(
            _blocked_holiday_message(holidays, blocked), "BLOCKED_DATE"))

    quota = {}
    if isinstance(balance_body, dict):
        data = balance_body.get("data")
        if isinstance(data, dict) and isinstance(data.get("leave_quota"), dict):
            quota = data["leave_quota"]
    entry = quota.get(slots.get("leave_type"))
    remaining = entry.get("remaining") if isinstance(entry, dict) else None
    if remaining is not None:
        try:
            requested = _compute_requested_days(slots)
            if requested > float(remaining):
                message, type_name = _insufficient_balance_message(
                    slots.get("leave_type") or "leave", remaining, requested)
                found.append(leave_failure.local_failure(
                    message, "INSUFFICIENT_BALANCE", heading=f"Not enough {type_name} balance"))
        except (TypeError, ValueError):
            pass

    if conflict:
        found.append(leave_failure.local_failure(
            _duplicate_conflict_message(conflict), "DUPLICATE_APPLICATION"))

    # erp-api already said this one; listing it twice would read as two
    # separate problems.
    return [f for f in found if f.reason_code != exclude_code]



# erp-api's leave_status labels (config/site-vars.php "leave_status" map),
# matched by PREFIX rather than the exact literal word — live bug
# (2026-08-20): "show my approve leave" (missing the "-d") and "show my
# cancel leave" (missing "-led") both failed to match the old exact-word
# check, falling through to the ambiguous "which leaves?" clarify even
# though the intent was completely unambiguous. Covers approve/approved/
# approval, reject/rejected/rejection, cancel/cancelled/canceled/cancelling
# — every common verb/adjective/noun form of the same status word.
_LEAVE_STATUS_FILTER_PATTERNS: dict[str, re.Pattern] = {
    "pending": re.compile(r"\bpending\b", re.IGNORECASE),
    "approved": re.compile(r"\bapprov\w*\b", re.IGNORECASE),
    "rejected": re.compile(r"\brejec\w*\b", re.IGNORECASE),
    "cancelled": re.compile(r"\bcancel(?:led|ed|l?ing)?\b", re.IGNORECASE),
}

# "is my leave approved" / "was my leave rejected" / "did HR approve my
# leave" / "has it been accepted yet" — a yes/no STATUS QUESTION, not a
# request to see a filtered list. Live bug: _extract_status_filter used to
# treat the bare presence of "approved"/"rejected" anywhere in the query as
# an explicit filter request, so "is my leave approved" hit the same refusal
# built for "show me my approved leaves" ("I can only show pending requests
# here") — even though the person never asked to SEE a list, just whether
# theirs had been decided. /leave/pending can't give a definitive yes/no for
# this anyway (an approved/rejected request simply won't be in the pending
# list, and there's no way to tell those two outcomes apart from here) — but
# it CAN tell them "still pending" when it's a match, so this must fall
# through to the normal pending lookup and give an honest answer, not a
# blanket refusal.
_STATUS_QUESTION_PATTERNS: list[re.Pattern] = [
    re.compile(r"\b(is|was|has|did)\b[\w\s']{0,25}?\b(approve|approved|reject|rejected|accept|accepted|decline|declined)\b", re.IGNORECASE),
    re.compile(r"\b(approve|approved|reject|rejected|accept|accepted|decline|declined)\b[\w\s']{0,15}?\b(yet|already|or not)\b", re.IGNORECASE),
]


def _is_status_question(query: str) -> bool:
    text = query.lower()
    return any(p.search(text) for p in _STATUS_QUESTION_PATTERNS)


def _match_status_word(query: str) -> Optional[str]:
    """Pure prefix match against the status vocabulary, with NO question
    check — used directly by the status-question branch (which needs to
    know WHICH status a question like 'why was my leave REJECTED' names,
    something _extract_status_filter deliberately can't tell it, see
    below)."""
    text = query.lower()
    for status, pattern in _LEAVE_STATUS_FILTER_PATTERNS.items():
        if pattern.search(text):
            return status
    return None


def _extract_status_filter(query: str) -> Optional[str]:
    """'I want to know only pending leave status' -> 'pending'. Deterministic
    prefix match — no LLM call needed for a closed, well-known vocabulary.
    Question phrasing ('is my leave approved') is deliberately NOT treated
    as an explicit LIST-filter request here — see _is_status_question above
    — but the status-question branch still needs the specific status word a
    question names, so it calls _match_status_word directly instead of this
    wrapper."""
    if _is_status_question(query):
        return None
    return _match_status_word(query)


def _estimate_leave_days(from_date: Optional[str], to_date: Optional[str]) -> Optional[float]:
    """Fallback used only when erp-api doesn't supply total_days directly —
    a plain inclusive date-span count, same arithmetic as the apply-leave
    branch's _compute_requested_days (minus half-day awareness, which
    /leave/status doesn't expose)."""
    if not from_date or not to_date:
        return None
    try:
        from datetime import date
        f = date.fromisoformat(from_date)
        t = date.fromisoformat(to_date)
        return float((t - f).days + 1)
    except Exception:
        return None


def _fmt_days(value) -> str:
    try:
        f = float(value)
        return str(int(f)) if f.is_integer() else str(f)
    except (TypeError, ValueError):
        return str(value)


def _pluralize_leave_type(value, name: str) -> str:
    """5, 'Casual Leave' -> '5 Casual Leaves'. 1, 'Casual Leave' -> '1
    Casual Leave'. Names the actual leave type in a count instead of a
    generic 'day(s)' ("14 Casual Leave day(s)" reads oddly; "14 Casual
    Leaves" doesn't). Falls back to a bare '(s)' suffix if value isn't
    numeric — shouldn't happen in practice, but a formatting nicety must
    never be the reason a message fails to render."""
    display = _fmt_days(value)
    try:
        n = float(display)
    except (TypeError, ValueError):
        return f"{display} {name}(s)"
    return f"{display} {name}" if n == 1 else f"{display} {name}s"


def _display_date(iso_date: Optional[str], with_weekday: bool = False) -> Optional[str]:
    """'2026-07-30' -> 'Thu, 30 Jul 2026' (with_weekday) or '30 Jul 2026' —
    Figma design's date format everywhere it appears (pending list, cancel
    preview/success). Returns the raw value unparsed rather than raising, so
    a malformed date still shows something instead of breaking the card."""
    if not iso_date:
        return None
    try:
        d = date.fromisoformat(str(iso_date)[:10])
    except (TypeError, ValueError):
        return str(iso_date)
    return d.strftime("%a, %d %b %Y") if with_weekday else d.strftime("%d %b %Y")


def _display_date_range(from_iso: Optional[str], to_iso: Optional[str]) -> Optional[str]:
    """Same date on both ends -> single formatted date, 'Mon, 24 Aug 2026'
    (matches the design for a one-day request). A real range shows the
    weekday on BOTH ends -> 'Mon, 24 Aug - Wed, 26 Aug 2026' (same year),
    or 'Wed, 30 Dec 2026 - Fri, 01 Jan 2027' (spanning years, year shown on
    both ends since the leading date's year isn't otherwise inferable)."""
    if not from_iso and not to_iso:
        return None
    if not from_iso or not to_iso:
        return _display_date(from_iso or to_iso)
    try:
        f = date.fromisoformat(str(from_iso)[:10])
        t = date.fromisoformat(str(to_iso)[:10])
    except (TypeError, ValueError):
        return f"{from_iso} - {to_iso}"
    if f == t:
        return f.strftime("%a, %d %b %Y")
    if f.year == t.year:
        return f"{f.strftime('%a, %d %b')} - {t.strftime('%a, %d %b %Y')}"
    return f"{f.strftime('%a, %d %b %Y')} - {t.strftime('%a, %d %b %Y')}"


def _selected_date_label(card: dict) -> str:
    """The same Figma-formatted date shown on the card ('Thu, 30 Jul 2026' /
    '14 - 15 Aug 2026') for the spoken cancel-leave sentences — these used to
    build their own '<from_date> to <to_date>' text straight off the raw ISO
    fields, so the chat bubble read '2026-08-07 to 2026-08-07' for a one-day
    request while the card right above it already said 'Thu, 07 Aug 2026'."""
    return (
        card.get("date_label")
        or _display_date_range(card.get("from_date"), card.get("to_date"))
        or f"{card.get('from_date')} to {card.get('to_date')}"
    )


def _keep_request_message(selected: dict) -> str:
    """The spoken reply for declining a pending cancellation ("Keep
    Request" / "discard" / "never mind" / etc.) — names the specific
    request being kept (date + reference), not just its leave type, so it
    reads as a real confirmation of WHICH request was left alone rather
    than a generic acknowledgement. Especially important once more than one
    leave request has been in play in the same conversation."""
    date_txt = _selected_date_label(selected) if selected.get("from_date") else None
    detail = f" ({date_txt}, ref {selected.get('reference')})" if date_txt and selected.get("reference") else ""
    return f"No problem — I've kept your {selected.get('leave_type', 'leave')} request{detail} as is."


_APPROVED_BACKDATED_CANCEL_MESSAGE = (
    "An approved leave cannot be cancelled after its leave date has passed."
)
_APPROVED_BACKDATED_CANCEL_NEXT_ACTION = "Would you like to contact HR for help with this?"


def _leave_date_has_passed(card: dict, today: Optional[date] = None) -> bool:
    """True once the leave's own end date (its whole period, for a range) is
    strictly before today. Only meaningful for an APPROVED leave — a pending
    one was never going to be executed on that date in the first place, so
    "the leave date has passed" isn't a policy block for it the way it is
    once a manager has actually approved the time off."""
    to_date = card.get("to_date") or card.get("from_date")
    if not to_date:
        return False
    try:
        end = date.fromisoformat(str(to_date)[:10])
    except (TypeError, ValueError):
        return False
    return end < (today or _today())


def _blocked_backdated_cancel_card(selected: dict) -> dict:
    """The same leave_failure card shape an erp-api rejection produces —
    "Cancellation Not Completed" / "Blocked by leave policy" / a POLICY_RULE
    chip inviting HR contact — for a case Helix can determine on its own
    (2026-08-26 product direction): an APPROVED leave whose date has already
    passed can never actually be cancelled, so there is nothing to preview
    or confirm. Caught here, before the balance-impact preview is ever
    shown, rather than letting the employee "confirm" something erp-api was
    always going to refuse."""
    failure = leave_failure.local_failure(_APPROVED_BACKDATED_CANCEL_MESSAGE, "POLICY_RULE")
    return leave_failure.build_card(
        "cancel_leave", failure, next_action=_APPROVED_BACKDATED_CANCEL_NEXT_ACTION,
        next_actions=[leave_failure.chip("Contact HR Help Desk", "contact_hr")],
    )


def _describe_candidate(card: dict) -> str:
    return f"{card['leave_type']} ({card['from_date']} to {card['to_date']})"


# Short display code for each known leave type slug (e.g. "Casual Leave" ->
# "CL") — used by the cancel-leave cards to match the "Leave Type (CODE)"
# design ("Casual Leave (CL)"). Kept as an explicit table rather than
# auto-deriving initials: Sick Leave and Short Leave would both collide on
# "SL" otherwise. None for any slug not in this table (comp_off/
# leave_without_pay/unknown types show without a code rather than guessing).
_LEAVE_TYPE_CODES: dict[str, str] = {
    "casual_leave": "CL",
    "sick_leave": "SL",
    "earned_leave": "EL",
    "short_leave": "SHL",
    "comp_off": "CO",
    "leave_without_pay": "LWP",
}

# Design wording for each status ("Pending Approval", not just "Pending") —
# falls back to a plain title-cased render of the raw status_name for any
# value not listed here, so an unrecognised/future erp-api status still
# renders something reasonable instead of breaking. "pending" here is the
# fallback used only when erp-api didn't send a role — see
# _pending_status_label for the normal case, which names the actual stage
# ("Pending with Manager" / "Pending with HR").
_STATUS_DISPLAY_LABELS: dict[str, str] = {
    "pending": "Pending Approval",
    "approved": "Approved",
    "rejected": "Rejected",
    "cancelled": "Cancelled",
}


def _pending_status_label(role: Optional[str], name: Optional[str] = None) -> str:
    """('manager', 'John Smith') -> 'Pending with John Smith (Manager)' —
    names WHO it's with, not just which stage, so the chip is actually
    identifying to the employee, not just categorical. Falls back to
    'Pending with Manager'-style role-only when erp-api sends a role but no
    name, then to the generic 'Pending Approval' label when it sends
    neither — never inventing an approver that wasn't actually returned."""
    role_text = role.strip() if role and role.strip() else None
    name_text = name.strip() if name and name.strip() else None
    if not role_text and not name_text:
        return _STATUS_DISPLAY_LABELS["pending"]
    display_role = ("HR" if role_text.lower() == "hr" else role_text.title()) if role_text else None
    if name_text and display_role:
        return f"Pending with {name_text} ({display_role})"
    if name_text:
        return f"Pending with {name_text}"
    return f"Pending with {display_role}"


# "by" for a request that's already been decided BY an approver. Only
# approved/rejected are here — cancellation happens through our own
# self-service cancel_leave flow (employee-initiated), never something an
# approver "does" the way approving/rejecting is, so it's deliberately NOT
# whitelisted here even if erp-api still sends a role/name on a cancelled
# record; _decided_status_label treats anything absent from this map as
# never eligible for the name/role enrichment, cancelled included.
_STATUS_APPROVER_CONNECTOR: dict[str, str] = {"approved": "by", "rejected": "by"}


def _decided_status_label(status_name: Optional[str], role: Optional[str], name: Optional[str]) -> str:
    """'approved' + ('manager', 'John Smith') -> 'Approved by John Smith
    (Manager)' — the approved/rejected counterpart to _pending_status_label,
    so those statuses name their actual approver too, not just pending
    ones. Cancelled (and any status not in _STATUS_APPROVER_CONNECTOR) is
    deliberately left as the plain label, never enriched — see that map's
    comment. Falls back to the plain _STATUS_DISPLAY_LABELS wording when
    erp-api sends neither a role nor a name for this record either."""
    base_label = _STATUS_DISPLAY_LABELS.get(
        status_name, (status_name or "unknown").replace("_", " ").title())
    connector = _STATUS_APPROVER_CONNECTOR.get(status_name)
    if not connector:
        return base_label
    role_text = role.strip() if role and role.strip() else None
    name_text = name.strip() if name and name.strip() else None
    if not role_text and not name_text:
        return base_label
    display_role = ("HR" if role_text.lower() == "hr" else role_text.title()) if role_text else None
    if name_text and display_role:
        return f"{base_label} {connector} {name_text} ({display_role})"
    if name_text:
        return f"{base_label} {connector} {name_text}"
    return f"{base_label} {connector} {display_role}"


# ── /leave/applied cards (leave history: pending/approved/cancelled/
# rejected/all). erp-api live-confirmed 2026-08-21: this endpoint now
# returns total_days, approver_name, and role directly — an earlier version
# of this comment claimed those only ever existed on /leave/pending (now
# retired) and read the old leave_count field name instead; both were stale.
def _build_applied_leave_card(lv: dict) -> dict:
    reference = f"LR-{lv['id']}" if lv.get("id") is not None else None
    # total_days is erp-api's own authoritative figure (handles half-days
    # correctly, unlike a date-span count) — prefer it. leave_count is kept
    # as a fallback for whichever older response shape it belonged to, and
    # the date-span estimate only as a last resort if erp-api omits both.
    total_days = lv.get("total_days")
    if total_days is None:
        total_days = lv.get("leave_count")
    if total_days is None:
        total_days = _estimate_leave_days(lv.get("from_date"), lv.get("to_date"))
    leave_type_slug = lv.get("leave_type_slug")
    card = {
        "id": lv.get("id"),
        "leave_type": lv.get("leave_type"),
        "leave_type_slug": leave_type_slug,
        "leave_type_code": _LEAVE_TYPE_CODES.get(leave_type_slug),
        "session_type": lv.get("session_type"),
        "total_days": total_days,
        "from_date": lv.get("from_date"),
        "to_date": lv.get("to_date"),
        "status_name": lv.get("status_name"),
        "reason": lv.get("reason"),
        "rejection_reason": lv.get("rejection_reason"),
        "submitted_at": lv.get("applied_date"),
        "reference": reference,
        "approver_name": lv.get("approver_name"),
        "approver_role": lv.get("role"),
    }
    # Figma design's date format ("Thu, 30 Jul 2026" for one day, "14 – 15
    # Aug 2026" for a range, "28 Jul 2026" with no weekday for "Applied
    # on") — raw ISO dates are kept above too, for any caller that still
    # wants them unformatted.
    card["date_label"] = _display_date_range(card["from_date"], card["to_date"])
    card["submitted_at_label"] = _display_date(card["submitted_at"])
    if card["status_name"] == "pending":
        card["status_label"] = _pending_status_label(card["approver_role"], card["approver_name"])
    else:
        card["status_label"] = _decided_status_label(
            card["status_name"], card["approver_role"], card["approver_name"])
    return card


def _single_applied_leave_message(lv: dict) -> str:
    days_txt = f" ({_fmt_days(lv['total_days'])} day(s))" if lv.get("total_days") is not None else ""
    applied_txt = f" Applied on {lv['submitted_at']}." if lv.get("submitted_at") else ""
    status = lv.get("status_name") or "unknown"
    # Names the actual approver for EVERY status ("pending with Manager" /
    # "approved by John Smith (Manager)" / "rejected by John Smith
    # (Manager)"), not just pending — reuses the card's own status_label
    # (already computed by _build_applied_leave_card via
    # _pending_status_label / _decided_status_label) rather than re-deriving
    # it, so the two never drift. No separate "Approver: ..." sentence is
    # needed any more — status_label already folds the name/role in for
    # every status, so a second sentence would just repeat it. Only the
    # leading word is lowercased for mid-sentence use ("is pending with...",
    # "is approved by...") — .lower()-ing the whole label would mangle a
    # real approver's name ("john smith" instead of "John Smith"). A
    # rejected record folds its reason into the same clause ("is rejected by
    # John Smith (Manager) — fever") rather than a separate sentence.
    if lv.get("status_label"):
        label = lv["status_label"]
        status_phrase = label[0].lower() + label[1:]
    else:
        status_phrase = status
    reason_suffix = (
        f" — {lv['rejection_reason']}"
        if status == "rejected" and lv.get("rejection_reason") else ""
    )
    return (f"Your {lv['leave_type']} request ({lv['from_date']} to {lv['to_date']}){days_txt} "
            f"is {status_phrase}{reason_suffix}.{applied_txt}")


# "show me all my leaves" / "my applied leaves" / "leave history" — an
# explicit ask for every status at once, distinct from the ambiguous "show
# my leaves" case (which asks which subset is meant — see
# _LEAVE_HISTORY_AMBIGUITY below).
_ALL_LEAVES_WORDS = ("all", "every", "applied", "everything", "history")


def _is_all_leaves_request(query: str) -> bool:
    text = query.lower()
    return any(re.search(r"\b" + w + r"\b", text) for w in _ALL_LEAVES_WORDS)


def _resolve_disambiguation_reply(query: str, candidates: list) -> Optional[dict]:
    """Best-effort match of a 'which one did you mean' reply against the
    stored candidate cards — by the ISO date appearing literally in the
    reply, by the bare day-of-month number when it's unique among the
    candidates, or by a leave-type keyword. Returns the single matching
    card, or None if it can't confidently resolve to exactly one (caller
    falls back to re-showing the list rather than guessing)."""
    text = query.lower()

    date_matches = [c for c in candidates if c["from_date"] in query or c["to_date"] in query]
    if len(date_matches) == 1:
        return date_matches[0]

    # "the 30th" / "on 30" — only trustworthy when exactly one candidate's
    # from_date falls on that day-of-month; with two candidates both due on
    # the 30th (different months) this deliberately stays ambiguous.
    day_numbers = re.findall(r"\b(\d{1,2})(?:st|nd|rd|th)?\b", text)
    if day_numbers:
        day_matches = [
            c for c in candidates
            if any(c["from_date"].split("-")[-1].lstrip("0") == d.lstrip("0") for d in day_numbers)
        ]
        if len(day_matches) == 1:
            return day_matches[0]

    type_matches = [c for c in candidates if c["leave_type"] and c["leave_type"].lower() in text]
    if len(type_matches) == 1:
        return type_matches[0]

    return None


# ── Cancel-leave request matching (AC#1) ──────────────────────────────────────
# Deterministic matching against the employee's actual /leave/pending records —
# the LLM (via _build_leave_cancel_extraction_prompt) only extracts what a
# turn mentions (date/leave_type/request_id/is_affirmative); it never picks
# the request itself. Priority order per the LLD: explicit ID, then exact
# date, then leave type + date, then (nothing extracted at all) every
# candidate — a vague "cancel my leave" is meant to surface the full list,
# not guess.

# Closed, simple format ("LR-2041", "LR2041", "#2041") — a deterministic
# regex catches this far more reliably than waiting on the LLM for something
# this unambiguous, same reasoning as _extract_status_filter's word-list.
#
# Live bug: a plain \b before "#" never matched "#2041" preceded by a space
# (the normal case, "cancel #2041") — \b needs a word/non-word transition,
# and space->"#" is non-word->non-word, so no boundary exists there. It only
# ever matched the unusual no-space form ("cancel#2041"). (?<!\w)# (not
# preceded by a word character) replaces \b for that branch only, so it
# still matches at start-of-string or after whitespace/punctuation, but not
# mid-word.
#
# [\s-]* (not the old "-?") between "LR" and the digits — live gap:
# "lr 137" (a plain space, no hyphen — the single most natural way to say a
# reference out loud) never matched at all, since "-?" only ever allowed
# ZERO or ONE hyphen, never a space. Covers "LR137" / "LR-137" / "LR 137" /
# "LR - 137" alike, still case-insensitive so "lr137"/"Lr137" match too.
_CANCEL_REQUEST_ID_PATTERN = re.compile(r"(?:\bLR[\s-]*|(?<!\w)#)(\d+)\b", re.IGNORECASE)

# Live bug repro: "cancel leave 78" — no LR-/# prefix, so the pattern above
# never matched and the query fell through to the vague "show every
# candidate" path instead of going straight to LR-78. Scoped to a number
# immediately following "leave"/"request" (optionally "number"/"no."/"#" in
# between) rather than any bare digit in the query — this function is only
# ever called from the already-cancel-scoped flow, so there's no risk of it
# firing for an unrelated intent.
#
# That scoping alone still wasn't enough: "cancel my leave 1 jan 2020" has
# "leave 1" in exactly that same shape, and got misread as id=1 (live bug
# report, 2026-08-24) — it happened to match an unrelated already-decided
# record and reported "already decided" for a date that has no leave
# history at all, instead of "nothing found for that date". Likewise
# "cancel my leave 3 days" (no "for") misread the day-count as id=3.
# _BARE_CANCEL_ID_DATE_CONTINUATION rejects a number immediately followed by
# a month name ("1 jan"), a date separator ("25/12", "25-12"), or a duration
# unit ("3 days") — all of those mean the number is part of a DATE or a
# day-count, never a reference number.
_BARE_CANCEL_ID_DATE_CONTINUATION = (
    r"(?!\s*(?:st|nd|rd|th)?\s*(?:jan\w*|feb\w*|mar\w*|apr\w*|may\w*|jun\w*|jul\w*|"
    r"aug\w*|sep\w*|oct\w*|nov\w*|dec\w*)\b)"
    r"(?!\s*[/-]\s*\d)"
    r"(?!\s*(?:day|days|week|weeks|month|months)\b)"
)
_BARE_CANCEL_ID_PATTERN = re.compile(
    r"\b(?:leave|request)s?\s+(?:number\s+|no\.?\s+|#\s*)?(\d+)\b" + _BARE_CANCEL_ID_DATE_CONTINUATION,
    re.IGNORECASE,
)


def _extract_request_id(query: str) -> Optional[str]:
    m = _CANCEL_REQUEST_ID_PATTERN.search(query)
    if m:
        return m.group(1)
    m = _BARE_CANCEL_ID_PATTERN.search(query)
    return m.group(1) if m else None


def _normalize_extracted_request_id(value) -> Optional[str]:
    """The LLM cancel-extraction prompt explicitly allows request_id to come
    back as either "LR-2041" or "2041" (see
    _build_leave_cancel_extraction_prompt) — strip any "LR"/"#" prefix so it
    always ends up as bare digits, matching what the deterministic regex
    fallback (_extract_request_id) already returns. Live bug: an unstripped
    "LR-136" survived into the "reference LR-{id}" message template,
    producing "LR-LR-136"."""
    if not value:
        return None
    m = _CANCEL_REQUEST_ID_PATTERN.search(str(value))
    if m:
        return m.group(1)
    digits = re.sub(r"\D", "", str(value))
    return digits or None


def _card_matches_request_id(card: dict, request_id: str) -> bool:
    """Exact match on the numeric id only. Live bug: the old check did
    `request_id in ref` — a SUBSTRING test against the whole "LR-<id>"
    string — so asking for a non-existent "LR-2" wrongly matched "LR-42",
    "LR-12", "LR-20", any reference merely CONTAINING that digit sequence
    anywhere, rather than reporting nothing found. Compared as ints (not
    strings) so a leading-zero variant like "042" still matches id 42."""
    if card.get("id") is None:
        return False
    try:
        return int(request_id) == int(card["id"])
    except (TypeError, ValueError):
        return str(card["id"]) == str(request_id)


def _card_covers_date(card: dict, date_str: str) -> bool:
    from_date, to_date = card.get("from_date"), card.get("to_date")
    if not (from_date and to_date):
        return False
    try:
        from datetime import date
        d = date.fromisoformat(date_str)
        return date.fromisoformat(from_date) <= d <= date.fromisoformat(to_date)
    except (TypeError, ValueError):
        return False


def _card_matches_weekday(card: dict, weekday_index: int) -> bool:
    """Checks every day IN the candidate's span, not just from_date — a
    multi-day leave (e.g. Mon 24th to Wed 26th) named by a later day in its
    own span ("cancel my leave for Wednesday") must still match, not just
    one whose FIRST day happens to be that weekday."""
    from_date = card.get("from_date")
    if not from_date:
        return False
    try:
        from datetime import date, timedelta
        start = date.fromisoformat(from_date)
        to_date = card.get("to_date")
        end = date.fromisoformat(to_date) if to_date else start
        span_days = (end - start).days
        if not (0 <= span_days <= 366):  # malformed/reversed dates — fall back to from_date only
            return start.weekday() == weekday_index
        return any((start + timedelta(days=i)).weekday() == weekday_index for i in range(span_days + 1))
    except (TypeError, ValueError):
        return False


# Deterministic fallback for a bare weekday name ("Friday", "next Monday") —
# a closed vocabulary, same reasoning as _CANCEL_REQUEST_ID_PATTERN: live-
# probed 2026-08-19/20 and the LLM's own date resolution for this shape of
# phrase was unreliable ("cancel my leave for Friday" failed to narrow down
# at all). "Friday"/"this Friday" means the next occurrence of that weekday
# on/after today (today itself if today IS that weekday); "next Friday"
# explicitly means the occurrence in the FOLLOWING week.
_WEEKDAY_NAMES = {
    "monday": 0, "tuesday": 1, "wednesday": 2, "thursday": 3,
    "friday": 4, "saturday": 5, "sunday": 6,
}
_WEEKDAY_FULL_NAMES = list(_WEEKDAY_NAMES.keys())

# Common abbreviations — an enumerable, unambiguous closed list, so matched
# literally rather than through fuzzy scoring (a 3-letter abbreviation is
# too short for difflib to score safely against unrelated short words).
_WEEKDAY_ABBREVIATIONS = {
    "mon": "monday",
    "tue": "tuesday", "tues": "tuesday",
    "wed": "wednesday", "weds": "wednesday",
    "thu": "thursday", "thur": "thursday", "thurs": "thursday",
    "fri": "friday",
    "sat": "saturday",
    "sun": "sunday",
}
_WEEKDAY_WORD_PATTERN = re.compile(
    r"\b(next\s+)?(" + "|".join(_WEEKDAY_FULL_NAMES + list(_WEEKDAY_ABBREVIATIONS.keys())) + r")\b",
    re.IGNORECASE,
)

# Typo tolerance for a misspelled full name ("moday", "momday", "wensday",
# "thersday") — empirically swept 2026-08-24 against real typos and
# plausible false-positive English words (same methodology as the
# unconfigured-leave-type typo tolerance in leave_eligibility_service.py,
# a different cutoff here since weekday names collide with different words).
# 0.8 is the safe floor: 0.75 false-matched "today" (ratio 0.727 vs
# "monday") and "money" (0.727 vs "monday") — which would have silently
# corrupted the already-correct today/tomorrow/yesterday relative-day
# resolution — while 0.8 still catches every tested real typo (momday/
# mondey/fridey/wedsday/saterday/etc, all >=0.833). "sundae" (0.833) is the
# one known false positive at this cutoff — accepted as negligible, it's
# not a plausible word in a leave-cancellation query.
_WEEKDAY_TYPO_CUTOFF = 0.8
_WEEKDAY_TYPO_TOKEN_PATTERN = re.compile(r"\b(next\s+)?([a-z]{4,10})\b", re.IGNORECASE)


def _resolve_weekday_mention(query: str) -> Optional[tuple[bool, int]]:
    """Finds the first weekday mentioned in `query` — a full name ("Friday"),
    a common abbreviation ("fri", "thurs"), or a typo of the full name
    ("moday", "wensday") — and returns (explicit_next, weekday_index).
    None if nothing resolves. Centralizes all three ways of recognizing a
    weekday so every caller (_resolve_weekday_date, the cancel-candidate
    matcher, the search-criterion label) gets the same tolerance for free."""
    m = _WEEKDAY_WORD_PATTERN.search(query)
    if m:
        word = m.group(2).lower()
        full_name = _WEEKDAY_ABBREVIATIONS.get(word, word)
        return bool(m.group(1)), _WEEKDAY_NAMES[full_name]

    for tm in _WEEKDAY_TYPO_TOKEN_PATTERN.finditer(query):
        token = tm.group(2).lower()
        close = difflib.get_close_matches(token, _WEEKDAY_FULL_NAMES, n=1, cutoff=_WEEKDAY_TYPO_CUTOFF)
        if close:
            return bool(tm.group(1)), _WEEKDAY_NAMES[close[0]]
    return None


def _resolve_weekday_date(query: str) -> Optional[str]:
    resolved = _resolve_weekday_mention(query)
    if not resolved:
        return None
    explicit_next, target_weekday = resolved
    from datetime import timedelta
    today = _today()
    days_ahead = (target_weekday - today.weekday()) % 7
    if explicit_next:
        days_ahead = days_ahead + 7 if days_ahead > 0 else 7
    return (today + timedelta(days=days_ahead)).isoformat()


# Deterministic single-day fallback for the same closed-vocabulary reason as
# _resolve_weekday_date — "today"/"yesterday"/"tomorrow" are exactly the
# kind of relative-date phrasing this codebase has already found an LLM
# unreliable on for a bare weekday name, so these are resolved locally too
# rather than trusted to the model. "day before "/"day after " each shift
# the named day by one more (so "day after tomorrow" = +2, "day before
# yesterday" = -2, "day after yesterday" = 0 — colloquial for today) —
# applied as a uniform +-1 delta on top of the bare word's own offset.
# Typo tolerance (difflib, cutoff swept against real typos and common query
# vocabulary with no false positives at 0.8) reuses the same weekday-typo
# reasoning above, extended to this word list.
_RELATIVE_DAY_WORDS = ["yesterday", "tomorrow", "today"]
_RELATIVE_DAY_BASE_OFFSETS = {"yesterday": -1, "today": 0, "tomorrow": 1}
_RELATIVE_DAY_PREFIX_DELTAS = {"before": -1, "after": 1}
_RELATIVE_DAY_PATTERN = re.compile(
    r"\b(day\s+(?:before|after)\s+)?(yesterday|tomorrow|today)\b", re.IGNORECASE,
)
_RELATIVE_DAY_TYPO_CUTOFF = 0.8
_RELATIVE_DAY_TYPO_TOKEN_PATTERN = re.compile(
    r"\b(day\s+(?:before|after)\s+)?([a-z]{4,10})\b", re.IGNORECASE,
)


def _resolve_relative_day_date(query: str) -> Optional[str]:
    from datetime import timedelta
    text = query.lower()

    m = _RELATIVE_DAY_PATTERN.search(text)
    if m:
        prefix, word = m.group(1), m.group(2)
    else:
        prefix = word = None
        for tm in _RELATIVE_DAY_TYPO_TOKEN_PATTERN.finditer(text):
            token = tm.group(2)
            close = difflib.get_close_matches(
                token, _RELATIVE_DAY_WORDS, n=1, cutoff=_RELATIVE_DAY_TYPO_CUTOFF,
            )
            if close:
                prefix, word = tm.group(1), close[0]
                break
        if word is None:
            return None

    offset = _RELATIVE_DAY_BASE_OFFSETS[word]
    if prefix:
        offset += _RELATIVE_DAY_PREFIX_DELTAS[prefix.strip().split()[1]]
    today = _today()
    return (today + timedelta(days=offset)).isoformat()


# Deterministic month-name resolver — same closed-vocabulary reasoning as
# _resolve_weekday_date, extended to "25 aug"/"aug 25"/"25th August, 2026"/
# "1 jan 2020" style mentions. Year defaults to the CURRENT year when not
# stated — a cancel target is just as often a past leave within this year
# as a future one, never assumed to roll to next year the way an explicit
# "next <weekday>" phrase would.
_MONTH_NAMES = {
    "january": 1, "jan": 1,
    "february": 2, "feb": 2,
    "march": 3, "mar": 3,
    "april": 4, "apr": 4,
    "may": 5,
    "june": 6, "jun": 6,
    "july": 7, "jul": 7,
    "august": 8, "aug": 8,
    "september": 9, "sep": 9, "sept": 9,
    "october": 10, "oct": 10,
    "november": 11, "nov": 11,
    "december": 12, "dec": 12,
}
_MONTH_FULL_NAMES = [
    "january", "february", "march", "april", "may", "june", "july",
    "august", "september", "october", "november", "december",
]
# "may" excluded from FUZZY typo matching only (still resolved normally via
# the exact dict above) — as a real month AND an extremely common English
# word ("I have many leaves left"), fuzzy-scoring anything near it is
# unsafe: empirically (2026-08-24 sweep), "many"/"mayo" both score above
# the cutoff that catches genuine month typos like "septmber"/"agust".
_MONTH_FUZZY_CANDIDATES = [m for m in _MONTH_FULL_NAMES if m != "may"]
_MONTH_TYPO_CUTOFF = 0.85

_MONTH_NAME_ALTERNATION = "|".join(sorted(_MONTH_NAMES.keys(), key=len, reverse=True))
_MONTH_NAME_TOKEN_PATTERN = re.compile(r"\b(" + _MONTH_NAME_ALTERNATION + r")\b", re.IGNORECASE)
_DAY_MONTH_YEAR_PATTERN = re.compile(
    r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(" + _MONTH_NAME_ALTERNATION + r")\.?,?\s*(\d{4})?\b",
    re.IGNORECASE,
)
_MONTH_DAY_YEAR_PATTERN = re.compile(
    r"\b(" + _MONTH_NAME_ALTERNATION + r")\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s*(\d{4})?\b",
    re.IGNORECASE,
)
# Same two shapes, but capturing ANY short word instead of a known month
# name — tried only when the exact patterns above find nothing, so a typo
# ("25 agust") can still resolve via _resolve_month_word's fuzzy fallback.
_DAY_WORD_YEAR_PATTERN = re.compile(
    r"\b(\d{1,2})(?:st|nd|rd|th)?\s+([a-z]{3,10})\.?,?\s*(\d{4})?\b", re.IGNORECASE,
)
_WORD_DAY_YEAR_PATTERN = re.compile(
    r"\b([a-z]{3,10})\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s*(\d{4})?\b", re.IGNORECASE,
)


def _resolve_month_word(word: str) -> Optional[int]:
    word = word.lower()
    if word in _MONTH_NAMES:
        return _MONTH_NAMES[word]
    close = difflib.get_close_matches(word, _MONTH_FUZZY_CANDIDATES, n=1, cutoff=_MONTH_TYPO_CUTOFF)
    return _MONTH_NAMES[close[0]] if close else None


def _resolve_absolute_date_mention(query: str) -> Optional[str]:
    from datetime import date
    today = _today()

    for pattern, day_first_group_order in (
        (_DAY_MONTH_YEAR_PATTERN, True), (_MONTH_DAY_YEAR_PATTERN, False),
        (_DAY_WORD_YEAR_PATTERN, True), (_WORD_DAY_YEAR_PATTERN, False),
    ):
        m = pattern.search(query)
        if not m:
            continue
        if day_first_group_order:
            day_str, month_word, year_str = m.group(1), m.group(2), m.group(3)
        else:
            month_word, day_str, year_str = m.group(1), m.group(2), m.group(3)
        month = _resolve_month_word(month_word)
        if not month:
            continue
        try:
            year = int(year_str) if year_str else today.year
            return date(year, month, int(day_str)).isoformat()
        except (TypeError, ValueError):
            continue
    return None


# Deterministic numeric DD/MM(/YYYY) resolver — "14/08", "14-08-2026". Day-
# first per this codebase's established convention (see the LLM prompts'
# own "CRITICAL: never default to US month-first" instructions) whenever
# that reading is valid; only falls back to the other ordering when day-
# first would be an invalid date outright (e.g. "08/14": month=14 doesn't
# exist, so 14 must be the day and 08 the month, regardless of position).
_NUMERIC_DATE_PATTERN = re.compile(r"\b(\d{1,2})[/-](\d{1,2})(?:[/-](\d{2,4}))?\b")


def _resolve_numeric_date_mention(query: str) -> Optional[str]:
    from datetime import date
    m = _NUMERIC_DATE_PATTERN.search(query)
    if not m:
        return None
    a, b = int(m.group(1)), int(m.group(2))
    year_str = m.group(3)
    if year_str:
        year = int(year_str)
        if year < 100:
            year += 2000
    else:
        year = _today().year

    try:
        return date(year, b, a).isoformat()  # day-first: a=day, b=month
    except ValueError:
        pass
    try:
        return date(year, a, b).isoformat()  # only valid the other way around
    except ValueError:
        return None


_EXPLICIT_YEAR_IN_QUERY_PATTERN = re.compile(r"\b(19|20)\d{2}\b")


def _roll_apply_dates_forward_if_past(extracted: dict, query: str) -> None:
    """Mutates extracted in place: if the LLM resolved a bare month/day
    mention ("15th November") with no year to a date that's already in the
    PAST, rolls from_date/to_date forward by exactly one year.

    Unlike cancel-leave (where a past date is a completely normal, common
    target — see _resolve_absolute_date_mention's current-year default),
    applying for a leave can only ever be for today or the future, so an
    ambiguous no-year mention should always resolve to the NEXT occurrence,
    same reasoning as _resolve_weekday_date's "next Friday" default. Live
    bug report (2026-08-24): "apply for leave for 15th november" (no year)
    came back from the LLM as a past date and got rejected as such, while
    "...15th november 2026" worked fine — confirming the LLM's own
    year-inference is the unreliable part, not the day/month.

    Only fires when the query itself names a month (by word — "November",
    "Nov") with no explicit year alongside it. Scoped this tightly on
    purpose: "today"/"tomorrow"/a bare weekday are relative phrases the LLM
    resolves against a KNOWN reference point and have no year-inference step
    to get wrong at all, so a past-dated extraction for one of those means
    something else is going on (test fixtures using an arbitrary fixed date,
    a genuine extraction mistake) — not this specific bug, and not this
    function's business to silently "fix" by shifting the date a full year.
    """
    from datetime import date, timedelta

    if not _MONTH_NAME_TOKEN_PATTERN.search(query):
        return
    if _EXPLICIT_YEAR_IN_QUERY_PATTERN.search(query):
        return
    from_date, to_date = extracted.get("from_date"), extracted.get("to_date")
    if not (from_date and to_date):
        return
    try:
        f = date.fromisoformat(from_date)
        t = date.fromisoformat(to_date)
    except (TypeError, ValueError):
        return
    if f >= _today():
        return  # already a future (or today) date — nothing to correct
    span = t - f
    try:
        new_from = f.replace(year=f.year + 1)
    except ValueError:
        new_from = f.replace(year=f.year + 1, day=28)  # Feb 29 -> Feb 28 in a non-leap year
    extracted["from_date"] = new_from.isoformat()
    extracted["to_date"] = (new_from + span).isoformat()


def _add_explicit_year_hint(query: str) -> str:
    """Appends the correct explicit year to a bare month/day mention BEFORE
    it ever reaches the LLM extraction prompt, instead of only correcting
    the date AFTER the fact — removes the model's year-guessing at the
    source rather than second-guessing its answer. Live-confirmed: "...15th
    november 2026" (year given) always resolved correctly; only the bare
    "...15th november" (no year) form triggered the faulty guess. Giving it
    the exact same explicit-year input the working case already has closes
    that gap directly.

    The year is computed dynamically from today's actual date each call
    (never hardcoded) — the CURRENT year, unless that day/month has already
    passed this year, in which case NEXT year — using the SAME deterministic
    day/month parser already built for cancel-leave
    (_resolve_absolute_date_mention), so this and the fallback correction in
    _roll_apply_dates_forward_if_past can never disagree with each other.
    """
    from datetime import date

    if not _MONTH_NAME_TOKEN_PATTERN.search(query) or _EXPLICIT_YEAR_IN_QUERY_PATTERN.search(query):
        return query
    resolved = _resolve_absolute_date_mention(query)
    if not resolved:
        return query
    try:
        d = date.fromisoformat(resolved)
    except ValueError:
        return query
    if d < _today():
        try:
            d = d.replace(year=d.year + 1)
        except ValueError:
            d = d.replace(year=d.year + 1, day=28)  # Feb 29 -> Feb 28 in a non-leap year
    return f"{query} {d.year}"


# Deterministic date-RANGE resolver for the "show my leaves" clarify's date
# dimension — same closed-vocabulary philosophy as _resolve_weekday_date.
# Handles relative phrases ("this month", "last 3 months") and an explicit
# "YYYY-MM-DD to YYYY-MM-DD" / "YYYY-MM-DD - YYYY-MM-DD" range. Returns
# (from_date, to_date) as ISO strings, or (None, None) if no range phrase is
# found at all (including explicit "all time"/"anytime"/"everything" —
# meaning don't filter by date).
_EXPLICIT_DATE_RANGE_PATTERN = re.compile(
    r"\b(\d{4}-\d{2}-\d{2})\s*(?:to|-|through|until)\s*(\d{4}-\d{2}-\d{2})\b", re.IGNORECASE,
)
_RELATIVE_N_UNIT_PATTERN = re.compile(
    r"\blast\s+(\d{1,2})\s+(day|days|week|weeks|month|months)\b", re.IGNORECASE,
)
_ORDINAL_WEEK_WORDS = {
    "1st": 1, "first": 1, "2nd": 2, "second": 2,
    "3rd": 3, "third": 3, "4th": 4, "fourth": 4,
}
_ORDINAL_WEEK_OF_MONTH_PATTERN = re.compile(
    r"\b(1st|first|2nd|second|3rd|third|4th|fourth)\s+week\b", re.IGNORECASE,
)


def _resolve_date_range_phrase(query: str) -> tuple[Optional[str], Optional[str]]:
    from datetime import date, timedelta

    text = query.lower()
    today = _today()

    m = _EXPLICIT_DATE_RANGE_PATTERN.search(query)
    if m:
        return m.group(1), m.group(2)

    if re.search(r"\b(all\s*time|anytime|any\s+time|everything|whole\s+history|all\s+days?)\b", text):
        return None, None

    # Checked BEFORE the plain "yesterday" branch below — "day before
    # yesterday" contains "yesterday" as a substring, so the plain check
    # would otherwise match first and silently drop the "day before" part.
    if re.search(r"\bday\s+before\s+yesterday\b", text):
        d = (today - timedelta(days=2)).isoformat()
        return d, d
    if re.search(r"\btoday\b", text):
        return today.isoformat(), today.isoformat()
    if re.search(r"\byesterday\b", text):
        d = (today - timedelta(days=1)).isoformat()
        return d, d
    if re.search(r"\btomorrow\b", text):
        d = (today + timedelta(days=1)).isoformat()
        return d, d

    m = _RELATIVE_N_UNIT_PATTERN.search(text)
    if m:
        n = int(m.group(1))
        unit = m.group(2)
        if unit.startswith("day"):
            delta = timedelta(days=n)
        elif unit.startswith("week"):
            delta = timedelta(weeks=n)
        else:  # month(s) — 30-day approximation, good enough for a display filter
            delta = timedelta(days=n * 30)
        return (today - delta).isoformat(), today.isoformat()

    # Ordinal week OF THE CURRENT MONTH ("1st week", "2nd week of this
    # month") — checked before the bare "this/current week" (calendar week)
    # branch below since they're different concepts sharing the word
    # "week". Week 1 = days 1-7, week 2 = days 8-14, etc.; the last ordinal
    # week of a short month runs to the month's actual last day.
    m = _ORDINAL_WEEK_OF_MONTH_PATTERN.search(text)
    if m:
        n = _ORDINAL_WEEK_WORDS[m.group(1)]
        start_day = (n - 1) * 7 + 1
        last_day_of_month = _last_day_of_month(today.year, today.month)
        if start_day > last_day_of_month:
            return None, None
        end_day = min(start_day + 6, last_day_of_month)
        return (date(today.year, today.month, start_day).isoformat(),
                date(today.year, today.month, end_day).isoformat())

    if re.search(r"\b(this|current)\s+week\b", text):
        start = today - timedelta(days=today.weekday())
        return start.isoformat(), today.isoformat()
    if re.search(r"\blast\s+week\b", text):
        this_week_start = today - timedelta(days=today.weekday())
        last_week_start = this_week_start - timedelta(days=7)
        last_week_end = this_week_start - timedelta(days=1)
        return last_week_start.isoformat(), last_week_end.isoformat()

    # "month starting" — shorthand for "from the start of this month",
    # same as "this month" below.
    if re.search(r"\b(this\s+month|month\s+start(?:ing)?)\b", text):
        return today.replace(day=1).isoformat(), today.isoformat()
    if re.search(r"\blast\s+month\b", text):
        first_of_this_month = today.replace(day=1)
        last_month_end = first_of_this_month - timedelta(days=1)
        last_month_start = last_month_end.replace(day=1)
        return last_month_start.isoformat(), last_month_end.isoformat()

    if re.search(r"\bthis\s+year\b", text):
        return today.replace(month=1, day=1).isoformat(), today.isoformat()
    if re.search(r"\blast\s+year\b", text):
        return date(today.year - 1, 1, 1).isoformat(), date(today.year - 1, 12, 31).isoformat()

    return None, None


# ── date_resolver-backed fallback for leave-status date filtering ─────────
# _resolve_date_range_phrase above is this file's own long-standing
# deterministic resolver and stays the FIRST thing tried (unchanged) — it
# already covers everything it's ever been asked to. This is a second,
# independent fallback for phrasing it was never built for: an absolute
# named-month mention like "21th august" (no year, no weekday, no
# "this/last" qualifier) — date_resolver deliberately doesn't handle those
# either (see its module docstring), so this ultimately falls through to a
# real LLM call, exactly like the apply-leave flow's own tier-2/tier-3
# fallback does for dates neither deterministic layer recognizes. Ported
# from hr_graph.py's since-deleted duplicate leave_action_node.
def _resolve_deterministic_date_range(query: str, today) -> Optional[tuple[str, str]]:
    """Same precedence chain as _apply_deterministic_date_overrides (explicit
    two-sided range -> named-week range -> weekday range -> single relative
    date, plus a trailing duration count), generalized as an independent,
    side-effect-free function that just answers "what date range does this
    query name" — no `slots`/`extracted` dict to reconcile a partial LLM
    guess against, since callers here (leave-status) have no such partial
    guess to begin with.

    Deliberately NOT sharing code with _apply_deterministic_date_overrides —
    that function carries extensive, individually-live-bug-fixed
    apply-leave-specific reconciliation logic and its own test coverage;
    duplicating this ~20-line precedence skeleton here is a smaller, safer
    change than restructuring it, and leaves the apply-leave flow's tested
    behavior completely untouched."""
    from datetime import date, timedelta

    range_result = date_resolver.resolve_date_range_phrase(query, today)
    if range_result and range_result[1] is not None:
        first, second = range_result
        return first["from_date"], second["from_date"]

    week_result = date_resolver.resolve_week_of_month_phrase(query, today)
    week_narrowed_to_weekday = None
    if week_result:
        first, second = week_result
        week_narrowed_to_weekday = date_resolver.weekday_within_span(
            query, date.fromisoformat(first["from_date"]), date.fromisoformat(second["from_date"]),
        )
        if week_narrowed_to_weekday is None:
            return first["from_date"], second["from_date"]

    weekday_range_result = date_resolver.resolve_relative_date_range_phrase(query, today)
    if weekday_range_result and weekday_range_result[1] is not None:
        first, second = weekday_range_result
        return first["from_date"], second["from_date"]

    resolved = (
        range_result[0] if range_result
        else weekday_range_result[0] if weekday_range_result
        else week_narrowed_to_weekday if week_narrowed_to_weekday
        else date_resolver.resolve_relative_date_phrase(query, today)
    )
    if not resolved:
        return None

    from_date = resolved["from_date"]
    to_date = from_date
    duration_days = date_resolver.extract_duration_days(query)
    if duration_days:
        try:
            to_date = (date.fromisoformat(from_date) + timedelta(days=duration_days - 1)).isoformat()
        except (TypeError, ValueError):
            pass
    return from_date, to_date


async def _resolve_date_range(
    query: str, today, purpose_hint: Optional[str] = None,
) -> Optional[tuple[str, str]]:
    """Deterministic-first, LLM-fallback date/range extraction.
    'show my leave details for 21th august' -> ('2026-08-21', '2026-08-21').

    date_resolver's own module docstring is explicit about why the
    deterministic chain always runs first here, not the LLM: "do not rely
    only on the LLM to calculate dates" (see date_resolver.py and
    _apply_deterministic_date_overrides). The LLM is only ever consulted
    for phrasing the deterministic resolver doesn't recognize, and told
    explicitly what the date is for via purpose_hint. Fails open (returns
    None) on any error, same contract as the rest of this feature's
    advisory calls."""
    deterministic = _resolve_deterministic_date_range(query, today)
    if deterministic:
        return deterministic
    try:
        prompt = _build_date_range_extraction_prompt(query, today, purpose_hint)
        raw = await _call_llm(prompt, max_tokens=60, model=INTENT_MODEL)
        parsed = _safe_json_parse(_extract_text(raw))
    except Exception as e:
        logger.warning(f"[Graph] date range extraction failed: {e}")
        return None
    from_date = parsed.get("from_date")
    if not from_date:
        return None
    return from_date, parsed.get("to_date") or from_date


def _last_day_of_month(year: int, month: int) -> int:
    from datetime import date, timedelta
    next_month_first = date(year + 1, 1, 1) if month == 12 else date(year, month + 1, 1)
    return (next_month_first - timedelta(days=1)).day


def _leave_overlaps_range(lv: dict, date_from: str, date_to: str) -> bool:
    try:
        from datetime import date
        lv_from = date.fromisoformat(lv.get("from_date"))
        lv_to = date.fromisoformat(lv.get("to_date"))
        return lv_from <= date.fromisoformat(date_to) and date.fromisoformat(date_from) <= lv_to
    except (TypeError, ValueError):
        return True  # malformed/missing dates on the record — don't hide it, show it


def _submitted_in_range(lv: dict, date_from: str, date_to: str) -> bool:
    try:
        from datetime import date
        submitted = date.fromisoformat(lv.get("submitted_at"))
        return date.fromisoformat(date_from) <= submitted <= date.fromisoformat(date_to)
    except (TypeError, ValueError):
        return False


def _describe_search_date(query: str, date_str: Optional[str]) -> Optional[str]:
    """Human label for a date-based cancel search term — prefers the
    CANONICAL weekday name ("Friday") over the internal resolved ISO date,
    since for a bare weekday name that resolved date is only ever the NEXT
    occurrence (see _resolve_weekday_date) and is not necessarily the actual
    date of the matching request(s): a recent PAST Friday is a common, valid
    match too (live case, 2026-08-24). The canonical name is shown even when
    the employee typed an abbreviation or a typo ("fri", "moday") — echoing
    the misspelling back would look like the assistant got it wrong too.
    Falls back to the formatted resolved date for anything else (an
    explicit date, "tomorrow", "next Friday" — genuinely future and
    unambiguous)."""
    resolved = _resolve_weekday_mention(query)
    if resolved and not resolved[0]:
        return _WEEKDAY_FULL_NAMES[resolved[1]].title()
    if date_str:
        return _display_date(date_str) or date_str
    return None


def _describe_search_criterion(query: str, extracted: dict) -> Optional[str]:
    """Human-readable echo of whatever single criterion (reference/date/
    type) a cancel search was narrowed by, for the 'I found one request
    matching X' lead-in. Mirrors the same priority order _match_cancel_
    candidates uses (id, then date, then type)."""
    request_id = extracted.get("request_id") or _extract_request_id(query)
    if request_id:
        text = str(request_id)
        return text if text.upper().startswith("LR") else f"LR-{text}"
    if extracted.get("date") and extracted.get("date_to") and extracted["date_to"] != extracted["date"]:
        return _display_date_range(extracted["date"], extracted["date_to"])
    if extracted.get("date"):
        return _describe_search_date(query, extracted["date"])
    if extracted.get("leave_type"):
        return extracted["leave_type"].replace("_", " ").title()
    range_from, range_to = _resolve_date_range_phrase(query)
    if range_from and range_to:
        return _display_date_range(range_from, range_to)
    return None


def _match_cancel_candidates(cards: list[dict], extracted: dict, query: str) -> list[dict]:
    """Each specific criterion (id/date/type) returns IMMEDIATELY once
    checked — including an empty list when it matches nothing — rather than
    falling through to try the next criterion or to 'return everything'.
    That fallthrough used to hide a real 'nothing found for that date/id'
    case behind a silent 'show all candidates' response (a live bug report,
    2026-08-20); only a message with NO usable criterion at all (the final
    'return list(cards)' below) is meant to show everything."""
    request_id = extracted.get("request_id") or _extract_request_id(query)
    if request_id:
        return [c for c in cards if _card_matches_request_id(c, str(request_id))]

    leave_type = extracted.get("leave_type")

    # An explicit two-date SPAN ("cancel my leave from 25 Aug to 29 Aug")
    # describes the leave record's OWN from/to dates, not a calendar-period
    # filter like "last week" below — matched against the candidate's exact
    # span first (the employee is describing a specific request), falling
    # back to "does this candidate's span overlap the given range at all"
    # only if no candidate matches it exactly (e.g. the employee misremembered
    # the exact end date by a day).
    date_from_explicit = extracted.get("date")
    date_to_explicit = extracted.get("date_to")
    if date_from_explicit and date_to_explicit and date_to_explicit != date_from_explicit:
        exact_span = [
            c for c in cards
            if c.get("from_date") == date_from_explicit and c.get("to_date") == date_to_explicit
        ]
        by_span = exact_span or [c for c in cards if _leave_overlaps_range(c, date_from_explicit, date_to_explicit)]
        if leave_type:
            by_type_and_span = [c for c in by_span if c.get("leave_type") and leave_type in c["leave_type"].lower().replace(" ", "_")]
            return by_type_and_span if by_type_and_span else by_span
        return by_span

    # Resolved here too (not just in _extract_cancel_fields) so that a bare
    # weekday/relative-day reply also works when this is re-run scoped to a
    # stored candidate list (_resolve_cancel_selection passes extracted={}).
    date_str = (
        extracted.get("date") or _resolve_weekday_date(query) or _resolve_relative_day_date(query)
        or _resolve_absolute_date_mention(query) or _resolve_numeric_date_mention(query)
    )
    if date_str:
        by_date = [c for c in cards if _card_covers_date(c, date_str)]
        if not by_date:
            # A bare weekday name ("Friday") only ever resolves to the NEXT
            # occurrence on/after today (see _resolve_weekday_date) — but
            # the request the employee means is just as often a recent PAST
            # Friday still sitting in their pending/approved list (live bug
            # report, 2026-08-24: "cancel my leave request for friday" found
            # nothing because the only Friday leave on file was days behind
            # "today", not ahead of it). When the exact resolved date comes
            # up empty and the query used a bare weekday word (not an
            # explicit "next <weekday>", which IS strictly future), fall
            # back to matching by weekday-of-week against the candidates'
            # own dates instead of the single computed date.
            resolved = _resolve_weekday_mention(query)
            if resolved and not resolved[0]:
                by_date = [c for c in cards if _card_matches_weekday(c, resolved[1])]
        if not by_date:
            # The date named might be when the leave was APPLIED FOR
            # ("submitted_at"), not the leave's own from/to dates — the
            # disambiguation prompts explicitly offer "applied date" as
            # something the employee can specify, so it needs to actually
            # resolve to something rather than just being empty words.
            by_date = [c for c in cards if c.get("submitted_at") == date_str]
        if leave_type:
            by_type_and_date = [c for c in by_date if c.get("leave_type") and leave_type in c["leave_type"].lower().replace(" ", "_")]
            return by_type_and_date if by_type_and_date else by_date
        return by_date

    # A date RANGE phrase ("last week", "this month", "1st week", "day
    # before yesterday" already covered above as a single day — this is the
    # multi-day cases) — reuses the same resolver the leave_status/"show my
    # leaves" branch uses, so cancel and status share one date vocabulary.
    # "all time"/"all days" resolves to (None, None) here too, meaning "no
    # date filter" — falls through same as no range phrase at all.
    range_from, range_to = _resolve_date_range_phrase(query)
    if range_from and range_to:
        by_range = [c for c in cards if _leave_overlaps_range(c, range_from, range_to)]
        if not by_range:
            # Same reasoning as the single-day applied-date fallback above
            # — "cancel my leave applied last week" describes WHEN it was
            # submitted, not the leave's own dates.
            by_range = [c for c in cards if _submitted_in_range(c, range_from, range_to)]
        if leave_type:
            by_type_and_range = [c for c in by_range if c.get("leave_type") and leave_type in c["leave_type"].lower().replace(" ", "_")]
            return by_type_and_range if by_type_and_range else by_range
        return by_range

    if leave_type:
        return [c for c in cards if c.get("leave_type") and leave_type in c["leave_type"].lower().replace(" ", "_")]

    # Nothing usable extracted — vague "cancel my leave"/"cancel my request".
    # Per AC#1, never guess: surface every active candidate for selection.
    return list(cards)


# Ordinal words for a selection reply like "the second one" — numerals
# ("1", "2") are parsed directly, this only covers the spelled-out form.
_ORDINAL_WORDS = {
    "first": 1, "second": 2, "third": 3, "fourth": 4, "fifth": 5,
    "sixth": 6, "seventh": 7, "eighth": 8, "ninth": 9, "tenth": 10,
}


def _resolve_cancel_selection(
    query: str, candidates: list[dict], extracted: Optional[dict] = None,
) -> Optional[dict]:
    """Resolves a reply to an 'awaiting_selection' prompt against the stored
    candidate list — by position (number or ordinal word), by reference ID,
    or by re-running the same date/type matcher scoped to just these
    candidates. Returns None if the reply still doesn't narrow to exactly
    one — the caller re-shows the list rather than guessing.

    `extracted` should be the SAME LLM+deterministic extraction the initial
    cancel turn uses (_extract_cancel_fields), not just the deterministic
    weekday/relative-day patterns alone — a reply naming an absolute date
    ("24 aug", "24/08") has no deterministic parser here (same reasoning as
    _extract_cancel_fields itself), so without the LLM pass this fell
    through to 'nothing matched' and repeated the same re-ask forever (live
    bug, 2026-08-24: 'cancel my leave request for 24 aug', as a SELECTION
    reply, never resolved even though LR-84 is dated exactly 2026-08-24).
    Callers that can't provide it (tests exercising this in isolation) may
    omit it — deterministic-only matching still applies."""
    text = query.lower().strip()
    extracted = extracted or {}

    request_id = extracted.get("request_id") or _extract_request_id(query)
    if request_id:
        by_id = [c for c in candidates if _card_matches_request_id(c, str(request_id))]
        if len(by_id) == 1:
            return by_id[0]
        # An explicit reference number that matches NOTHING in this
        # candidate list must not fall through to the positional/ordinal
        # checks below — live bug: "LR-3" naming a reference that doesn't
        # exist in the list got silently reinterpreted as "pick the 3rd
        # item" whenever the un-matched number was small enough to also
        # look like a position. The caller gives an honest "couldn't find
        # that reference" answer instead of guessing a candidate.
        return None

    m = re.search(r"\b(\d{1,2})\b", text)
    if m:
        idx = int(m.group(1))
        if 1 <= idx <= len(candidates):
            return candidates[idx - 1]

    for word, idx in _ORDINAL_WORDS.items():
        if re.search(r"\b" + word + r"\b", text) and idx <= len(candidates):
            return candidates[idx - 1]

    narrowed = _match_cancel_candidates(candidates, extracted, query)
    if len(narrowed) == 1:
        return narrowed[0]

    return None


def _slug_for_leave_type(leave_type_value: Optional[str], leave_quota: dict) -> Optional[str]:
    """Best-effort join between a /leave/pending record's 'leave_type' string
    (representation not guaranteed identical to /leave/balance's slug keys)
    and a leave_quota slug — snake-cased normalization first (covers the
    common case, e.g. 'Casual Leave' -> 'casual_leave'), then a
    title-case-reversal fallback matched against each known slug."""
    if not leave_type_value:
        return None
    candidate = leave_type_value.strip().lower().replace(" ", "_").replace("-", "_")
    if candidate in leave_quota:
        return candidate
    for slug in leave_quota:
        if slug.replace("_", " ").lower() == leave_type_value.strip().lower():
            return slug
    return None


# AC#6 — conversational next actions, consistent across every leave branch
# (not just pending-status): balance, status, and a successful apply all end
# with a relevant suggestion instead of just stopping. The cancel_leave
# intent itself is real and routed (see the cancel branch below); only the
# underlying erp-api cancel ACTION is still stubbed, so this suggestion is
# honest about what it leads to today, not aspirational copy.
_LEAVE_STATUS_FOLLOWUPS = [
    "Would you like to check your leave balance?",
    "Would you like to apply for leave?",
]
_LEAVE_STATUS_CANCEL_SUGGESTION = "You can also ask me to cancel a pending or approved request."
_LEAVE_BALANCE_FOLLOWUPS = [
    "Would you like to check your pending leave requests?",
    "Would you like to apply for leave?",
]
_APPLY_SUCCESS_FOLLOWUPS = [
    "Would you like to check its status?",
    "Need to apply for another leave?",
]


# erp-api's leave_quota keys (confirmed live against a real employee account:
# casual_leave, sick_leave, earned_leave, short_leave, comp_off,
# leave_without_pay) mapped from the words a user would naturally say.
# Multi-word/hyphenated phrases use substring match; single words use a
# word-boundary regex — same convention as nlp_service.py's _keyword_matches.
_LEAVE_TYPE_FILTER_WORDS: dict[str, str] = {
    "casual": "casual_leave",
    "sick": "sick_leave",
    "earned": "earned_leave",
    "short leave": "short_leave",
    "comp off": "comp_off",
    "comp-off": "comp_off",
    "compoff": "comp_off",
    "leave without pay": "leave_without_pay",
    "unpaid": "leave_without_pay",
    "lwp": "leave_without_pay",
}


def _extract_leave_type_filters(query: str) -> list[str]:
    """'How many SICK leaves do I have left' -> ['sick_leave']. Without this,
    a question naming one specific leave type got the exact same generic
    'here's your leave balance' answer (with every type's numbers, casual
    included) as a bare 'what's my leave balance' — the response never
    actually reflected what was asked.

    Returns every matched type, not just the first: 'how many casual AND
    sick leaves do I have' previously only answered casual and silently
    dropped the sick half of the question."""
    text = query.lower()
    matched = []
    for word, slug in _LEAVE_TYPE_FILTER_WORDS.items():
        is_match = word in text if (" " in word or "-" in word) else bool(re.search(r"\b" + word + r"\b", text))
        if is_match and slug not in matched:
            matched.append(slug)
    return matched


def _normalize_leave_type_phrase(value: str) -> str:
    return re.sub(r"[\s_-]+", " ", value or "").strip().lower()


def _match_known_leave_type(text: Optional[str], known: Optional[list[dict]]) -> Optional[str]:
    """Deterministic leave-type matcher — backs the "never deny a type this
    company actually has" fix. Matches `text` against each known type's own
    slug AND display name after normalization (case/whitespace/separator-
    insensitive — "Short Leave"/"short_leave"/"Short-Leave"/"  short
    leave  " are all the same), and also accepts a bare identifying word
    with the generic "leave" suffix dropped ("short" alone still matches
    "Short Leave"), so it can only ever return a real configured type,
    never fabricate one from nothing. `known` is a list of
    {"slug": ..., "name": ...} dicts — erp-api's leave_settings.leave_type[]
    shape; None (erp-api unreachable) or an unmatched text both return
    None rather than guessing."""
    if not known:
        return None
    normalized_input = _normalize_leave_type_phrase(text)
    if not normalized_input:
        return None
    for entry in known:
        slug = entry.get("slug") or ""
        name = entry.get("name") or ""
        candidates = {
            _normalize_leave_type_phrase(slug),
            _normalize_leave_type_phrase(slug).removesuffix(" leave").strip(),
            _normalize_leave_type_phrase(name),
            _normalize_leave_type_phrase(name).removesuffix(" leave").strip(),
        }
        candidates.discard("")
        if normalized_input in candidates:
            return slug
    return None


# Status/qualifier words that can sit directly before "leave(s)" in a status
# query ("show my PENDING leaves", "my APPLIED leaves") without naming a
# type at all — must never be misread as an unsupported leave TYPE name.
# Not relevant to leave_eligibility_service's own generic-mention fallback
# (eligibility questions never talk about pending/approved/etc.), so kept
# local here rather than folded into that shared stopword set.
_STATUS_WORD_CANDIDATES = {
    "pending", "approved", "approve", "approval", "rejected", "reject",
    "rejection", "cancelled", "canceled", "cancel", "cancelling",
    "accepted", "accept", "declined", "decline", "applied", "all",
    "recent", "upcoming", "past", "old", "new", "outstanding",
}


async def _unsupported_leave_type_message_for_status(
    query: str, bearer_token: Optional[str], company_id, conversation_id: str,
) -> Optional[str]:
    """Bug found 2026-08-26: 'show my maternity leaves' / 'show my medical
    leaves' name a leave type _extract_leave_type_filters' closed
    vocabulary doesn't recognise at all — leave_type_filters came back
    empty, identical to a query naming no type, so the status branch
    quietly showed every leave type instead of saying the named one isn't
    supported. Mirrors leave_eligibility_service's dynamic check (against
    THIS company's real leave_settings, never a hardcoded list) so a
    company that genuinely configures, say, Paternity Leave still gets a
    real answer for it here too — only a truly unconfigured name reaches
    this message.

    Deferred import: leave_eligibility_service.py already imports FROM
    this module (_extract_leave_type_filters, _LEAVE_TYPE_CODES), so
    importing it back at module load time would be circular; importing
    inside this function, at call time, is safe since both modules are
    already fully loaded by then.

    Returns None (never raises) whenever there's nothing to say — no
    erp-api call is made unless the query actually names a candidate word
    outside both the closed vocabulary and the status-word set above, and
    any erp-api failure here just falls through to normal handling rather
    than blocking the whole status check over what is, after all, an extra
    lookup."""
    from services.leave_eligibility_service import (
        _mentions_unconfigured_leave, _extract_unrecognised_leave_mention,
        _match_configured_leave_types,
    )

    def _candidate() -> Optional[str]:
        found = _mentions_unconfigured_leave(query) or _extract_unrecognised_leave_mention(query, {})
        return found if found and found not in _STATUS_WORD_CANDIDATES else None

    # Cheap, no-I/O pre-check: only worth an extra erp-api round trip when
    # the query actually names SOMETHING that isn't already in the closed
    # vocabulary above (the common case — no such phrasing at all — never
    # pays for this).
    if not _candidate():
        return None
    try:
        balance_result = await erp_client.get_leave_balance(
            bearer_token, company_id=company_id, conversation_id=conversation_id)
    except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
        return None
    body = balance_result["body"].get("data") or {}
    leave_settings = body.get("leave_settings") or {}
    configured = {t.get("slug"): t for t in leave_settings.get("leave_type", []) if t.get("slug")}
    if not configured:
        return None
    # _mentions_unconfigured_leave comes from a FIXED word list, so it fires
    # for "paternity" even when this company genuinely has paternity_leave
    # configured — checked here against the REAL configured types (now
    # fetched) before trusting that fixed-list hit, same guard
    # leave_eligibility_service's own node applies for this exact case.
    if _match_configured_leave_types(query, configured):
        return None
    named = _mentions_unconfigured_leave(query) or _extract_unrecognised_leave_mention(query, configured)
    if not named or named in _STATUS_WORD_CANDIDATES:
        return None
    available = [configured[s].get("name") or s.replace("_", " ").title() for s in configured]
    supported_list = (
        f"{', '.join(available[:-1])}, and {available[-1]}" if len(available) > 1
        else (available[0] if available else "no leave types yet")
    )
    return (
        f"Helix AI currently supports {supported_list}. '{named.title()} Leave' is not "
        f"supported in this portal. Please contact HR for assistance."
    )


# A bare leave-type reply during slot collection ("casual leave", "sick
# leave") and a genuine leave-policy question ("what is the FMLA policy")
# both classify as leave_policy via fast_classify's keyword list — see
# hr_graph.classify_node's Fast-path 0.5 comment for why they must be told
# apart. Marker-based, not length-based: a wordier-than-usual bare reply
# ("I'd like to take casual leave from next Monday") must not get misread as
# a question just for being long — breaking the bare-reply path is the worse
# failure mode of the two (it derails slot collection entirely), so only
# explicit interrogative/explanatory language counts.
_LEAVE_POLICY_QUESTION_MARKERS = (
    "what", "how", "why", "explain", "describe", "tell me", "policy",
    "rule", "eligib", "entitle", "allow", "?",
)


def _looks_like_leave_policy_question(query: str) -> bool:
    text = query.lower()
    return any(marker in text for marker in _LEAVE_POLICY_QUESTION_MARKERS)


# Reply-resolution for the "which leaves would you like to see?" clarifying
# question (see leave_history_clarify_state.py and hr_graph.classify_node's
# Fast-path 0.3). Deterministic keyword matching — closed vocabulary, same
# philosophy as the cancel-leave patterns — checked in a fixed priority order
# so a reply naming more than one word still resolves predictably.
_HISTORY_CLARIFY_BALANCE_WORDS = ("balance", "remaining", "left")


def _resolve_leave_history_clarification(query: str) -> Optional[str]:
    """Returns 'leave_balance', 'pending', 'approved', 'cancelled',
    'rejected', 'all', or None (unrecognized reply)."""
    text = query.lower()
    if any(re.search(r"\b" + w + r"\b", text) for w in _HISTORY_CLARIFY_BALANCE_WORDS):
        return "leave_balance"
    if re.search(r"\bapproved\b", text):
        return "approved"
    if re.search(r"\b(cancelled|canceled)\b", text):
        return "cancelled"
    if re.search(r"\b(rejected|declined)\b", text):
        return "rejected"
    if re.search(r"\bpending\b", text):
        return "pending"
    if re.search(r"\b(applied|all|everything|history)\b", text):
        return "all"
    return None


# Reverse lookup off this file's own word->slug map, so the rewritten query
# (below) can splice in a natural trigger word for the leave type that was
# mentioned in the ORIGINAL ambiguous query — e.g. stored slug "sick_leave"
# -> "sick" — letting _extract_leave_type_filters re-derive it from the
# rewritten query text with zero new plumbing. Multiple words can map to the
# same slug (comp_off has three); any one of them round-trips correctly, so
# last-wins is fine.
_SLUG_TO_LEAVE_TYPE_WORD = {slug: word for word, slug in _LEAVE_TYPE_FILTER_WORDS.items()}


def _rewrite_query_for_history_clarify_resolution(
    resolved: str, reply_query: str, stored: dict,
) -> str:
    """Combines the resolved category with a leave type and date range —
    each preferring what the REPLY itself mentions (e.g. 'sick, approved,
    last month' answers all three in one go), falling back to whatever was
    already captured on the original ambiguous turn (stored in
    leave_history_clarify_state) when the reply doesn't repeat it."""
    reply_type_slugs = _extract_leave_type_filters(reply_query)
    leave_type_slug = reply_type_slugs[0] if reply_type_slugs else stored.get("leave_type_slug")
    type_word = _SLUG_TO_LEAVE_TYPE_WORD.get(leave_type_slug) if leave_type_slug else None

    reply_date_from, reply_date_to = _resolve_date_range_phrase(reply_query)
    date_from = reply_date_from or stored.get("date_from")
    date_to = reply_date_to or stored.get("date_to")
    date_suffix = f" from {date_from} to {date_to}" if date_from and date_to else ""

    if resolved == "leave_balance":
        return f"{type_word or ''} leave balance".strip()
    return f"{type_word or ''} {resolved} leaves{date_suffix}".strip()


# "give me options of dates" / "which dates are available" — the user is
# asking US to suggest dates rather than naming one. There's no such thing
# as a fixed slot calendar for leave (any date can be requested, subject to
# manager approval / blackout dates checked at submission), so slot
# extraction correctly finds no date here — but without this check the code
# just re-asked the exact same bare "What dates would you like to take off?"
# prompt, which reads as the bot ignoring the question entirely.
_DATE_SUGGESTION_REQUEST_PATTERNS: list[re.Pattern] = [
    re.compile(r"\b(options?|available|availability|open|free|suggest|recommend)\b[\w\s']{0,20}?\bdates?\b", re.IGNORECASE),
    re.compile(r"\bdates?\b[\w\s']{0,20}?\b(options?|available|availability|open|free)\b", re.IGNORECASE),
]


def _is_asking_for_date_suggestions(query: str) -> bool:
    text = query.lower()
    return any(p.search(text) for p in _DATE_SUGGESTION_REQUEST_PATTERNS)


# "Monthly sick leave limit reached ... What dates would you like to try
# instead?" -> "what is my limit" — a completely natural follow-up after
# being told a limit was hit. Same failure mode as the date-suggestion case
# above: with no date in the reply, this fell straight through to the bare
# date prompt, ignoring the actual question.
_LEAVE_LIMIT_QUESTION_PATTERNS: list[re.Pattern] = [
    re.compile(r"\b(what|whats|what's)\b[\w\s']{0,15}?\b(my|the)\b[\w\s']{0,10}?\blimit\b", re.IGNORECASE),
    re.compile(r"\blimit\b[\w\s']{0,15}?\b(is|allowed|reached)\b", re.IGNORECASE),
    re.compile(r"\bhow\s+many\b[\w\s']{0,20}?\bcan\s+i\s+(apply|take|request)\b", re.IGNORECASE),
    # "what's the MAXIMUM days I can take at once" — same question, "limit"
    # rephrased as "maximum"/"max". Found via live probing: this didn't match
    # any of the above and fell straight through to the bare date prompt.
    re.compile(r"\b(maximum|max)\b[\w\s']{0,20}?\bcan\s+i\s+(apply|take|request)\b", re.IGNORECASE),
    re.compile(r"\b(maximum|max)\b[\w\s']{0,15}?\bdays?\b", re.IGNORECASE),
]


def _is_asking_about_limit(query: str) -> bool:
    text = query.lower()
    return any(p.search(text) for p in _LEAVE_LIMIT_QUESTION_PATTERNS)


# "no, cancel this" / "actually never mind" at a confirmation prompt — found
# via live probing: is_affirmative correctly comes back False for these, so
# the code fell into the "not a clear yes — treat as a revision" branch. But
# a revision assumes the NEXT turn will supply new info to re-fill a cleared
# slot; here nothing was cleared, so with every slot already full it just
# re-validated the identical unchanged request and re-showed the exact same
# confirmation prompt — cancelling was never actually possible. Worse, "never
# mind" being run through slot extraction as if it might contain a field
# occasionally got misread as a "reason" ("actually never mind" -> reason:
# "actually never mind"), polluting the draft with garbage. This must be
# checked BEFORE extraction's fields get merged into slots, and independent
# of the LLM's is_affirmative call — cancellation is a closed enough
# vocabulary to catch deterministically, same reasoning as the date-
# suggestion/limit-question checks above.
_CANCEL_REQUEST_PATTERNS: list[re.Pattern] = [
    re.compile(r"\bcancel\b", re.IGNORECASE),
    re.compile(r"\b(never\s*mind|nevermind)\b", re.IGNORECASE),
    re.compile(r"\bforget\s+it\b", re.IGNORECASE),
    re.compile(r"\bdon'?t\s+(submit|apply|bother)\b", re.IGNORECASE),
    re.compile(r"\b(abort|stop|scrap)\s+(this|it|that|the\s+request)\b", re.IGNORECASE),
    re.compile(r"\bno\s+longer\s+(need|want)\b", re.IGNORECASE),
    # Reused as-is for the cancel-LEAVE confirmation step (see the cancel
    # branch below): a bare "Cancel" there means "cancel this [cancellation]
    # action" i.e. keep the leave request, matching the LLD's own decline
    # examples ("No / Don't cancel / Cancel / Keep it -> DECLINED"). "Keep
    # Request" is the real UI's decline button label, so it's matched
    # explicitly rather than relying on a bare "keep" that could collide
    # with unrelated phrasing elsewhere.
    re.compile(r"\bkeep\s+(it|this|(the\s+)?request)\b", re.IGNORECASE),
]

# A bare/leading "no" is deliberately NOT in _CANCEL_REQUEST_PATTERNS above —
# in the open-ended apply-leave slot flow a reply like "no, actually 3 days
# not 2" is a correction, not a decline, and must fall through to revision.
# The cancel-leave confirmation moment has no such open-endedness (only a
# yes/no answer is ever expected there), so a leading "no" is unambiguous and
# safe to treat as an explicit decline only in that one context.
_CANCEL_CONFIRM_BARE_NO = re.compile(r"^\s*no\b", re.IGNORECASE)


def _is_declining_or_cancelling(query: str) -> bool:
    text = query.lower()
    return any(p.search(text) for p in _CANCEL_REQUEST_PATTERNS)


# ── Cancel-leave confirmation decision (AC#3) ─────────────────────────────────
# A dedicated scheme for the cancel-LEAVE confirmation step — NOT the same as
# _is_declining_or_cancelling above (which apply-leave's own confirmation step
# still uses unchanged; apply-leave doesn't have this exact ambiguity).
#
# Two live-probed failures (2026-08-19/20) drove this design:
#   1. "Keep Request" (the real UI's decline button label) came back from the
#      LLM extraction as is_affirmative=true. A decline check gated behind
#      "and not is_affirmative" let that misread silently execute a real
#      cancellation nobody asked for.
#   2. "yes Cancel LR-32" — an unambiguous confirmation naming the very
#      request already selected — got treated as neither confirm nor decline
#      deterministically (bare \bcancel\b collides with the decline list) and
#      fell through to the LLM, which didn't reliably say is_affirmative=true
#      for it either, so the SAME confirmation prompt was re-shown forever.
#
# Fix: a STRONG decline signal (never mind, forget it, don't cancel, keep it/
# this/the request, abort/stop/scrap this, no longer need/want, a leading
# "no") always wins outright, even alongside "yes". Otherwise, a CONFIRM
# marker (confirm, proceed, go ahead, a leading yes/yeah/yep/sure) always wins
# outright over a bare "cancel" appearing elsewhere in the same message — this
# is what makes "yes Cancel LR-32" and the LLD's own "Yes, cancel it" example
# confirm deterministically, without needing the LLM at all. Only a BARE
# "cancel" with no confirm marker present is treated as a (weaker) decline —
# matching the LLD's bare "Cancel" -> DECLINED example. The LLM's
# is_affirmative is consulted only as a last resort, for a reply with none of
# these keywords.
_CANCEL_LEAVE_STRONG_DECLINE_PATTERNS: list[re.Pattern] = [
    re.compile(r"\b(never\s*mind|nevermind)\b", re.IGNORECASE),
    re.compile(r"\bforget\s+it\b", re.IGNORECASE),
    re.compile(r"\bdon'?t\s+cancel\b", re.IGNORECASE),
    # "discard" added alongside abort/stop/scrap (live UX request, 2026-08-24)
    # — "discard my request" means abandon the CANCELLATION attempt and keep
    # the leave as is, same as "Keep Request". "my request" added alongside
    # "the request" since a decline is just as often phrased that way.
    re.compile(r"\b(abort|stop|scrap|discard)\s+(this|it|that|((the|my)\s+)?request)\b", re.IGNORECASE),
    re.compile(r"\bno\s+longer\s+(need|want)\b", re.IGNORECASE),
    re.compile(r"\bkeep\s+(it|this|((the|my)\s+)?request)\b", re.IGNORECASE),
    # Bare single-word replies to the confirmation prompt (live UX request,
    # 2026-08-27) — "discard"/"kept"/"save" alone, with no object after them
    # (already covered above when one IS given, e.g. "discard it"). Anchored
    # to "the whole reply is essentially just this word" rather than a bare
    # \bword\b search anywhere in the message, since this fires only in
    # reply to a yes/no confirmation prompt — a short, on-topic answer is
    # expected here, so this can't collide with an unrelated sentence that
    # happens to contain "save" elsewhere the way an unanchored search could
    # (e.g. "save my earned leave for later" is a different topic, not a
    # decline).
    re.compile(r"^\s*(discard|discarded|kept|save|saved)\s*[.!]?\s*$", re.IGNORECASE),
]
_CANCEL_LEAVE_BARE_WORD_PATTERN = re.compile(r"\bcancel\b", re.IGNORECASE)
_CANCEL_LEAVE_CONFIRM_PATTERNS: list[re.Pattern] = [
    re.compile(r"\b(confirm|proceed)\b", re.IGNORECASE),
    re.compile(r"\bgo\s+ahead\b", re.IGNORECASE),
    re.compile(r"^\s*(yes|yeah|yep|sure)\b", re.IGNORECASE),
]


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


def _is_strong_cancel_decline(query: str) -> bool:
    return (any(p.search(query) for p in _CANCEL_LEAVE_STRONG_DECLINE_PATTERNS)
            or bool(_CANCEL_CONFIRM_BARE_NO.search(query)))


def _decide_cancel_confirmation(query: str, extracted: dict) -> str:
    """Returns 'decline', 'confirm', or 'ambiguous' for a reply to the
    cancel-leave confirmation prompt — see the module comment above."""
    if _is_strong_cancel_decline(query):
        return "decline"
    confirming = _is_confirming(query)
    if confirming:
        return "confirm"
    if _CANCEL_LEAVE_BARE_WORD_PATTERN.search(query):
        return "decline"
    if extracted.get("is_affirmative"):
        return "confirm"
    return "ambiguous"


async def _describe_leave_type_limit(
    erp_client_mod, bearer_token: str, company_id, conversation_id: str, leave_type_slug: Optional[str],
) -> Optional[str]:
    """Looks up the real per-type limits (max_apply_in_month, oneTypeMax)
    from erp-api's leave_settings — the same data that already backs the
    balance branch — so 'what is my limit' gets a real, specific answer
    instead of a guess."""
    if not leave_type_slug:
        return None
    try:
        result = await erp_client_mod.get_leave_balance(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
        )
    except (erp_client_mod.ErpApiTimeout, erp_client_mod.ErpApiUnavailable, erp_client_mod.ErpApiUnauthorized):
        return None

    leave_types = result["body"].get("data", {}).get("leave_settings", {}).get("leave_type", [])
    type_info = next((t for t in leave_types if t.get("slug") == leave_type_slug), None)
    if not type_info:
        return None

    label = type_info.get("name") or leave_type_slug.replace("_", " ").title()
    bits = []
    if type_info.get("max_apply_in_month"):
        bits.append(f"up to {type_info['max_apply_in_month']} request(s) per month")
    if type_info.get("oneTypeMax"):
        bits.append(f"up to {type_info['oneTypeMax']} day(s) per single request")
    if not bits:
        return None
    return f"Your {label} limit is {' and '.join(bits)}."


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

    def _finish(message: str, intent: str = "apply_leave", extra_data: Optional[dict] = None) -> dict:
        data = {"answer": message}
        # Frontend-facing flag for the whole cancel-leave lifecycle (preview,
        # ask-for-reason, ask-which-one, decline, etc.) — False on every
        # response by default, True only on the one that actually completed
        # the cancellation (_execute_cancel overrides it via extra_data).
        if intent in ("cancel_leave", "cancel_ask"):
            data["cancelled"] = False
            # Distinct from "cancelled" above: this says whether there's a
            # real leave record in play for THIS turn (a match, a candidate
            # list, a preview already in progress) — True by default, since
            # every step of the flow past the very first fetch is talking
            # about a specific leave (or leaves) that does exist. Only the
            # "nothing on record at all" turns override it to False via
            # extra_data — see the two "you don't have any ... to cancel"
            # messages and the fresh-turn erp-api-unreachable case below,
            # none of which have any leave data to show.
            data["leave_to_cancel"] = True
        # Same idea for failure cards: False by default on every apply/cancel
        # response, True only when this turn actually carries a leave_failure
        # card (leave_failure.build_card() sets it in extra_data) — lets the
        # frontend check one reliable boolean instead of probing for the
        # nested "failure" object's presence.
        if intent in ("apply_leave", "cancel_leave", "cancel_ask"):
            data["is_failure"] = False
        if extra_data:
            data.update(extra_data)
        writer({"type": "done", "intent": intent, "is_hr": True,
                "data": data, "message": message, "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    # ── Role gate (AC#1) — fetched lazily, only for actual leave interactions,
    # so erp-api's availability never affects ordinary (non-leave) HR chat.
    # Re-checked every turn rather than cached once per conversation — cheap,
    # and correctly catches a mid-conversation role change.
    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, erp_client.ErpApiUnauthorized):
        return _finish("I'm unable to reach the HR system right now — please try again shortly.")

    # Managers get full self-service here — leave_balance, apply_leave, and
    # leave_status/cancel are never restricted by role. Every erp_client call
    # in this node is scoped to the caller's own token, so a manager only
    # ever sees/affects their own leave data, never a team view — there's no
    # role-based gate left to apply. is_manager is logged for observability
    # only; team-approval workflows are a separate feature that never routes
    # through this node.
    is_manager = context_result["body"].get("data", {}).get("is_manager", False)
    logger.info(f"[Graph] Leave context fetched | is_manager={is_manager}")
    # Already-fetched, not a second call: the cancel branch's preview/success
    # cards identify the employee with this plus `company_id` (which is
    # already the JWT's user_id — see main.py's verify_jwt_token/company_id
    # naming), so no extra erp-api round trip is needed just to show a name.
    employee_name = context_result["body"].get("data", {}).get("name")

    def _employee_identity() -> dict:
        # erp-api's /leave/context now returns emp_no (e.g. "geo3") — the
        # real, human-readable employee code, shown exactly as erp-api
        # sends it (no "EMP-" prefix — removed 2026-08-27). Synthesized
        # from company_id only as a fallback for a payload that omits
        # emp_no, so the card never shows a blank in place of a code.
        emp_no = context_result["body"].get("data", {}).get("emp_no")
        emp_code = str(emp_no) if emp_no else (str(company_id) if company_id is not None else None)
        return {
            "user_id": company_id, "name": employee_name,
            "emp_code": emp_code,
        }

    # if is_manager:
    #     msg = ("Applying for leave and checking leave balance through the AI assistant "
    #            "isn't available for your role yet — this is currently for individual "
    #            "employees only.")
    #     return _finish(msg, intent="leave_restricted")
    existing_slots = leave_slot_service.get_slots(company_id, conversation_id)

    # Mid-flow interruption reminder — appended when a balance/status check
    # happens while an apply-leave draft is still in progress, so answering
    # the question doesn't make the pending draft silently disappear.
    resume_reminder = ""
    if existing_slots:
        parts = [existing_slots.get("leave_type"), existing_slots.get("from_date")]
        draft_desc = " for " + " on ".join(p for p in parts if p) if any(parts) else ""
        resume_reminder = f" You still have a leave application in progress{draft_desc} — just reply to continue it."

    # ── Balance branch (AC#2) ─────────────────────────────────────────────────
    if state["intent"] == "leave_balance":
        writer({"type": "fetching_balance", "message": "Checking your leave balance..."})
        try:
            result = await erp_client.get_leave_balance(bearer_token, company_id=company_id, conversation_id=conversation_id)
        except erp_client.ErpApiTimeout:
            return _finish("I couldn't reach the HR system in time — please try again in a moment.", intent="leave_balance")
        except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
            return _finish("I'm unable to reach the HR system right now — please try again shortly.", intent="leave_balance")

        # erp-api's sendInfo() uses 400 for business-rule failures (see
        # _request's docstring) — those come back here as a normal 200-level
        # result, not an exception, so "success" must be checked explicitly.
        # Without this, a failed call silently fell through to "data.get()"
        # on a body with no "data" key, producing an empty {} payload while
        # still claiming "Here's your current leave balance." — a real bug
        # reported live: the message looked successful with nothing in it.
        raw_body = result["body"]
        if not raw_body.get("success", False):
            error_msg = raw_body.get("message") or "I couldn't fetch your leave balance right now."
            return _finish(f"{error_msg}{resume_reminder}", intent="leave_balance")

        body = raw_body.get("data", {})
        leave_quota = body.get("leave_quota", {})
        if not leave_quota:
            return _finish(
                f"I couldn't find any leave balance information for your account.{resume_reminder}",
                intent="leave_balance",
            )

        type_filters = _extract_leave_type_filters(query)
        matched = {slug: leave_quota[slug] for slug in type_filters if slug in leave_quota}

        if matched:
            if len(matched) == 1:
                (slug, info), = matched.items()
                label = slug.replace("_", " ").title()
                msg = f"You have {_pluralize_leave_type(info.get('remaining'), label)} remaining out of {info.get('total')}."
            else:
                parts = "; ".join(
                    f"{slug.replace('_', ' ').title()}: {info.get('remaining')}/{info.get('total')} remaining"
                    for slug, info in matched.items()
                )
                msg = f"Here's what you asked for — {parts}."
            filtered_body = {**body, "leave_quota": matched, "suggestions": _LEAVE_BALANCE_FOLLOWUPS}
            writer({"type": "leave_balance", "data": filtered_body})
            return _finish(f"{msg}{resume_reminder}", intent="leave_balance", extra_data=filtered_body)

        full_body = {**body, "suggestions": _LEAVE_BALANCE_FOLLOWUPS}
        writer({"type": "leave_balance", "data": full_body})
        return _finish(f"Here's your current leave balance.{resume_reminder}", intent="leave_balance", extra_data=full_body)

    # ── Status branch — check existing leave application(s) ──────────────────
    if state["intent"] == "leave_status":
        # ── Resolve a reply to a pending "which leave did you mean?" ────────
        # question (see the status-question handling below). Checked first
        # and unconditionally: a bare reply like "the casual leave one" or
        # "the 30th" won't itself re-match leave_status through normal
        # classification, so classify_node's own fast-path routes it straight
        # back here — this is where it actually gets resolved.
        pending_candidates = leave_disambiguation_state.get_candidates(company_id, conversation_id)
        if pending_candidates:
            resolved = _resolve_disambiguation_reply(query, pending_candidates)
            leave_disambiguation_state.clear_candidates(company_id, conversation_id)
            if resolved:
                resolved_data = {
                    "leaves": [resolved], "filter": None, "total_count": 1,
                    "display_limit": 1, "has_more": False,
                    "suggestions": list(_LEAVE_STATUS_FOLLOWUPS) + (
                        [_LEAVE_STATUS_CANCEL_SUGGESTION]
                        if resolved.get("status_name") in ("pending", "approved") else []
                    ),
                }
                writer({"type": "leave_status", "data": resolved_data})
                return _finish(f"{_single_applied_leave_message(resolved)}{resume_reminder}",
                                intent="leave_status", extra_data=resolved_data)
            # Couldn't confidently match a candidate — don't guess; fall
            # through to normal handling below, which re-shows the list.

        status_filter = _extract_status_filter(query)
        is_all_request = _is_all_leaves_request(query)
        is_status_question = _is_status_question(query)
        leave_type_filters = _extract_leave_type_filters(query)
        date_from, date_to = _resolve_date_range_phrase(query)
        # Fallback for phrasing _resolve_date_range_phrase was never built
        # for (an absolute named-month mention, "21th august") — only spent
        # when the query plausibly names a date at all (has_date_expression,
        # computed once in classify_node) AND the resolver above found
        # nothing, so the common already-handled cases (today/this week/
        # last month/an explicit ISO range/...) never pay for it. Live bug:
        # "show my leave details for 21th august" returned every leave on
        # record instead of filtering to that one day.
        if date_from is None and date_to is None and state.get("has_date_expression"):
            fallback_range = await _resolve_date_range(
                query, _today_in_app_timezone(),
                purpose_hint="the employee's own leave request history",
            )
            if fallback_range:
                date_from, date_to = fallback_range

        # A type-less closed-vocabulary match ("maternity", "medical", ...)
        # must be flagged as unsupported BEFORE the ambiguous "which
        # leaves?" branch below — a named-but-unsupported type is not the
        # same thing as no type being named at all, and must never be
        # quietly reinterpreted as "show me everything".
        if not leave_type_filters:
            unsupported_msg = await _unsupported_leave_type_message_for_status(
                query, bearer_token, company_id, conversation_id)
            if unsupported_msg:
                return _finish(f"{unsupported_msg}{resume_reminder}", intent="leave_status")

        # ── Ambiguous "which leaves?" — never guess. Fires only when the
        # query gives NO signal at all about which subset is meant: no
        # explicit status word, no "all"/"applied" wording, not a yes/no
        # status question, and doesn't even say "status" (which already
        # reads as "tell me about what I've submitted" in common usage —
        # kept as the existing pending-default behavior so queries that were
        # never actually ambiguous in practice don't start re-asking).
        if (not status_filter and not is_all_request
                and not is_status_question and "status" not in query.lower()):
            leave_type_slug = leave_type_filters[0] if leave_type_filters else None
            leave_history_clarify_state.set_state(
                company_id, conversation_id,
                {"leave_type_slug": leave_type_slug, "date_from": date_from, "date_to": date_to},
            )
            type_label = leave_type_slug.replace("_", " ").title() if leave_type_slug else None
            type_phrase = f"{type_label} " if type_label else ""
            category_ask = (
                f"your {type_phrase}balance, all your applied {type_phrase}requests, or "
                f"specifically approved, cancelled, or rejected ones"
            )
            range_ask = "" if (date_from and date_to) else " (and let me know the time period — e.g. this month, last 3 months, or a specific range)"
            msg = (
                f"Just to make sure I get you the right info — are you asking about {category_ask}"
                f"{range_ask}?"
            )
            return _finish(msg, intent="leave_status")

        # ── Status question ("is my leave approved") — answerable precisely
        # now, searching every status instead of pending-only. ─────────────
        if is_status_question:
            writer({"type": "fetching_status", "message": "Checking your leave requests..."})
            try:
                result = await erp_client.get_applied_leaves(
                    bearer_token, leave_status="all", company_id=company_id, conversation_id=conversation_id,
                )
            except erp_client.ErpApiTimeout:
                return _finish("I couldn't reach the HR system in time — please try again in a moment.", intent="leave_status")
            except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
                return _finish("I'm unable to reach the HR system right now — please try again shortly.", intent="leave_status")

            all_leaves = result["body"].get("data", {}).get("leaves", [])
            if date_from and date_to:
                all_leaves = [lv for lv in all_leaves if _leave_overlaps_range(lv, date_from, date_to)]
            cards = [_build_applied_leave_card(lv) for lv in all_leaves]
            if leave_type_filters:
                cards = [c for c in cards if c.get("leave_type_slug") in leave_type_filters]
            # A status question can ALSO name the specific status it's asking
            # about ("why was my leave REJECTED") — when there are several
            # candidates, narrow to that status first so this answers about
            # the rejected one(s) directly instead of dumping every status
            # mixed together as "which one?". Only narrow when it actually
            # disambiguates (narrowed set non-empty): a single overall match
            # still gets its real, honest status regardless of what was
            # asked ("was it rejected?" / "no, it's approved"), and if
            # narrowing would eliminate every candidate, keep the full set
            # so this falls through to "which one?" instead of a false
            # "not found". Live bug (2026-08-20), found twice: status_filter
            # is unconditionally None here by construction
            # (_extract_status_filter suppresses it for question phrasing —
            # see its docstring), so this must use _match_status_word
            # directly instead, which has no such suppression.
            if len(cards) > 1:
                question_status = _match_status_word(query)
                if question_status:
                    narrowed = [c for c in cards if c.get("status_name") == question_status]
                    if narrowed:
                        cards = narrowed

            if not cards:
                msg = "I couldn't find a matching leave request — there's nothing on record for that."
            elif len(cards) == 1:
                msg = _single_applied_leave_message(cards[0])
            else:
                # Genuinely ambiguous which submitted request they mean — ask
                # instead of dumping every status in one sentence (that's what
                # an explicit "show me my X leaves" LIST request gets, below).
                # The reply gets resolved at the top of this branch.
                leave_disambiguation_state.set_candidates(company_id, conversation_id, cards)
                options = " or ".join(_describe_candidate(c) for c in cards)
                msg = f"You have multiple matching leave requests — which one are you asking about? {options}?"
            return _finish(f"{msg}{resume_reminder}", intent="leave_status")

        # ── Explicit status/all fetch — erp-api filters server-side now, via
        # the /leave/applied endpoint (pending/approved/cancelled/rejected/
        # all), a strict superset of the old pending-only /leave/pending. ──
        api_status = status_filter or ("all" if is_all_request else "pending")
        writer({"type": "fetching_status", "message": "Checking your leave requests..."})
        try:
            result = await erp_client.get_applied_leaves(
                bearer_token, leave_status=api_status, company_id=company_id, conversation_id=conversation_id,
            )
        except erp_client.ErpApiTimeout:
            return _finish("I couldn't reach the HR system in time — please try again in a moment.", intent="leave_status")
        except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
            return _finish("I'm unable to reach the HR system right now — please try again shortly.", intent="leave_status")

        all_leaves = result["body"].get("data", {}).get("leaves", [])
        if leave_type_filters:
            all_leaves = [lv for lv in all_leaves if lv.get("leave_type_slug") in leave_type_filters]
        if date_from and date_to:
            all_leaves = [lv for lv in all_leaves if _leave_overlaps_range(lv, date_from, date_to)]

        filter_label = f"{status_filter} " if status_filter else ("applied " if is_all_request else "pending ")
        range_label = f" ({date_from} to {date_to})" if date_from and date_to else ""
        total_count = len(all_leaves)
        cards = [_build_applied_leave_card(lv) for lv in all_leaves]

        # ── Follow-up suggestions (AC#6) ────────────────────────────────────
        # Cancelling only makes sense for a PENDING or APPROVED request — no
        # longer safe to always attach now that rejected/cancelled/mixed
        # ("all") results are shown too. Checked against the actual
        # displayed cards (not just api_status) since "all" can be a mix.
        suggestions = list(_LEAVE_STATUS_FOLLOWUPS)
        if any(c.get("status_name") in ("pending", "approved") for c in cards):
            suggestions.append(_LEAVE_STATUS_CANCEL_SUGGESTION)

        status_data = {
            "leaves": cards, "filter": status_filter, "total_count": total_count,
            "display_limit": total_count, "has_more": False, "suggestions": suggestions,
        }
        writer({"type": "leave_status", "data": status_data})

        if total_count == 0:
            # Exact copy required by HA-161's spec for the pending view —
            # checked against api_status (what was actually queried), not
            # status_filter alone, so it also covers the implicit
            # default-to-pending case (no status word in the query at all),
            # not just an explicit "pending". Every other filter/date-range
            # combination keeps the generic wording — no exact copy was
            # specified for those.
            if api_status == "pending" and not range_label:
                msg = "You currently have no pending leave requests."
            else:
                msg = f"You don't have any {filter_label}leave requests on record{range_label}."
        elif len(cards) == 1:
            msg = _single_applied_leave_message(cards[0])
        else:
            summary = "; ".join(
                f"{lv['leave_type']} ({lv['from_date']} to {lv['to_date']}): {lv.get('status_name') or 'unknown'}"
                for lv in cards
            )
            msg = f"Your {filter_label}leave requests{range_label} — {summary}."

        return _finish(f"{msg}{resume_reminder}", intent="leave_status", extra_data=status_data)

    # ── Cancel branch (AC#1-#5) — Match -> Select -> Preview -> Confirm ->
    # Execute, calling erp-api's /leave/cancel endpoint (live since
    # 2026-08-19). See leave_cancel_state.py for the Redis-backed state
    # machine that carries the flow across turns.
    if state["intent"] == "cancel_leave":

        async def _extract_cancel_fields(q: str) -> dict:
            extracted: dict = {}
            try:
                prompt = _build_leave_cancel_extraction_prompt(q)
                raw = await _call_llm(prompt, max_tokens=150, model=INTENT_MODEL)
                extracted = _safe_json_parse(_extract_text(raw))
                if extracted.get("request_id"):
                    extracted["request_id"] = _normalize_extracted_request_id(extracted["request_id"])
                usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
                if usage:
                    usage_events.append({"source": "leave_cancel_extraction", "usage": usage})
            except Exception as e:
                logger.warning(f"[Graph] leave cancel extraction failed: {e}")
            # Deterministic weekday/relative-day fallback (see
            # _resolve_weekday_date / _resolve_relative_day_date /
            # _resolve_absolute_date_mention / _resolve_numeric_date_mention)
            # — applied regardless of whether the LLM call above worked at
            # all, so "Friday"/"yesterday"/"25 Aug"/"14/08" all resolve even
            # during an LLM outage, and never depend on the model's own
            # (previously proven unreliable) date arithmetic.
            if not extracted.get("date"):
                resolved_date = (
                    _resolve_weekday_date(q) or _resolve_relative_day_date(q)
                    or _resolve_absolute_date_mention(q) or _resolve_numeric_date_mention(q)
                )
                if resolved_date:
                    extracted["date"] = resolved_date
            return extracted

        async def _execute_cancel(selected: dict, cancel_reason: str) -> dict:
            # No client-side "is this still pending/eligible" pre-check —
            # erp-api's /leave/cancel call owns ALL of that validation
            # (ownership, current status, lock state, policy restriction)
            # and returns a specific reason when it says no (AC#5). Checking
            # it here too would just be a second, possibly-stale copy of the
            # same logic — one source of truth, forwarded verbatim.
            writer({"type": "cancelling_leave", "message": "Cancelling your leave request..."})
            try:
                cancel_result = await erp_client.cancel_leave(
                    bearer_token, selected["id"], cancel_reason,
                    company_id=company_id, conversation_id=conversation_id,
                )
            except erp_client.ErpApiTimeout:
                return _finish("I couldn't reach the HR system in time to cancel this — please try again in a moment.", intent="cancel_leave")
            except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
                return _finish("I'm unable to reach the HR system right now — please try again shortly.", intent="cancel_leave")

            leave_cancel_state.clear_state(company_id, conversation_id)

            cancel_body = cancel_result["body"]
            if leave_failure.is_failure(cancel_body):
                # HEL-283 — routed through the same shared layer as apply, so
                # cancel gets identical reason codes, technical-leak guarding
                # and controlled fallback rather than a second, looser
                # implementation of the same rule (the raw
                # cancel_body.get("message") this replaced bypassed all of
                # that). erp-api's /leave/cancel owns eligibility/ownership/
                # lock-state validation; its reason is shown verbatim, never
                # invented or reworded here.
                failure = leave_failure.interpret_failure(cancel_body)
                # Deliberately NO local findings added alongside this one.
                # Whether a matched request is cancellable is erp-api's call
                # and erp-api's alone (see the fresh-turn comment below: no
                # client-side pending/approved pre-check), so its rejection is
                # the whole reason. Re-deriving a second reason here would
                # both duplicate logic this flow chose not to own and put a
                # sentence in front of the employee that the backend never
                # said — exactly what AC5 rules out. The enhancement is the
                # SHAPE: status, reason_code and human-readable text.
                #
                # AC6 — the next step follows from the reason_code, never from
                # reading the message. A policy-blocked cancellation (HA-163
                # Sprint 2 Scenario C, e.g. LP-14's 48-hour notice rule) gets
                # a Help Desk chip — policy exceptions are HR's call, not
                # something re-picking a date/request fixes. Any other real,
                # understood rejection offers to view other requests instead.
                # On a fallback, the spoken sentence stays suppressed (erp-api
                # told us nothing, so "here's what to do" would be a guess),
                # but the chip is still safe to attach — it echoes the
                # fallback text's own "...or contact HR support" line rather
                # than contradicting it, which is why HA-163's "always attach
                # chips" rule can hold even here.
                if failure.is_fallback:
                    next_action = None
                    chips = [leave_failure.chip("Contact HR Help Desk", "contact_hr")]
                elif failure.reason_code == "POLICY_RULE":
                    next_action = "Would you like to contact HR for help with this?"
                    chips = [leave_failure.chip("Contact HR Help Desk", "contact_hr")]
                else:
                    next_action = "Would you like to see your other leave requests?"
                    chips = [leave_failure.chip("View My Leave Requests", "view_leave_requests")]
                card = leave_failure.build_card(
                    "cancel_leave", failure, next_action=next_action, next_actions=chips)
                writer({"type": "leave_failure", "data": card})
                spoken = failure.display_message
                if next_action:
                    spoken = f"{spoken} {next_action}"
                return _finish(f"{spoken}{resume_reminder}",
                                intent="cancel_leave", extra_data=card)

            cancel_data = cancel_body.get("data", {})
            leave_type_slug = cancel_data.get("leave_type_slug")

            # AC#4 — report the authoritative post-cancellation balance from
            # erp-api, not the pre-cancellation preview figure. Best-effort:
            # the cancellation itself already succeeded, so a balance-refresh
            # hiccup here shouldn't read as a failure. total kept alongside
            # remaining (not just remaining) so the card can show "6 of 12
            # available", matching the Figma design, not just the bare count.
            updated_balance = None
            updated_total = None
            try:
                balance_result = await erp_client.get_leave_balance(bearer_token, company_id=company_id, conversation_id=conversation_id)
                quota_entry = balance_result["body"].get("data", {}).get("leave_quota", {}).get(leave_type_slug, {})
                # _fmt_days strips the trailing ".0" erp-api's numeric-string
                # figures would otherwise carry through as ("6.0" instead of
                # "6") — same normalization already used for total_days.
                raw_balance = quota_entry.get("remaining")
                raw_total = quota_entry.get("total")
                updated_balance = _fmt_days(raw_balance) if raw_balance is not None else None
                updated_total = _fmt_days(raw_total) if raw_total is not None else None
            except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
                pass

            # erp-api's /leave/cancel response only ever carries {leave_id,
            # status, status_name, leave_type_slug, leave_count,
            # cancel_reason} — no display name, dates, or reference. `selected`
            # (the matched candidate, already a full _build_applied_leave_card)
            # supplies those; cancel_data is spread SECOND so its fresh
            # status/status_name overrides `selected`'s now-stale "pending"
            # ones. status_label is recomputed the same way rather than
            # reused, since a cancelled record is never "Pending with X".
            success_data = {
                **selected, **cancel_data,
                "status_label": _STATUS_DISPLAY_LABELS.get(
                    cancel_data.get("status_name"), selected.get("status_label")),
                "updated_balance": updated_balance,
                "updated_total": updated_total,
                "employee": _employee_identity(),
                # Cancellation is done — nothing left to collect.
                "ask_cancel_leave_reason": False,
                "cancelled": True,
            }
            writer({"type": "leave_cancel_success", "data": success_data})

            if updated_balance is not None and updated_total is not None:
                balance_txt = (f" Updated balance: {selected.get('leave_type', 'leave')} — "
                               f"{updated_balance} of {updated_total} available.")
            elif updated_balance is not None:
                balance_txt = (f" Updated balance: "
                               f"{_pluralize_leave_type(updated_balance, selected.get('leave_type', 'leave'))} available.")
            else:
                balance_txt = ""
            msg = (
                f"Your {selected.get('leave_type', 'leave')} request ({_selected_date_label(selected)}, "
                f"ref {selected.get('reference')}) has been cancelled."
                f"{balance_txt}"
            )
            return _finish(msg, intent="cancel_leave", extra_data=success_data)

        async def _preview_cancel_request(
            selected: dict, reason: Optional[str] = None, match_label: Optional[str] = None,
        ) -> dict:
            # A still-pending request just hasn't happened yet, so there's
            # nothing "backdated" to block — only an APPROVED leave whose
            # date has already passed hits this rule (2026-08-26 product
            # direction). Checked before anything else in this function: no
            # balance-impact preview, no Confirm/Keep prompt, since erp-api's
            # own /leave/cancel would always refuse this anyway — showing a
            # preview implying it's confirmable would be misleading.
            if selected.get("status_name") == "approved" and _leave_date_has_passed(selected):
                leave_cancel_state.clear_state(company_id, conversation_id)
                card = _blocked_backdated_cancel_card(selected)
                writer({"type": "leave_failure", "data": card})
                spoken = f"{_APPROVED_BACKDATED_CANCEL_MESSAGE} {_APPROVED_BACKDATED_CANCEL_NEXT_ACTION}"
                return _finish(f"{spoken}{resume_reminder}", intent="cancel_leave", extra_data=card)

            # AC#2 — balance impact BEFORE anything happens. Advisory-grade
            # slug join (see _slug_for_leave_type): if it can't be resolved,
            # still show the preview with what IS known rather than failing.
            writer({"type": "fetching_balance", "message": "Checking your leave balance..."})
            try:
                balance_result = await erp_client.get_leave_balance(bearer_token, company_id=company_id, conversation_id=conversation_id)
            except erp_client.ErpApiTimeout:
                return _finish("I couldn't reach the HR system in time — please try again in a moment.", intent="cancel_leave")
            except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
                return _finish("I'm unable to reach the HR system right now — please try again shortly.", intent="cancel_leave")

            leave_quota = balance_result["body"].get("data", {}).get("leave_quota", {})
            slug = selected.get("leave_type_slug") or _slug_for_leave_type(selected.get("leave_type"), leave_quota)
            raw_current_balance = leave_quota.get(slug, {}).get("remaining") if slug else None
            # Duration is the leave's own length — shown in the summary line
            # regardless of status. Restoration is a SEPARATE question: only
            # an APPROVED leave has ever had days deducted from the balance
            # in the first place (erp-api deducts on approval, not on
            # submission), so only an approved leave has anything to restore
            # on cancellation. Live bug (2026-08-25): this used to reuse
            # duration as the restored-days figure unconditionally, so
            # cancelling a still-PENDING request showed a false "+1 day
            # restored" — nothing was ever deducted, so nothing is restored.
            raw_duration_days = selected.get("total_days")
            is_approved = selected.get("status_name") == "approved"
            raw_days_to_restore = raw_duration_days if is_approved else 0
            # _fmt_days strips the trailing ".0" a numeric-string/float figure
            # would otherwise carry through as ("6.0 days" instead of "6
            # days") — same normalization already used for total_days
            # elsewhere, applied here for the same reason.
            current_balance = _fmt_days(raw_current_balance) if raw_current_balance is not None else None
            duration_days = _fmt_days(raw_duration_days) if raw_duration_days is not None else None
            days_to_restore = _fmt_days(raw_days_to_restore) if raw_days_to_restore is not None else None

            preview = {
                **selected, "current_balance": current_balance, "days_to_restore": days_to_restore,
                "balance_restored": is_approved,
                # Always False here — this preview is asking for CONFIRMATION
                # first and foremost (the reason is only mentioned in the same
                # sentence as a heads-up, not as a dedicated ask). The flag
                # only flips True once confirmation has actually happened and
                # a reason still needs collecting on its own turn (see the
                # "confirm" branch and the awaiting_reason re-ask below) —
                # that's the one point where the frontend should show a
                # dedicated reason input.
                "ask_cancel_leave_reason": False,
            }
            # Came for free from the role-gate fetch at the top of this node
            # — no extra erp-api call needed for display identity.
            preview["employee"] = _employee_identity()
            if raw_current_balance is not None:
                try:
                    preview["projected_balance"] = _fmt_days(float(raw_current_balance) + float(raw_days_to_restore))
                except (TypeError, ValueError):
                    preview["projected_balance"] = None
            else:
                preview["projected_balance"] = None
            # Humanized counterpart to the "+X day(s) restored to <type>
            # (<code>)" line the card shows for an approved cancellation —
            # for a pending one, says plainly why the balance box shows no
            # change instead of leaving the frontend to guess at wording for
            # a zeroed restoration figure.
            leave_type_name = selected.get("leave_type", "leave")
            leave_type_code = selected.get("leave_type_code")
            type_with_code = f"{leave_type_name} ({leave_type_code})" if leave_type_code else leave_type_name
            if is_approved:
                day_word = "day" if days_to_restore == "1" else "days"
                preview["balance_impact_note"] = (
                    f"+{days_to_restore} {day_word} restored to {type_with_code}"
                    if days_to_restore is not None else None
                )
            else:
                preview["balance_impact_note"] = (
                    f"This request hasn't been approved yet, so no days were deducted — "
                    f"cancelling it won't change your {type_with_code} balance."
                )

            leave_cancel_state.set_state(
                company_id, conversation_id,
                {"step": "awaiting_confirmation", "selected": selected, "reason": reason},
            )
            writer({"type": "leave_cancellation_preview", "data": preview})

            if preview["projected_balance"] is None:
                balance_txt = ""
            elif is_approved:
                # States the day change AND the "+X day(s) restored" count
                # explicitly (not just the before/after numbers) — this
                # request really was approved, so the balance really is
                # changing, and saying so plainly is the counterpart to the
                # pending branch below explicitly saying why it ISN'T.
                restore_note = f" ({preview['balance_impact_note']})" if preview.get("balance_impact_note") else ""
                balance_txt = (
                    f" Current balance: {_pluralize_leave_type(current_balance, leave_type_name)} "
                    f"-> after cancellation: {_pluralize_leave_type(preview['projected_balance'], leave_type_name)}"
                    f"{restore_note}."
                )
            else:
                # Same number on both sides, said plainly instead of an
                # "X -> X" arrow that reads like a formatting glitch.
                balance_txt = (
                    f" Current balance: {_pluralize_leave_type(current_balance, leave_type_name)} — unchanged, "
                    f"since this request hasn't been approved yet and no days were deducted."
                )
            days_txt = f" ({duration_days} day(s))" if duration_days is not None else ""
            # One combined ask (confirm + reason together) instead of two
            # separate turns — skipped if a reason is already known (e.g.
            # volunteered on the original matching turn), since there's
            # nothing left to ask for.
            reason_ask = "" if reason else " and the reason for cancelling"
            # Only set when this match came from a SPECIFIC search criterion
            # (date/type/reference) narrowing straight to one result — a
            # naturally-single pending leave with no criteria given at all
            # doesn't get an "I found one matching X" line, since nothing
            # was actually searched for.
            lead_in = f'I found one leave request matching "{match_label}" in your submitted requests: ' if match_label else ""
            msg = (
                f"{lead_in}Here's your {selected.get('leave_type', 'leave')} request ({_selected_date_label(selected)}"
                f"{days_txt}, ref {selected.get('reference')}).{balance_txt} "
                f"Please review the details above. Would you like to cancel this request? "
                f"Reply to confirm{reason_ask}.{resume_reminder}"
            )
            return _finish(msg, intent="cancel_leave", extra_data=preview)

        cancel_state = leave_cancel_state.get_state(company_id, conversation_id)

        # ── Confirmation-turn recognition (AC#3) ─────────────────────────
        if cancel_state and cancel_state.get("step") == "awaiting_confirmation":
            selected = cancel_state["selected"]
            extracted = await _extract_cancel_fields(query)

            # A reply to "would you like to cancel this?" is normally short
            # — yes/no/confirm/decline. But the employee can also start an
            # entirely NEW cancel-leave request while an earlier one is
            # still sitting unresolved (never explicitly confirmed or
            # declined, e.g. state left over from a prior turn). Live bug:
            # "I want to cancel my sick leave", sent while a stale
            # confirmation was still pending, names a leave type but has no
            # confirm marker — its bare "cancel" fell into the weak-decline
            # fallback below and silently discarded the OLD pending request
            # ("Leave Request Kept") instead of answering the NEW one.
            # Detected by a concrete new matching criterion (leave type,
            # date, or reference) that a genuine yes/no reply never carries
            # — when one is present, and the reply isn't itself an explicit
            # confirm/decline, treat this as a fresh request: drop the stale
            # state and fall through to the normal fresh-turn matching below
            # (which already handles "found one", "found several", and
            # "found none" gracefully — the same list shown when first
            # asking to cancel).
            names_new_criterion = bool(
                extracted.get("leave_type") or extracted.get("date")
                or extracted.get("request_id") or _extract_request_id(query)
            )
            if names_new_criterion and not _is_confirming(query) and not _is_strong_cancel_decline(query):
                leave_cancel_state.clear_state(company_id, conversation_id)
                cancel_state = None
            else:
                decision = _decide_cancel_confirmation(query, extracted)

                if decision == "decline":
                    # Not cleared outright — kept as a short-lived "declined"
                    # memory so a vague follow-up ("cancel again", "cancel my
                    # previous request") can resume straight to confirmation
                    # instead of re-matching from scratch (see the
                    # "Resuming after a decline" branch below).
                    leave_cancel_state.set_state(
                        company_id, conversation_id,
                        {"step": "declined", "selected": selected, "reason": cancel_state.get("reason")},
                    )
                    return _finish(
                        f"{_keep_request_message(selected)}{resume_reminder}",
                        intent="cancel_leave", extra_data={"keep_leave_request": True},
                    )

                if decision == "confirm":
                    # One step when possible: confirm + reason together (the
                    # preview prompt above already asks for both in the same
                    # message). A reason volunteered on this turn or the
                    # original matching turn is used as-is; otherwise this now
                    # asks a dedicated follow-up for it (live UX request,
                    # 2026-08-24) rather than silently substituting a generic
                    # placeholder reason nobody actually gave.
                    known_reason = extracted.get("reason") or cancel_state.get("reason")
                    if not known_reason:
                        leave_cancel_state.set_state(
                            company_id, conversation_id,
                            {"step": "awaiting_reason", "selected": selected},
                        )
                        return _finish(
                            f"Got it — could you tell me the reason for cancelling this "
                            f"{selected.get('leave_type', 'leave')} request?",
                            intent="cancel_leave", extra_data={"ask_cancel_leave_reason": True},
                        )
                    return await _execute_cancel(selected, known_reason)

                # Ambiguous reply — re-ask, keep state rather than silently
                # dropping the pending confirmation.
                leave_cancel_state.set_state(company_id, conversation_id, cancel_state)
                return _finish(
                    f"Sorry, I didn't catch that — would you like me to go ahead and cancel your "
                    f"{selected.get('leave_type', 'leave')} request ({_selected_date_label(selected)}, "
                    f"ref {selected.get('reference')})? (yes/no)",
                    intent="cancel_leave",
                )

        # ── Reason-turn recognition ───────────────────────────────────────
        # Reached only when the confirm reply above had no reason attached
        # (see the "confirm" branch) — the employee's whole reply here IS
        # the reason, no extraction needed, EXCEPT a change of heart still
        # has to be honored (a strong "never mind"/"keep it" reply here must
        # still decline, not get filed away as a literal cancellation reason).
        if cancel_state and cancel_state.get("step") == "awaiting_reason":
            selected = cancel_state["selected"]
            if _is_strong_cancel_decline(query):
                # Same short-lived "declined" memory as the confirmation-turn
                # decline above, so a vague follow-up can resume straight to
                # confirmation instead of re-matching from scratch.
                leave_cancel_state.set_state(
                    company_id, conversation_id,
                    {"step": "declined", "selected": selected, "reason": None},
                )
                return _finish(
                    f"{_keep_request_message(selected)}{resume_reminder}",
                    intent="cancel_leave", extra_data={"keep_leave_request": True},
                )
            reason = query.strip()
            if not reason:
                leave_cancel_state.set_state(company_id, conversation_id, cancel_state)
                return _finish(
                    "Could you share a brief reason for cancelling this request?",
                    intent="cancel_leave", extra_data={"ask_cancel_leave_reason": True},
                )
            return await _execute_cancel(selected, reason)

        # ── Selection-turn recognition (AC#1) ────────────────────────────
        if cancel_state and cancel_state.get("step") == "awaiting_selection":
            candidates = cancel_state.get("candidates", [])
            # Same extraction the initial cancel turn uses (LLM + weekday/
            # relative-day fallback) — a bare regex pass alone can't resolve
            # an absolute date like "24 aug" named in a selection reply.
            extracted = await _extract_cancel_fields(query)
            chosen = _resolve_cancel_selection(query, candidates, extracted)
            if not chosen:
                leave_cancel_state.set_state(company_id, conversation_id, cancel_state)
                writer({"type": "leave_cancellation_selection", "data": {"requests": candidates}})
                # A reference number was named explicitly but doesn't match
                # anything in THIS list — a more specific answer than the
                # generic "couldn't quite tell" below, which reads as if
                # nothing about the reply was understood at all.
                named_request_id = extracted.get("request_id") or _extract_request_id(query)
                if named_request_id:
                    message = (
                        f"I couldn't find a request with reference LR-{named_request_id} in this "
                        f"list — please pick one below by leave type, date, number, or reference."
                    )
                else:
                    message = (
                        "Sorry, I couldn't quite tell which request you mean — could you let me know "
                        "the leave type, leave date, applied date, number, or reference so I can find "
                        "the right one for you?"
                    )
                return _finish(message, intent="cancel_ask", extra_data={"requests": candidates})
            return await _preview_cancel_request(
                chosen, reason=extracted.get("reason") or cancel_state.get("reason"),
                match_label=_describe_search_criterion(query, extracted),
            )

        # ── Resuming after a decline ──────────────────────────────────────
        # "Keep Request" used to clear_state() outright, so a follow-up like
        # "cancel my previous request" / "cancel again" / a bare "cancel"
        # carried no criterion of its own and fell all the way through to
        # the vague-query path below — re-showing the FULL candidate list
        # instead of picking straight back up where the employee left off
        # (live UX report). Declining now leaves a short-lived "declined"
        # state remembering the selection instead of clearing it outright;
        # a follow-up that doesn't name a genuinely DIFFERENT request (no
        # new leave type/date/reference) re-offers the SAME confirmation
        # rather than re-matching from scratch. A follow-up that DOES name
        # a new criterion falls through to fresh matching as normal.
        if cancel_state and cancel_state.get("step") == "declined":
            declined_selected = cancel_state["selected"]
            extracted = await _extract_cancel_fields(query)
            names_new_criterion = bool(
                extracted.get("leave_type") or extracted.get("date")
                or extracted.get("request_id") or _extract_request_id(query)
            )
            if not names_new_criterion:
                return await _preview_cancel_request(
                    declined_selected, reason=extracted.get("reason") or cancel_state.get("reason"),
                )
            leave_cancel_state.clear_state(company_id, conversation_id)
            cancel_state = None

        # ── Fresh turn — no state (AC#1) ──────────────────────────────────
        # Fetches every status via /leave/applied. This layer only finds
        # WHICH request the employee means — erp-api's own /leave/cancel
        # call is the single source of truth for whether a matched request
        # is actually cancellable (AC#5), so a specific date/ID/type match
        # goes straight to preview regardless of its current status, no
        # client-side pending/approved pre-check.
        writer({"type": "fetching_status", "message": "Checking your leave requests..."})
        try:
            result = await erp_client.get_applied_leaves(
                bearer_token, leave_status="all", company_id=company_id, conversation_id=conversation_id,
            )
        except erp_client.ErpApiTimeout:
            return _finish("I couldn't reach the HR system in time — please try again in a moment.",
                            intent="cancel_leave", extra_data={"leave_to_cancel": False})
        except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
            return _finish("I'm unable to reach the HR system right now — please try again shortly.",
                            intent="cancel_leave", extra_data={"leave_to_cancel": False})

        all_leaves = result["body"].get("data", {}).get("leaves", [])
        cards = [_build_applied_leave_card(lv) for lv in all_leaves]

        if not cards:
            return _finish(f"You don't have any leave requests to cancel.{resume_reminder}",
                            intent="cancel_leave", extra_data={"leave_to_cancel": False})

        # Only used for the VAGUE-query fallback list below (and the "no
        # match found" fallback) — presenting an already-cancelled/rejected
        # item as something to pick FROM a list isn't useful, even though a
        # SPECIFIC match against one is still taken straight to preview and
        # left for erp-api to accept or refuse. Both "pending" AND
        # "approved" count as cancellable candidates here — a future leave
        # that's already been approved is still a normal thing to cancel
        # (erp-api's own /leave/cancel explicitly restores balance for an
        # approved leave, which pending doesn't even have deducted yet), so
        # excluding approved ones from this picker would hide a real,
        # common case, not just an edge case.
        cancellable_cards = [c for c in cards if c.get("status_name") in ("pending", "approved")]

        extracted = await _extract_cancel_fields(query)
        # A range phrase ("last week", "this month") never resolves to a
        # single "date" field from the LLM/weekday/relative-day extraction
        # above, but is just as much a specific criterion as an exact date
        # — without this check it would be misread as a vague "cancel my
        # leave" and shown the full candidate list instead of being matched.
        range_from_hint, range_to_hint = _resolve_date_range_phrase(query)
        has_specific_criteria = bool(
            extracted.get("request_id") or _extract_request_id(query)
            or extracted.get("date") or extracted.get("leave_type")
            or (range_from_hint and range_to_hint)
        )

        lead_msg = ""
        if has_specific_criteria:
            matches = _match_cancel_candidates(cards, extracted, query)
            if not matches:
                lead_msg = (
                    "Hmm, I couldn't find a leave request matching that — nothing on record fits "
                    "it, so there's nothing to cancel there. "
                )
                matches = cancellable_cards
            elif len(matches) > 1:
                # Multiple specific matches (e.g. "cancel my sick leave"
                # matching several sick-leave records of different
                # statuses) — a pick-FROM-a-list must only offer genuinely
                # cancellable-looking options, same reasoning as the vague
                # case; a single, UNAMBIGUOUS match is still taken straight
                # to preview above regardless of status either way.
                narrowed = [m for m in matches if m.get("status_name") in ("pending", "approved")]
                if narrowed:
                    matches = narrowed
                else:
                    lead_msg = "That request's already been decided, so it can't be cancelled anymore. "
                    matches = cancellable_cards
        else:
            # Vague query ("cancel my leave") — never guess (AC#1), surface
            # every cancellable-looking (pending or approved) candidate.
            matches = cancellable_cards

        if not matches and not lead_msg:
            return _finish(f"You don't have any pending or approved leave requests to cancel.{resume_reminder}",
                            intent="cancel_leave", extra_data={"leave_to_cancel": False})

        if lead_msg or len(matches) > 1:
            display = matches[:PENDING_LEAVE_DISPLAY_LIMIT]
            leave_cancel_state.set_state(
                company_id, conversation_id,
                {"step": "awaiting_selection", "candidates": display, "reason": extracted.get("reason")},
            )
            writer({"type": "leave_cancellation_selection", "data": {"requests": display}})
            # Targeted follow-up when the employee already gave ONE
            # criterion (type or date) and it narrowed the list but not to
            # a single match — ask specifically for whichever piece is
            # still missing, rather than the generic "pick by number or
            # reference" that applies to a truly vague "cancel my leave"
            # with no criteria at all. Both given but still ambiguous (e.g.
            # duplicate submissions) falls to asking for the reference ID
            # directly, since that's the only thing left to disambiguate by.
            given_type = extracted.get("leave_type") if not lead_msg else None
            given_date = extracted.get("date") if not lead_msg else None
            given_date_to = extracted.get("date_to") if not lead_msg else None
            # An explicit two-date span ("from 25 Aug to 29 Aug") describes
            # the leave's OWN dates, not a calendar-period filter — labelled
            # as that exact range rather than just its start date.
            explicit_range_label = (
                _display_date_range(given_date, given_date_to)
                if given_date and given_date_to and given_date_to != given_date else None
            )
            # A range phrase ("last week", "this month") narrows the list
            # just like an exact date does, but never populates "date" —
            # fall back to it for the same ask, labelled with the actual
            # resolved range rather than a single (possibly misleading) day.
            range_label = (
                _display_date_range(range_from_hint, range_to_hint)
                if not lead_msg and range_from_hint and range_to_hint else None
            )
            if given_type and not given_date and not range_label:
                type_label = given_type.replace("_", " ").title()
                ask = (f"You have multiple {type_label} requests — could you tell me the leave date, "
                       f"applied date, or reference ID of the one you want to cancel?")
            elif (given_date or range_label) and not given_type:
                date_label = explicit_range_label or (_describe_search_date(query, given_date) if given_date else None) or range_label or given_date
                ask = (f"You have multiple leave requests on {date_label} — which leave type "
                       f"is it, or do you have the reference ID?")
            elif given_type and (given_date or range_label):
                type_label = given_type.replace("_", " ").title()
                date_label = explicit_range_label or (_describe_search_date(query, given_date) if given_date else None) or range_label or given_date
                ask = (f"You have multiple {type_label} requests on {date_label} — could you "
                       f"give me the reference ID of the one you want to cancel?")
            else:
                ask = (
                    "Could you let me know which one you'd like to cancel — by its leave type, "
                    "leave date, applied date, number, or reference?"
                    if len(display) > 1 else "Would you like to cancel this one instead?"
                )
            # cancel_ask, not cancel_leave: this response is a QUESTION —
            # nothing has been resolved to one specific request yet. Kept
            # distinct so a consumer of this API can tell "we're asking
            # which leave" apart from "we've matched one and are proceeding"
            # (preview/confirm/execute, all still cancel_leave). Also why
            # main.py's _STATEFUL_QUERY_INTENTS lists cancel_ask alongside
            # cancel_leave — this depends on the live candidate list exactly
            # like cancel_leave itself and must never be cached.
            return _finish(f"{lead_msg}{ask}{resume_reminder}", intent="cancel_ask", extra_data={"requests": display})

        match_label = _describe_search_criterion(query, extracted) if has_specific_criteria else None
        return await _preview_cancel_request(matches[0], reason=extracted.get("reason"), match_label=match_label)

    # ── Apply branch ──────────────────────────────────────────────────────────
    slots = existing_slots or {
        "step": "collecting", "leave_type": None, "from_date": None,
        "to_date": None, "session_type_slug": None, "reason": None,
    }

    # A "cancel"/"never mind"/"forget it" reply discards the in-progress
    # DRAFT at any point in the flow, not just at the final
    # awaiting_confirmation step (previously only checked there, further
    # below) — so saying "cancel this" while still collecting the leave
    # type or dates fell through to slot extraction, found nothing new, and
    # silently re-asked for whatever was still missing instead of ever
    # recognizing the discard request. Checked before the (expensive) slot-
    # extraction call, and only when there's an existing draft to discard —
    # a bare "cancel" on a brand-new turn with no slots yet has nothing to
    # discard and is handled by ordinary classification instead.
    if existing_slots and _is_declining_or_cancelling(query):
        leave_slot_service.clear_slots(company_id, conversation_id)
        return _finish(
            "No problem — I've cancelled that leave request. "
            "Let me know if you'd like to start a new one."
        )

    # One extraction call serves both purposes: fills slots on a collecting
    # turn, and carries is_affirmative on a confirmation turn.
    extracted: dict = {}
    try:
        # Only the prompt sees the year hint (see _add_explicit_year_hint) —
        # `query` itself stays untouched for every other use below (slot
        # merging keys off `extracted`, not the raw text).
        prompt = _build_leave_slot_extraction_prompt(_add_explicit_year_hint(query), slots)
        raw = await _call_llm(prompt, max_tokens=200, model=INTENT_MODEL)
        extracted = _safe_json_parse(_extract_text(raw))
        usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
        if usage:
            usage_events.append({"source": "leave_slot_extraction", "usage": usage})
    except Exception as e:
        logger.warning(f"[Graph] leave slot extraction failed: {e}")

    _roll_apply_dates_forward_if_past(extracted, query)

    # ── Confirmation-turn recognition ────────────────────────────────────────
    if slots.get("step") == "awaiting_confirmation":
        if extracted.get("is_affirmative"):
            writer({"type": "submitting_leave", "message": "Submitting your leave request..."})
            try:
                result = await erp_client.apply_leave(
                    bearer_token, slots["leave_type"], slots["from_date"], slots["to_date"],
                    slots.get("session_type_slug"), slots.get("reason"),
                    company_id=company_id, conversation_id=conversation_id,
                )
            except erp_client.ErpApiTimeout:
                return _finish("I couldn't reach the HR system in time to submit this — please try again in a moment.")
            except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
                return _finish("I'm unable to reach the HR system right now — please try again shortly.")

            body = result["body"]
            if leave_failure.is_failure(body):
                # erp-api's own wording, passed through untouched — never
                # reworded, categorised or explained here (HEL-283 AC5).
                # interpret_failure is the single place that rule is applied,
                # shared with the eligibility flow and available to cancel.
                failure = leave_failure.interpret_failure(body)
                error_msg = failure.display_message
                # Gathered before the slots below are cleared — these checks
                # read from_date/to_date.
                extra_failures = await _collect_additional_failures(
                    erp_client, bearer_token, company_id, conversation_id,
                    slots, failure.reason_code,
                )
                # Resubmitting the exact same slots would just fail identically
                # again (duplicate application, locked attendance date, etc.) —
                # a bare "yes"/"try again" reply re-enters this same branch and
                # loops forever hitting the same erp-api rejection, since step
                # was never reset. Drop back to collecting so the next reply
                # is treated as new input, not another confirmation attempt.
                slots["step"] = "collecting"
                if failure.is_fallback:
                    # erp-api gave us nothing usable, so we do not know what
                    # went wrong. The fallback already carries its own guidance
                    # ("try again later or contact HR support"); appending
                    # "what dates would you like instead?" would contradict it
                    # and imply the dates were at fault. AC6 asks for a next
                    # action "wherever applicable" — here none is. Dates are
                    # still cleared so a bare "yes" can't resubmit forever.
                    slots["from_date"] = None
                    slots["to_date"] = None
                    next_action = None
                    # HA-163 Sprint 2 spec: "always attach relevant chips" —
                    # safe here specifically because it echoes what the
                    # fallback message's own text already says ("...or
                    # contact HR support"), unlike a "try different dates"
                    # chip, which would contradict "we don't know what went
                    # wrong" the same way the spoken suggestion would.
                    chips = [leave_failure.chip("Contact HR Help Desk", "contact_hr")]
                elif "reason" in error_msg.lower():
                    # erp-api rejected specifically over the reason field —
                    # the proactive ask above should normally prevent this,
                    # but if it still happens (a company-specific rule, an
                    # erp-api change), clearing dates instead would send the
                    # user in circles re-picking dates that were never the
                    # problem. Re-collect the reason instead.
                    slots["reason"] = None
                    next_action = "Could you share a brief reason for this leave?"
                    chips = [leave_failure.chip("Add a Reason", "provide_reason")]
                elif "session type" in error_msg.lower() or "session_type" in error_msg.lower():
                    # Live bug: erp-api rejects some leave types (e.g.
                    # sick_leave) with "The session type slug field is
                    # required..." even for what looked like a plain
                    # single-day request — the proactive half-day ask above
                    # doesn't cover every such type. Same "re-collect the
                    # slot that was actually invalidated" treatment as the
                    # reason branch above — clearing dates instead would be
                    # nonsensical, since the dates were never the problem.
                    slots["session_type_slug"] = None
                    next_action = "Would that be a full day or half day?"
                    chips = [leave_failure.chip("Provide Session Type", "provide_session_type")]
                else:
                    # Otherwise assume it's date-related (duplicate application,
                    # locked attendance date, notice period, etc — leave/session
                    # type are rarely the actual cause) and clear dates so the
                    # next reply is read as picking a new date.
                    slots["from_date"] = None
                    slots["to_date"] = None
                    next_action = "What dates would you like to try instead?"
                    chips = [leave_failure.chip("Select Another Date", "select_another_date")]
                leave_slot_service.set_slots(company_id, conversation_id, slots)
                # AC6: the offered next step follows from whichever slot was
                # invalidated above. The branch does read the message, but only
                # to decide which slot to re-collect — a recovery choice, not a
                # claim about why erp-api refused. The reason shown to the
                # employee stays erp-api's own words either way. Title comes
                # from the action; reason_code is a badge hint and is None when
                # unrecognised, in which case the UI shows the plain card.
                card = leave_failure.build_card(
                    "apply_leave", [failure] + extra_failures,
                    next_action=next_action, next_actions=chips)
                writer({"type": "leave_failure", "data": card})
                spoken = " ".join([error_msg] + [f.display_message for f in extra_failures])
                # Carried on the done event as well as the leave_failure one:
                # a client that renders from done alone would otherwise get the
                # flat sentence and none of the structure.
                return _finish(f"{spoken} {next_action}" if next_action else spoken,
                               extra_data=card)

            # applyUsersLeave() returns ALL of the user's applied leaves (no
            # orderBy), not just the one just created — take the max id, not
            # the first element, or this picks an arbitrary old application.
            application = body.get("data")
            app_id = None
            if isinstance(application, list) and application:
                app_id = max(
                    (row.get("id") for row in application if isinstance(row, dict) and row.get("id") is not None),
                    default=None,
                )

            # A silently-failed clear leaves these slots sitting at
            # "awaiting_confirmation" with the same dates — the user's very
            # next unrelated reply ("ok thanks") can get routed straight back
            # into this branch and, if extraction happens to read it as
            # affirmative, resubmit this exact request a second time. Retry
            # once, and if it still fails, force the step to a terminal
            # marker instead of leaving it as "awaiting_confirmation" — that
            # keeps a stale read from ever matching the resubmit branch
            # again, so the worst case becomes a freshly re-shown
            # confirmation prompt (safe, if mildly redundant) rather than a
            # silent duplicate submission.
            if not leave_slot_service.clear_slots(company_id, conversation_id):
                if not leave_slot_service.clear_slots(company_id, conversation_id):
                    logger.error(
                        "[Graph] Failed to clear leave slots after successful submission "
                        "(app_id=%s, company_id=%s, conversation_id=%s) — forcing terminal step as fallback",
                        app_id, company_id, conversation_id,
                    )
                    leave_slot_service.set_slots(company_id, conversation_id, {**slots, "step": "submitted"})

            # status is the outcome of the leave operation — the apply went
            # through — and is the counterpart of the failure card's
            # "REJECTED". NOT erp-api's own status_name on the leave, which
            # reads "Pending" here: the request was accepted, and is now
            # waiting on the approver.
            success_data = {"status": "ACCEPTED", "application_id": app_id,
                            "suggestions": _APPLY_SUCCESS_FOLLOWUPS}
            writer({"type": "leave_success", "data": success_data})
            confirm_msg = (f"Your leave request has been submitted — Request #{app_id}."
                           if app_id else "Your leave request has been submitted.")
            return _finish(confirm_msg, intent="leave_success", extra_data=success_data)

        # A decline/cancel reply is already handled by the discard check
        # above (before slot extraction even ran) — reaching here means
        # this wasn't a clear "yes" either, so treat it as a revision.
        slots["step"] = "collecting"

    # Captured BEFORE this turn's merge below — the unrecognized-leave-type
    # recovery/denial logic right after it must only ever run while
    # leave_type is genuinely still being collected, not retroactively once
    # it's already locked in from an earlier turn (live bug: a garbled
    # reason-prompt reply like "fever009" tripped extraction's unfamiliar-
    # word heuristic into flagging unrecognized_leave_type even though
    # leave_type was never in question at that point in the conversation —
    # see test_reason_reply_flagged_as_unrecognized_leave_type_is_not_
    # rejected_when_type_already_known).
    had_leave_type_before = bool(slots.get("leave_type"))

    # Merge this turn's extracted fields into the slots.
    for field in ("leave_type", "from_date", "to_date", "session_type_slug", "reason"):
        if extracted.get(field):
            slots[field] = extracted[field]
    # A reason has now actually been supplied (via extraction this turn, or
    # already sitting from an earlier one) — any retry count from a prior
    # failed attempt no longer applies. See the reason gate below.
    if slots.get("reason"):
        slots.pop("reason_attempts", None)

    # ── Leave-type recovery/denial against the company's REAL configured
    # list — live bug: extraction flagging a reply as unrecognized_leave_
    # type (or returning leave_type as a display name like "Short Leave"
    # rather than its slug) used to be treated as authoritative, either
    # silently storing an unusable non-slug value or denying a type the
    # company actually has. Only the real configured list can decide that,
    # so it's consulted here, before either the raw merge above or the
    # "ask for leave type" block below gets the final say. Skipped entirely
    # once leave_type was already locked in from an earlier turn (see
    # had_leave_type_before above) — nothing this turn's extraction says
    # about leave_type is relevant at that point.
    unrecognized_leave_type_denial = None
    if not had_leave_type_before:
        candidate = extracted.get("leave_type") or extracted.get("unrecognized_leave_type")
        if candidate:
            known_leave_types = await _fetch_known_leave_types(
                erp_client, bearer_token, company_id, conversation_id,
            )
            matched_slug = _match_known_leave_type(candidate, known_leave_types)
            if matched_slug:
                slots["leave_type"] = matched_slug
            elif extracted.get("unrecognized_leave_type"):
                # extracted.get("leave_type") alone (no unrecognized_leave_
                # type flag) with no match just leaves slots["leave_type"]
                # as whatever the raw merge set — erp-api's own apply() call
                # remains the backstop for a slug this deterministic check
                # somehow still missed (e.g. erp-api unreachable, known_
                # leave_types is None). A genuine unrecognized_leave_type
                # flag with no match, though, is worth an explicit denial —
                # see the "ask for leave type" block below.
                slots["leave_type"] = None
                unrecognized_leave_type_denial = (candidate, known_leave_types)

    # ── Tier 1: deterministic date/duration override ─────────────────────────
    # Must run AFTER the LLM merge above (so it can see/override this turn's
    # own guess) and BEFORE persisting below and BEFORE the back-date-
    # disallowed check further down, which must evaluate the FINAL corrected
    # from_date, not a possibly-wrong LLM guess. Everything downstream
    # (holiday/conflict check, balance/day-count validation, confirmation
    # card, the actual apply_leave call) reads slots["from_date"]/["to_date"]
    # and so picks up the correction with no further changes needed anywhere
    # else in this function.
    today = _today_in_app_timezone()
    det_matched = _apply_deterministic_date_overrides(query, slots, extracted, today)

    # ── Tier 2: structured tool-calling extraction ────────────────────────────
    # Only spent when tier 1 found nothing AND the query plausibly names a
    # relative date at all — most turns never reach this. See
    # services.ai_service.extract_structured_date_fields for the field
    # schema/prompt and date_resolver.resolve_structured_date for the pure
    # arithmetic. Looked up through hr_graph's own module namespace (a
    # deferred import — hr_graph imports this module at its own load time,
    # so importing hr_graph back here at call time, not module load time,
    # avoids a circular import) rather than a direct import into this
    # module, so the existing hr_graph.extract_structured_date_fields test
    # patches (see hr_graph.py's own comment on why that import is kept)
    # still take effect now that this tier actually runs.
    _looks_like_a_date_query = _query_needs_relative_date_scrutiny(query, today)
    if not det_matched and _looks_like_a_date_query:
        from datetime import timedelta
        import services.hr_graph as hr_graph
        structured_fields, structured_usage = await hr_graph.extract_structured_date_fields(query, today)
        if structured_usage:
            usage_events.append({"source": "structured_date_extraction", "usage": structured_usage})
        structured_result = date_resolver.resolve_structured_date(
            today,
            day_offset=structured_fields["day_offset"],
            target_weekday=structured_fields["target_weekday"],
            weekday_relation=structured_fields["weekday_relation"],
            ordinal=structured_fields["ordinal"],
            month_offset=structured_fields["month_offset"],
        )
        if structured_result:
            slots["from_date"] = structured_result.isoformat()
            duration_days = structured_fields.get("duration_days")
            slots["to_date"] = (
                (structured_result + timedelta(days=duration_days - 1)).isoformat()
                if duration_days else structured_result.isoformat()
            )
            det_matched = True
            logger.info(
                "[Graph] Structured date extraction resolved: %r -> %s..%s",
                {k: v for k, v in structured_fields.items() if v is not None},
                slots["from_date"], slots["to_date"],
            )

    # ── Tier 3: don't silently trust — or even suggest — a date that ONLY
    # the LLM's raw guess produced, with no deterministic cross-check at
    # all. A wrong guess is worse than admitting uncertainty (live repro:
    # "second week friday" guessed a date that isn't even a Friday) — every
    # reason clears the slot and asks a plain, open question instead.
    needs_confirmation = _llm_date_needs_confirmation(
        query, extracted.get("from_date"), extracted.get("to_date"), det_matched, today,
    )
    if needs_confirmation:
        reason = needs_confirmation["reason"]
        slots["from_date"] = None
        slots["to_date"] = None
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        if reason == "invalid":
            return _finish(
                "That doesn't look like a valid date — could you tell me the exact "
                "date (or date range) you meant?",
                extra_data={"requires_date_input": True},
            )
        if reason == "past_date":
            return _finish(
                f"{needs_confirmation['llm_from_date']} has already passed — did you mean "
                "a different date? What date would you like to take off?",
                extra_data={"requires_date_input": True},
            )
        # "ambiguous_relative_phrase" — genuinely unclear, and nothing here
        # can vouch for any specific date, so none is suggested.
        return _finish(
            "I want to make sure I get the right day — could you tell me the exact "
            "date (or date range) you'd like?",
            extra_data={"requires_date_input": True},
        )

    # Persist the merge immediately — on a "revision" turn (all slots were
    # already filled, user corrected one and fell through from the branch
    # above) the next step is _find_conflicting_leave, which only catches
    # the two expected erp-api exceptions; anything else (e.g. a malformed
    # response body) would otherwise propagate uncaught before this turn's
    # correction is ever saved, silently reverting to the pre-correction
    # slots on the next turn. Every branch below persists again anyway as it
    # progresses, so this is a harmless extra write, not a behavior change.
    leave_slot_service.set_slots(company_id, conversation_id, slots)

    # Reject a past date immediately if this company disallows back-dated
    # leave — same "check it the moment we can, not after three more
    # questions" reasoning as the conflict check below. Live bug repro: "i
    # want to apply leave for yesterday" asked "what type of leave?" first,
    # even though the date alone was already enough to know (for a company
    # with back_date_leave_allow="0") the request could never succeed.
    if slots.get("from_date") and await _is_back_date_disallowed(
        erp_client, bearer_token, company_id, conversation_id, slots.get("from_date"),
    ):
        leave_slot_service.set_slots(
            company_id, conversation_id,
            {**slots, "step": "collecting", "from_date": None, "to_date": None},
        )
        return _finish(
            "You can't apply for leave on a past date. What date would you like to try instead?",
            extra_data={"requires_date_input": True},
        )

    # Live UX complaint: the conflict check used to run only once every
    # OTHER slot (leave_type, session type, reason) was also collected, so a
    # duplicate date only surfaced after the user had already answered
    # "full day or half day?" and "what's the reason?" — wasted turns on a
    # request that was never going to succeed. erp-api's apply() rejects an
    # overlapping date regardless of leave TYPE, so this only needs
    # from_date/to_date and must run the moment those are known — even
    # before leave_type, and before fetching the company's leave-type list
    # for the "what type?" question below (no point spending that erp-api
    # round trip on a request about to be rejected anyway).
    if slots.get("from_date") and slots.get("to_date"):
        # Holiday-blocked check moved up here alongside the conflict check
        # (live bug report, 2026-08-24): it used to live ONLY inside
        # _collect_additional_failures, which runs "ONLY after erp-api has
        # already refused" — so if erp-api's own apply() doesn't itself
        # reject a fully-holiday request (nothing guarantees it does), the
        # check never ran at all and the request went through uncaught.
        # Fetched in parallel with the conflict check since neither depends
        # on the other, same reasoning as _collect_additional_failures.
        holiday_body, conflict = await asyncio.gather(
            _fetch_holidays_or_none(erp_client, bearer_token, company_id, conversation_id),
            _find_conflicting_leave(erp_client, bearer_token, company_id, conversation_id,
                                    slots.get("from_date"), slots.get("to_date")),
        )

        holidays = _holiday_index(holiday_body)
        blocked = _fully_blocked_holidays(holidays, slots.get("from_date"), slots.get("to_date"))
        if blocked:
            leave_slot_service.set_slots(
                company_id, conversation_id,
                {**slots, "step": "collecting", "from_date": None, "to_date": None},
            )
            failure = leave_failure.local_failure(
                _blocked_holiday_message(holidays, blocked), "BLOCKED_DATE")
            next_action = "What dates would you like to try instead?"
            # HA-163 Sprint 2 spec, Scenario B: a single actionable chip.
            chips = [leave_failure.chip("Select Another Date", "select_another_date")]
            card = leave_failure.build_card(
                "apply_leave", failure, next_action=next_action, next_actions=chips)
            writer({"type": "leave_failure", "data": card})
            return _finish(f"{failure.display_message} {next_action}", intent="apply_leave", extra_data=card)

        if conflict:
            leave_slot_service.set_slots(
                company_id, conversation_id,
                {**slots, "step": "collecting", "from_date": None, "to_date": None},
            )
            # Same leave_failure card shape as the balance pre-check right
            # below and the cancel-leave failures — this is a proactive
            # LOCAL block (same reasoning as the balance one above: Helix
            # catches it before ever calling erp-api's apply()), so it needs
            # its own card rather than relying on _collect_additional_failures,
            # which only runs after an actual erp-api rejection.
            failure = leave_failure.local_failure(
                _duplicate_conflict_message(conflict), "DUPLICATE_APPLICATION",
            )
            next_action = "What dates would you like to try instead?"
            chips = [leave_failure.chip("Select Another Date", "select_another_date")]
            card = leave_failure.build_card(
                "apply_leave", failure, next_action=next_action, next_actions=chips)
            writer({"type": "leave_failure", "data": card})
            return _finish(
                f"{failure.display_message} {next_action}", intent="apply_leave",
                extra_data={**card, "requires_date_input": True},
            )

    # Ask for the next missing required slot, in order.
    if not slots.get("leave_type"):
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        # A genuinely unrecognized type this turn (checked against the real
        # configured list above, not just extraction's own guess) gets an
        # explicit denial naming what was asked for, instead of silently
        # re-asking "what type of leave?" with no acknowledgement of what
        # the user actually said — see unrecognized_leave_type_denial above.
        if unrecognized_leave_type_denial:
            candidate, known_leave_types = unrecognized_leave_type_denial
            if known_leave_types:
                names = [t["name"] for t in known_leave_types]
                options = names[0] if len(names) == 1 else f"{', '.join(names[:-1])}, or {names[-1]}"
                return _finish(
                    f'We don\'t have a "{candidate}" leave type here — the leave '
                    f"types you can apply for are: {options}."
                )
            return _finish(f'We don\'t have a "{candidate}" leave type here.')
        known_leave_types = await _fetch_known_leave_types(
            erp_client, bearer_token, company_id, conversation_id,
        )
        if known_leave_types:
            names = [t["name"] for t in known_leave_types]
            options = names[0] if len(names) == 1 else f"{', '.join(names[:-1])}, or {names[-1]}"
            return _finish(f"What type of leave would you like to apply for — {options}?")
        return _finish("What type of leave would you like to apply for — casual, sick, earned, or something else?")

    if not slots.get("from_date") or not slots.get("to_date"):
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        if _is_asking_for_date_suggestions(query):
            return _finish(
                "There's no fixed list of available dates — you can request almost "
                "any date; it just needs your manager's approval and can't fall on "
                "a locked or blackout date. What date or date range would you like?"
            )
        if _is_asking_about_limit(query):
            limit_desc = await _describe_leave_type_limit(
                erp_client, bearer_token, company_id, conversation_id, slots.get("leave_type"),
            )
            if not limit_desc:
                limit_desc = "I couldn't fetch your exact limit right now — you can check with HR."
            return _finish(f"{limit_desc} What dates would you like to try instead?")
        return _finish("What dates would you like to take off?", extra_data={"requires_date_input": True})

    # Half-day only makes sense for a single day — a multi-day range is
    # always full days throughout, so skip asking entirely rather than
    # invite an answer that would misrepresent the request (see
    # _compute_requested_days for what happens if this got answered anyway).
    if (slots["leave_type"] in _SESSION_TYPE_REQUIRED_LEAVE_TYPES
            and _is_single_day(slots) and not slots.get("session_type_slug")):
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish("Would that be a full day or half day?")

    # The multi-day counterpart of the single-day ask above: never asked
    # (a half-day answer would misrepresent a multi-day request — see the
    # comment above), but must still be filled in explicitly rather than
    # left None, so downstream slot reads (confirmation card, the saved
    # slots themselves) see the actual session type this request will use.
    if (slots["leave_type"] in _SESSION_TYPE_REQUIRED_LEAVE_TYPES
            and not _is_single_day(slots) and not slots.get("session_type_slug")):
        slots["session_type_slug"] = "full_day"

    # "half day" alone (as opposed to explicitly "first half"/"second half")
    # is ambiguous — the extraction prompt is instructed to return the
    # generic "half_day" slug rather than guess, specifically so this branch
    # can ask instead of silently defaulting. Previously the LLM had no way
    # to signal that ambiguity and would guess first_half_day every time,
    # applying the wrong half without ever telling the user it had guessed.
    if _is_single_day(slots) and slots.get("session_type_slug") == "half_day":
        slots["session_type_slug"] = None
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish("Would that be the first half or second half of the day?")

    # erp-api treats short_leave as an inherently single-unit type — its
    # apply()/update() call force-sets leave_count="1" regardless of the
    # date range given (the same way a half-day forces 0.5) and rejects a
    # multi-day short_leave range outright at SUBMISSION time ("The from
    # date and to date must be the same for this leave request"). Live
    # bug: a 15-day short_leave range sailed all the way through
    # confirmation and only failed after the user said "yes, submit it" —
    # caught here instead, before confirmation, same reasoning as every
    # other early validation in this block. Only the dates are cleared —
    # leave_type stays, so the retry doesn't also re-ask "what type?".
    if slots["leave_type"] == "short_leave" and not _is_single_day(slots):
        leave_slot_service.set_slots(
            company_id, conversation_id, {**slots, "from_date": None, "to_date": None},
        )
        return _finish(
            "Short Leave can only be applied for a single day. What date would you like to take instead?",
            extra_data={"requires_date_input": True},
        )

    # Validate against balance (AC#3) as soon as leave_type + dates (and,
    # where relevant, session_type_slug — the half-day disambiguation above
    # already ran, so requested_days is accurate here) are all known. Moved
    # ahead of the reason question (live UX fix, 2026-08-26): reason has no
    # bearing on how many days are being requested, so asking for it before
    # checking balance meant a request that was going to be rejected anyway
    # ("apply sick leave for 15 days" with 3 remaining) still made the
    # employee answer "what's the reason?" first — a wasted round-trip, the
    # same class of bug the holiday/conflict checks were moved earlier for.
    # This is advisory: erp-api's own apply() call is the authoritative check.
    writer({"type": "fetching_balance", "message": "Checking your leave balance..."})
    try:
        balance_result = await erp_client.get_leave_balance(bearer_token, company_id=company_id, conversation_id=conversation_id)
    except erp_client.ErpApiTimeout:
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish("I couldn't reach the HR system in time — please try again in a moment.")
    except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish("I'm unable to reach the HR system right now — please try again shortly.")

    leave_quota = balance_result["body"].get("data", {}).get("leave_quota", {})
    remaining = leave_quota.get(slots["leave_type"], {}).get("remaining")
    requested_days = _compute_requested_days(slots)

    if remaining is not None:
        try:
            if requested_days > float(remaining):
                # Helix blocks the submission here, which is why erp-api's own
                # insufficient-balance rejection never reaches a chat user —
                # chasing that wording is wasted effort. Legitimate to state as
                # a reason: the numbers come from the balance API, so this is
                # reported data, not a theory about why erp-api said no.
                reason_text, type_name = _insufficient_balance_message(
                    slots["leave_type"], remaining, requested_days)
                next_action = "Would you like to check your available balance or apply for the available days instead?"
                # HA-163 Sprint 2 spec, Scenario A: two chips. "Apply for N
                # Days" only makes sense with days actually left to offer —
                # a zero balance gets "Use Another Leave Type" instead of a
                # chip suggesting a 0-day application.
                remaining_days = _fmt_days(remaining)
                chips = [leave_failure.chip("Check Available Balance", "check_leave_balance")]
                is_zero_balance = float(remaining) <= 0
                if not is_zero_balance:
                    chips.append(leave_failure.chip(
                        f"Apply for {remaining_days} Day{'s' if remaining_days != '1' else ''}",
                        "apply_reduced_days"))
                else:
                    chips.append(leave_failure.chip("Use Another Leave Type", "change_leave_type"))

                # Live bug repro: dates used to be left untouched on this
                # rejection, so a reply that ISN'T actually a new date (any
                # text extraction finds no date in) silently re-validated
                # the exact same insufficient-balance combination and
                # repeated the identical rejection forever with no way out
                # — same "clear it so the next turn falls through to a
                # fresh ask" treatment as the conflict/back-date rejections
                # beside this one.
                slots["from_date"] = None
                slots["to_date"] = None
                requires_date_input = True
                if is_zero_balance:
                    # A zero-total type is a wrong-TYPE problem, not a
                    # wrong-DATES one — no date could ever fix it, so
                    # (unlike the partial-shortfall case above) leave_type
                    # itself is cleared too, and the frontend must NOT be
                    # told to show a calendar. Suggests other types that
                    # actually have balance right now, sourced from this
                    # SAME balance fetch (leave_quota's full type list, with
                    # leave_settings.leave_type for a nicer display name —
                    # same lookup _fetch_known_leave_types uses) so no extra
                    # erp-api round trip is spent on it.
                    names_by_slug = {
                        t["slug"]: t.get("name")
                        for t in balance_result["body"].get("data", {}).get(
                            "leave_settings", {}).get("leave_type", [])
                        if t.get("slug")
                    }
                    alternate_names = []
                    for slug, entry in leave_quota.items():
                        if slug == slots.get("leave_type") or slug in alternate_names:
                            continue
                        try:
                            if float(entry.get("remaining")) <= 0:
                                continue
                        except (TypeError, ValueError):
                            continue
                        alternate_names.append(names_by_slug.get(slug) or slug.replace("_", " ").title())
                    reason_text = f"You have no {type_name} balance."
                    if alternate_names:
                        options = (
                            alternate_names[0] if len(alternate_names) == 1
                            else f"{', '.join(alternate_names[:-1])}, or {alternate_names[-1]}"
                        )
                        reason_text += f" You could apply using {options} instead."
                    next_action = "Would you like to check your available balance or use a different leave type?"
                    slots["leave_type"] = None
                    requires_date_input = False

                leave_slot_service.set_slots(company_id, conversation_id, slots)
                card = leave_failure.build_card(
                    "apply_leave",
                    leave_failure.local_failure(
                        reason_text, "INSUFFICIENT_BALANCE", heading=f"Not enough {type_name} balance"),
                    next_action=next_action, next_actions=chips,
                )
                writer({"type": "leave_failure", "data": card})
                extra_data = {**card, "requires_date_input": True} if requires_date_input else card
                return _finish(f"{reason_text} {next_action}", extra_data=extra_data)
        except (TypeError, ValueError):
            pass  # non-numeric remaining — let erp-api's own apply() gate it

    # erp-api's own validator marks 'reason' nullable, but the standard
    # (non-AI) leave application flow requires it — asking for it here keeps
    # AI-submitted requests consistent with that, and avoids a submit-time
    # 400 that the caller only discovers after already confirming (see the
    # reason-aware branch above, which re-prompts if erp-api ever rejects for
    # this despite this check — a company-specific rule or an erp-api change
    # neither this slot nor its extraction anticipated).
    if not slots.get("reason"):
        # Live bug repro: extraction correctly refuses to let a bare
        # leave-type mention ("sick leave") leak into 'reason' — that's its
        # own documented rule — but a reply that just restates the type
        # isn't an actual reason either, so extraction keeps returning null
        # and this branch re-asked the SAME question forever with no way
        # out. First failed attempt still asks again (extraction might just
        # need a clearer answer); the SECOND consecutive failure accepts the
        # raw reply verbatim instead of looping a third time.
        attempts = slots.get("reason_attempts", 0) + 1
        if attempts == 1:
            slots["reason_attempts"] = attempts
            leave_slot_service.set_slots(company_id, conversation_id, slots)
            return _finish("What's the reason for this leave request?")
        slots["reason"] = query
        slots.pop("reason_attempts", None)
        leave_slot_service.set_slots(company_id, conversation_id, slots)

    slots["step"] = "awaiting_confirmation"
    leave_slot_service.set_slots(company_id, conversation_id, slots)
    confirmation_data = {**slots, "total_days": requested_days}
    writer({"type": "leave_confirmation", "data": confirmation_data})
    return _finish(
        f"To confirm: {requested_days} day(s) of {slots['leave_type'].replace('_', ' ')} "
        f"from {slots['from_date']} to {slots['to_date']}. Shall I submit this request?",
        extra_data=confirmation_data,
    )
