from __future__ import annotations

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

from langgraph.types import StreamWriter

from schema.agent import HRState

from services.ai_service import (
    LLM_TASK_MAX_TOKENS,
    classify_choice,
    classify_confirmation_reply,
    _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.date_query_resolver as date_query_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_submit_claim as leave_submit_claim
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
import services.access_notice as access_notice
import services.nlp_service as nlp_service
import services.permission_service as permission_service

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.
    # Short leave is one unit whichever half it is in - erp-api force-sets
    # leave_count="1" for it. Counting its half as 0.5 put "0.5 day(s) of
    # short leave" on the card and under-checked the balance.
    if slots.get("leave_type") == "short_leave" and _is_single_day(slots):
        return 1.0
    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.

    get_applied_leaves with leave_status="all", NOT get_pending_leaves. The
    overlap filter below accepts "pending" OR "approved", because erp-api's
    apply() rejects an overlap with either — but /leave/pending returns
    PENDING rows only, so the "approved" half of that filter could never
    match anything and an already-APPROVED leave on the same date went
    completely undetected. (The filter was written against the old
    /leave/status, which returned every status; when that route became
    pending-only the filter quietly lost half its job.) /leave/applied is a
    strict superset — see the leave_status branch below, which migrated for
    the same reason.

    Worth knowing when reading the tests: the regression test for this
    function stubs an APPROVED leave onto the conflict lookup, so it was
    passing against a mock more generous than the real endpoint.

    Live bug: an 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 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.

    Advisory, and fails open by design: if erp-api rejects or ignores
    applied_leave_date on this route, the worst case is the wider unscoped
    list, which is still strictly more than the pending-only query this
    replaced. erp-api's own apply() remains the authoritative gate."""
    if not from_date or not to_date:
        return None
    try:
        result = await erp_client_mod.get_applied_leaves(
            bearer_token, leave_status="all",
            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"]
    )

    # Highest precedence of all — a date the user typed out in full digits is
    # the most explicit signal available, and the ONLY one where the LLM
    # produces a well-formed-but-WRONG answer that no downstream guard can
    # detect (live bug: "From 10/09/2026 to 11/09/2026" was submitted as
    # 2026-10-09 -> 2026-11-09, a 32-day request the user never made; see
    # date_resolver.resolve_numeric_date_range's section header for why
    # day-first is this product's convention rather than a preference).
    #
    # Restored 2026-09-07: this call was present in hr_graph.py's original
    # (now deleted) leave_action_node and was the ONE resolver dropped when
    # this pipeline was ported here — the port gained three weekday
    # resolvers and lost this. That left all-numeric dates with no
    # deterministic vetting at all, riding entirely on the LLM reading them
    # day-first, which is exactly what this module's own header forbids
    # ("do not rely only on the LLM to calculate dates"). A month-first slip
    # turns a future date into a past one and the request is refused as
    # already passed, with nothing downstream able to tell the difference.
    numeric_range_result = date_resolver.resolve_numeric_date_range(query, today)
    if numeric_range_result and numeric_range_result[1] is not None:
        first, second = numeric_range_result
        slots["from_date"] = first["from_date"]
        slots["to_date"] = second["from_date"]
        logger.info(
            "[Graph] Deterministic numeric-date range override: %r -> %s, %r -> %s",
            first["matched_phrase"], first["from_date"], second["matched_phrase"], second["from_date"],
        )
        return True

    # A weekday WITHIN a named month - "last Friday of Aug month", "first
    # Monday of the July month". QA: the weekday resolvers below read these
    # as last week's Friday / next Monday (18 Sep, 28 Sep); date_query_resolver
    # computes the real calendar day (28 Aug, 6 Jul) for the right year.
    # Exactly one such phrase: two ("first friday of next month to last friday
    # of next month") are a RANGE, which the range resolvers below own.
    if sum(1 for m in _WEEKDAY_WORD_RE.finditer(query)
           if date_resolver._WEEKDAY_OF_MONTH_TAIL.match(query[m.end():])) == 1:
        try:
            ordinal = date_query_resolver.resolve(query, today)
        except Exception:
            ordinal = None
        if isinstance(ordinal, dict) and ordinal.get("type") == "single":
            slots["from_date"] = slots["to_date"] = ordinal["date"].isoformat()
            logger.info("[Graph] Deterministic weekday-of-month override: %r -> %s",
                        query[:80], slots["from_date"])
            return True

    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"],
        )

    # The third anchor for the same construct — "the last week of this
    # month". A named month and "next month" were both wired up here; "this
    # month" never was, so the phrase resolved to nothing and the employee
    # got an empty date picker (QA report, 2026-09-09). Same shape as the
    # next-month block above, including the weekday narrowing.
    this_month_week_result = date_resolver.resolve_week_of_this_month_phrase(query, today)
    this_month_week_narrowed_to_weekday = None
    if this_month_week_result:
        tmw_start, tmw_end = this_month_week_result
        this_month_week_narrowed_to_weekday = date_resolver.weekday_within_span(query, tmw_start, tmw_end)
        if this_month_week_narrowed_to_weekday is None:
            slots["from_date"] = tmw_start.isoformat()
            slots["to_date"] = tmw_end.isoformat()
            logger.info(
                "[Graph] Deterministic week-of-this-month range override: %s..%s",
                tmw_start.isoformat(), tmw_end.isoformat(),
            )
            return True
        logger.info(
            "[Graph] Deterministic week-of-this-month narrowed to weekday: %r -> %s",
            this_month_week_narrowed_to_weekday["matched_phrase"],
            this_month_week_narrowed_to_weekday["from_date"],
        )

    resolved = (
        # Same reasoning as the numeric-range override above, for the
        # single-date case ("apply casual leave on 08/09/2026", or a bare
        # "08/09/2026" answering the "what dates?" prompt). First in this
        # chain for the same reason it is first there: explicit digits beat
        # every phrase-based resolver below it, and a month-first misreading
        # is undetectable downstream.
        numeric_range_result[0] if numeric_range_result
        else 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 this_month_week_narrowed_to_weekday if this_month_week_narrowed_to_weekday
        # Ahead of the qualifier-based resolvers below because "last day of
        # next month" would otherwise be caught by the bare "next month"
        # pattern and then thrown away by the ambiguity discard beneath this
        # chain — even though naming the last day makes it fully determinate.
        else date_resolver.resolve_last_day_of_month_phrase(query, today)
        or 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)
        # Last resort — a BARE weekday with no qualifier ("apply casual leave
        # on sunday"). Every resolver above needs a qualifier ("next monday",
        # "this week's friday"), so a plain weekday name matched NONE of them
        # and the flow fell through to whatever the LLM guessed. That is the
        # one input the model demonstrably gets wrong: on gpt-4o-mini
        # "sunday" resolved to a Friday and "monday" to a Saturday, and a
        # wrong-but-valid date is invisible to every check downstream.
        # _resolve_weekday_date does the arithmetic locally and is already
        # trusted for exactly this in the cancel flow.
        or _bare_weekday_anchor(query, today)
        # Same reasoning, same last-resort position, for the other single-date
        # phrasings this module already resolves locally for the CANCEL flow
        # but never wired into the apply flow: an explicit calendar date
        # ("25 aug", "15th october", "2026-10-15") and "today/yesterday".
        # These matched none of the qualifier-based resolvers above, so the
        # apply flow was taking whatever the model returned for exactly the
        # inputs that are least ambiguous to a human and most mechanical to
        # compute. Resolving the date here does NOT decide whether the leave
        # is allowed — a back-dated request still goes through the existing
        # back-date/eligibility checks downstream, which is the right order:
        # establish WHICH date was meant first, then judge it.
        or _single_date_anchor(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.
    # "next week" joins "next month" here (CEO review point 8). It resolved
    # to the whole Monday-Sunday span — SEVEN days, weekend included — and
    # offered that as the request. Nobody asking for "leave next week" has
    # said which days of it they want, and a 7-day guess is not a small
    # error: it spends a week of someone's balance on days they never named,
    # and an employee's real working days depend on a roster Helix cannot
    # see. The rule is that Helix fills dates in only when it can determine
    # them reliably; otherwise it shows the date picker.
    if resolved and resolved.get("matched_kind") in ("next_month", "next_calendar_week"):
        logger.info(
            "[Graph] Discarding bare %r match — no day/weekday named, genuinely "
            "ambiguous which dates within the period. query=%r",
            resolved.get("matched_kind"), 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:
                    # Recorded, not resolved. Letting the range quietly win
                    # assumes the employee meant the range and mistyped the
                    # count, and nothing here knows which half is the
                    # mistake — "2 days from Thursday to Saturday" is equally
                    # likely to be a wrong end date or a wrong count.
                    #
                    # It also produced genuinely broken requests: the
                    # deterministic resolvers downstream can move from_date
                    # without moving to_date, and this exact shape reached
                    # the confirmation card as 0.0 and then -1.0 day(s).
                    # CEO review point 3: never guess when the request
                    # contradicts itself.
                    logger.warning(
                        "[Graph] Duration count (%s day(s)) conflicts with explicit date range "
                        "(%s day(s), %s to %s) — asking rather than choosing. query=%r",
                        duration_days, actual_days, slots["from_date"], slots["to_date"], query,
                    )
                    # setdefault, not assignment: extraction may already have
                    # flagged this message, and its reading of the phrase is
                    # the one the employee actually wrote. Overwriting it
                    # here produced "you mentioned 2 days, but the dates you
                    # gave cover 7" for a Thursday-to-Saturday range — a
                    # number from this layer's own resolution, not from
                    # anything the employee said.
                    slots.setdefault("_duration_range_conflict", {
                        "duration_days": duration_days,
                        "range_days": actual_days,
                    })
            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 not llm_from_date:
        return None

    # Checked BEFORE the det_matched early-out below, unlike everything else
    # in this function. The rest of these reasons are judgement calls about
    # whether the LLM can be trusted alone, and a deterministic match settles
    # those. These two are not judgement calls: a string that is not a date,
    # or a range that ends before it starts, is wrong whoever produced it.
    #
    # The inversion is often introduced BY the deterministic layer — a
    # resolver can move from_date without moving to_date — so gating this on
    # det_matched switched the check off in exactly the case that needed it.
    invalid = {"reason": "invalid", "llm_from_date": llm_from_date, "llm_to_date": llm_to_date}
    try:
        from_d = date.fromisoformat(llm_from_date)
    except (TypeError, ValueError):
        return invalid

    if llm_to_date:
        try:
            to_d = date.fromisoformat(llm_to_date)
        except (TypeError, ValueError):
            return invalid
        if to_d < from_d:
            return invalid

    if det_matched:
        return None

    if det_matched:
        return None

    # "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

    # A bare ordinal day-of-month that has already passed this month ("on
    # 8th" asked on the 9th) is ambiguous about the MONTH and nothing else,
    # and that ambiguity is exactly what puts the model's guess in the past
    # when it doesn't roll the month forward. Checked AHEAD of "past_date"
    # for two reasons, both from the live report (2026-09-09):
    #
    #  - Consistency. The identical query "apply leave on 8th" came back as
    #    "2026-09-08 has already passed..." on one run and "I want to make
    #    sure I get the right day..." on the next, purely because the model
    #    guessed 2026-09-08 once and 2026-10-08 the other time. The reason
    #    the user is asked must not depend on which way that guess fell.
    #  - Accuracy. "past_date" reports a specific date back to the user as
    #    though they had asked for it — but they never typed a month at all,
    #    so naming 2026-09-08 as "already passed" describes an inference the
    #    assistant made, not anything the user said.
    ambiguous_day = date_resolver.mentions_ambiguous_bare_day_of_month(query, today)
    if ambiguous_day is not None:
        return {
            "reason": "ambiguous_bare_day_of_month", "day": ambiguous_day,
            "llm_from_date": llm_from_date, "llm_to_date": llm_to_date,
        }

    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


_BALANCE_RETRY_SLOTS = (
    "balance_retry_from_date", "balance_retry_to_date", "balance_retry_leave_type",
)


def _clear_balance_retry(slots: dict) -> None:
    """Drops the dates parked by an insufficient-balance rejection so they
    can't resurface on an unrelated later turn — see the restore block in
    leave_action_node. Safe to call when nothing is parked."""
    for key in _BALANCE_RETRY_SLOTS:
        slots.pop(key, None)


def _next_date_on_day_of_month(day: int, today: date) -> Optional[date]:
    """The next calendar date after `today` that falls on day-of-month
    `day`, skipping months that don't have it (a bare "31st" in a 30-day
    month, "30th" in February). Deterministic arithmetic on a day number
    the user typed literally — no inference about WHICH day, only which
    month — so unlike the model's own guess this is safe to state back to
    the user (see the ambiguous_bare_day_of_month branch in
    leave_action_node). None if `day` isn't a real day-of-month at all.

    Only ever called for a day already passed this month (that is
    mentions_ambiguous_bare_day_of_month's own precondition), so the search
    starts at the following month. 14 iterations covers the worst case (the
    31st, from a February) with room to spare."""
    if not 1 <= day <= 31:
        return None
    year, month = today.year, today.month
    for _ in range(14):
        month += 1
        if month > 12:
            month, year = 1, year + 1
        try:
            return date(year, month, day)
        except ValueError:
            continue  # e.g. the 31st of a 30-day month
    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"))


# Deliberately NOT the cancel flow's _is_confirming/_is_strong_cancel_decline.
# Those carry cancel-specific semantics (a bare "cancel" reads as a decline
# there) that mean nothing when the question on screen is "did you mean
# 'fever'?". Narrow patterns, scoped to that one question.
_SPELLING_CONFIRM = re.compile(
    r"^\s*(y|ya|yes|yeah|yep|yup|ok|okay|sure|correct|right|thats?\s+right|"
    r"exactly|confirm|use\s+(that|it))\b[\s.!]*$", re.IGNORECASE)
_SPELLING_DECLINE = re.compile(
    r"^\s*(n|no|nope|nah|wrong|incorrect|keep\s+(it|mine|as\s+is)|"
    r"leave\s+it|as(\s+i)?\s+(wrote|typed)(\s+it)?)\b[\s.!]*$", re.IGNORECASE)


# Typed agreement the fixed list misses. QA: "yess" at the reason question
# reached the model, which read it as a new reason, and the card said
# "Reason: Yess". Held letters are collapsed first ("yesss", "okk", "yeahh"),
# and the common slips are named; both are still whole-reply matches only.
_CONFIRM_TYPOS = re.compile(r"^\s*(yrs|yse|ys|yea|yah|yas|yeh|okie|okey|k)\b[\s.!]*$", re.IGNORECASE)
_HELD_LETTERS = re.compile(r"([a-z])\1+", re.IGNORECASE)


def _is_spelling_confirm(query: str) -> bool:
    q = query or ""
    collapsed = _HELD_LETTERS.sub(r"\1", q)
    return bool(_SPELLING_CONFIRM.match(q) or _SPELLING_CONFIRM.match(collapsed)
                or _CONFIRM_TYPOS.match(collapsed))


def _is_spelling_decline(query: str) -> bool:
    q = query or ""
    return bool(_SPELLING_DECLINE.match(q) or _SPELLING_DECLINE.match(_HELD_LETTERS.sub(r"\1", q)))


def _substitute_preserving_case(text: str, as_typed: str, replacement: str) -> str:
    """Swaps the FIRST whole-word occurrence of `as_typed` for `replacement`,
    carrying over the case of what it replaced.

    The suggestion arrives lowercase from the model. Dropped in verbatim it
    un-capitalises the reason whenever the uncertain word leads the sentence —
    "Fvr" confirmed as "fever" saved as "fever", undoing the capitalization
    the same story asks for two requirements earlier.
    """
    def _sub(m: re.Match) -> str:
        found = m.group(0)
        if found[:1].isupper():
            return replacement[:1].upper() + replacement[1:]
        return replacement

    return re.sub(rf"\b{re.escape(as_typed)}\b", _sub, text, count=1, flags=re.IGNORECASE)


# A whole-week reference with no day named inside it. "next week" resolved to
# Monday-Sunday, SEVEN days including the weekend, and offered that as the
# request. CEO review point 8 removes that assumption outright: Helix fills
# dates in only when it can determine them reliably from employee/company
# data, and must otherwise put the date picker on screen and ask. An
# employee's real working days depend on a roster and weekly-off pattern
# Helix does not have, so today it always asks.
#
# The exclusion is what makes it safe: "next week monday", "next week from
# the 14th" and "monday to wednesday next week" all NAME something inside the
# week, so they are ordinary date phrases and are left alone. Only the bare
# span is ambiguous.
# A vague PERIOD with no specific day named inside it. "week" was the only one
# covered, so "I need leave next month" sailed past this guard entirely and got
# resolved into a ~30-day span.
# Backward spans too: QA's "CL for previous week" silently became one day of
# it - 14th, 15th or 16th depending on the run - and was then refused as past.
_BARE_WEEK_SPAN_RE = re.compile(
    r"\b(?:next|the following|coming|upcoming|this|previous|last|past)\s+(?:week|month|fortnight)\b"
    r"|\bnext\s+couple\s+of\s+(?:days|weeks)\b"
    r"|\bin\s+a\s+(?:week|month)\b",
    re.IGNORECASE)
_WEEK_SPAN_NARROWED_RE = re.compile(
    r"\b(?:mon|tues?|wed(?:nes)?|thur?s?|fri|sat(?:ur)?|sun)(?:day)?\b"
    r"|\d{1,2}\s*(?:st|nd|rd|th)?\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)"
    r"|\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{1,2}\b"
    r"|\d{4}-\d{2}-\d{2}"
    r"|\b(?:first|second|third|fourth|last)\s+(?:day|half)"
    r"|\b(?:today|tomorrow|yesterday)\b"
    r"|\bfrom\b.*\bto\b",
    re.IGNORECASE)


def _names_a_bare_week_span(query: str) -> bool:
    """True for "leave next week" — a week named with nothing inside it."""
    q = query or ""
    if not _BARE_WEEK_SPAN_RE.search(q):
        return False
    return not _WEEK_SPAN_NARROWED_RE.search(q)



def _reason_matches_what_was_typed(raw_text: str, cleaned_reason: str) -> bool:
    """True when Helix's stored reason IS what the employee typed, give or
    take capitalisation and a trailing full stop.

    Decides whether the approval question is worth asking. The CEO review
    requires confirmation for an AI-MODIFIED reason; when Helix changed
    nothing there is nothing to approve, and the confirmation card that comes
    next already shows the reason before anything is submitted.

    Equality, deliberately not "is the reason contained in what they typed".
    A containment test would wave through "i have personal work" -> "Personal
    work", and stripping filler IS a modification — the employee should see
    that Helix dropped words before it is saved.

      "Fever"                     -> "Fever"          same, no question
      "personal work"             -> "Personal work"  same but for case, no question
      "i have personal work"      -> "Personal work"  CHANGED, ask
      "The reason is vacation"    -> "Vacation"       CHANGED, ask
      "feever and weaknes"        -> "Fever and weakness"  CHANGED, ask
    """
    def _norm(t: str) -> str:
        return " ".join(str(t or "").strip().rstrip(".!,").lower().split())

    return bool(cleaned_reason) and _norm(raw_text) == _norm(cleaned_reason)



def _drop_unusable_reason_uncertainty(extracted: dict) -> None:
    """Clears reason_uncertain_* unless it survives STEP 5's own gates.

    Mutates `extracted` in place. A flag that does not survive is simply
    dropped — never escalated into a question — so the worst case is the
    silent correction Helix would have made anyway, not a needless
    "did you mean?" round trip.

    Gate 1: the flagged word must still be in "reason" EXACTLY as typed. If
      the model wrote a corrected spelling into "reason" it plainly knew what
      the word meant, and asking about it would be theatre. This is the gate
      the model gets wrong most often — live, "persnal work" came back
      corrected to "Personal work" AND flagged.
    Gate 3: it must be ONE word from the message, not a phrase and not the
      whole reason — a question quoting the entire message back reads as
      Helix having understood nothing.
    Plus: both fields or neither, and the suggestion must actually differ
    from what they typed.
    """
    as_typed = (extracted.get("reason_uncertain_as_typed") or "").strip()
    suggestion = (extracted.get("reason_uncertain_suggestion") or "").strip()
    reason = extracted.get("reason") or ""

    ok = bool(as_typed and suggestion and reason)
    if ok and len(as_typed.split()) != 1:
        ok = False                                      # gate 3
    if ok and as_typed.lower() == suggestion.lower():
        ok = False                                      # nothing to ask
    if ok and not re.search(rf"\b{re.escape(as_typed)}\b", reason, re.IGNORECASE):
        ok = False                                      # gate 1 — already corrected

    if not ok:
        extracted.pop("reason_uncertain_as_typed", None)
        extracted.pop("reason_uncertain_suggestion", None)



def _normalize_type_name(name) -> str:
    """"Casual Leave" / "casual leave" / " Casual  Leave " -> "casual_leave",
    so a display name from one endpoint can be matched against a slug from
    another."""
    return "_".join(str(name or "").strip().lower().split())


def _abbreviations_for_configured_types(
    abbrev_payload, known_leave_types: Optional[list[dict]],
) -> dict[str, str]:
    """{"CL": "casual_leave", "SL": "sick_leave"} — the company's shorthand,
    narrowed to the leave types this company has actually CONFIGURED.

    The configured list is the gate, and that is the whole design (HA-665
    review). Helix never decides that CL means Casual Leave; it reads that
    from the company's own configuration, and honours it only when Casual
    Leave is a type this company has. A company without Earned Leave gets no
    "EL", and nothing needs special-casing for it. A company that calls
    casual leave "PL" works with no code change at all.

    It also disposes of everything in the abbreviations payload that is not a
    leave type — "A": "Absent", "P": "Present", "O": "Off", "HD": "Half Day
    Leave" (a session type here, not a type you apply for), the
    regularization codes, and the bare "L": "Leave" — because none of their
    names match a configured leave slug. No exception list to keep in sync as
    the endpoint grows.
    """
    if not known_leave_types or not isinstance(abbrev_payload, dict):
        return {}

    configured = {t["slug"] for t in known_leave_types if t.get("slug")}
    # A type is matched on its slug AND its display name, since those are the
    # two spellings the two endpoints use for the same thing.
    slug_by_name = {}
    for t in known_leave_types:
        slug = t.get("slug")
        if not slug:
            continue
        slug_by_name[_normalize_type_name(slug)] = slug
        if t.get("name"):
            slug_by_name[_normalize_type_name(t["name"])] = slug

    out: dict[str, str] = {}
    for abbrev, full_name in abbrev_payload.items():
        if not abbrev or not isinstance(abbrev, str):
            continue
        slug = slug_by_name.get(_normalize_type_name(full_name))
        if slug and slug in configured:
            out[abbrev.strip()] = slug
    return out


async def _fetch_leave_abbreviations(
    erp_client_mod, bearer_token: str, company_id, conversation_id: str,
) -> Optional[dict]:
    """The raw {abbrev: name} map, or None. Never raises — see
    erp_client.get_leave_abbreviations. A company that has configured none,
    or an endpoint not deployed yet, simply leaves Helix working off full
    names as before."""
    try:
        result = await erp_client_mod.get_leave_abbreviations(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
        )
    except Exception as e:
        logger.warning("[Graph] leave abbreviations unavailable: %s", e)
        return None
    data = (result or {}).get("body", {}).get("data")
    return data if isinstance(data, dict) else None


# Reason examples shown with the "what's the reason?" question, per leave
# type (HA-665). Asking for a reason with no examples left employees guessing
# at the register expected; asking with SICK examples while they apply for
# casual leave is worse.
#
# Defaults, not hard rules. The keys are this deployment's slugs, and the
# CONFIGURED type is what selects the list — a company without earned leave
# never sees the earned-leave examples. When the leave configuration starts
# carrying its own examples they should take precedence over this table; it
# exists so the question is useful today, not to be the source of truth.
_REASON_EXAMPLES_BY_SLUG: dict[str, tuple[str, ...]] = {
    "sick_leave": ("Fever", "Doctor's appointment", "Medical checkup"),
    "casual_leave": ("Personal work", "Home maintenance", "Family function"),
    "earned_leave": ("Vacation", "Travel", "Personal time off"),
    "short_leave": ("Bank work", "Late arrival", "Personal errand"),
}

# For a type with no entry above — a custom or newly configured one — and for
# the case where the reason is asked before any type is known. Deliberately
# spans personal AND medical so it steers nobody toward either.
_REASON_EXAMPLES_FALLBACK: tuple[str, ...] = ("Personal work", "Doctor's appointment")

# Asked for with "do you have other reasons?" - never a repeat of the first set.
_MORE_REASON_EXAMPLES_BY_SLUG: dict[str, tuple[str, ...]] = {
    "sick_leave": ("Cold and cough", "Migraine", "Recovering after treatment", "Dental procedure"),
    "casual_leave": ("Bank work", "Travel", "Attending a wedding", "Child's school event"),
    "earned_leave": ("Family event", "Pilgrimage", "Relocation", "Rest and recovery"),
    "short_leave": ("Doctor's visit", "School pickup", "Government office work", "Vehicle repair"),
}
_MORE_REASON_EXAMPLES_FALLBACK: tuple[str, ...] = ("Family function", "Bank work", "Medical checkup", "Travel")
_MORE_REASONS_RE = re.compile(
    r"\b(?:other|more|different|another|additional)\s+(?:reasons?|options?|examples?|suggestions?)\b"
    r"(?!\s+(?:is|was|are)\b|\s*[:=-])|\bany\s+(?:other|more)\b(?!\s+\w+\s+(?:is|was)\b)", re.IGNORECASE)
_NON_POSITIVE_DAY_COUNT_RE = re.compile(
    r"(?<![\w.])(-\s?\d+(?:\.\d+)?|0+(?:\.0+)?)\s*days?\b", re.IGNORECASE)
# "Apply leave for 500 days starting tomorrow" went on to ask the leave type
# (UV-25, 29 Oct). No leave runs longer than a year.
_MAX_LEAVE_DAYS = 365
_DAY_COUNT_RE = re.compile(r"(?<![\w.\-])(\d{1,6})\s*(?:working\s+|calendar\s+)?days?\b", re.IGNORECASE)
# "yesterday in the year 1990", "5 Nov 1990", "10/11/1990": a year far from
# now. A year only where a date can hold one - not a number in a reason.
_EXPLICIT_YEAR_RE = re.compile(
    r"(?:\b(?:in|of|year)\s+(?:the\s+year\s+)?"
    r"|\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?\s+(?:\d{1,2}(?:st|nd|rd|th)?,?\s+)?"
    r"|\b\d{1,2}(?:st|nd|rd|th)?\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?,?\s+"
    r"|\b\d{1,2}[/-]\d{1,2}[/-])((?:19|20)\d{2})\b", re.IGNORECASE)


def _impossible_leave_span(query: str, today: date) -> Optional[str]:
    """The refusal for a day count or a year no leave can have, else None."""
    for m in _DAY_COUNT_RE.finditer(query or ""):
        if int(m.group(1)) > _MAX_LEAVE_DAYS:
            return (f"{m.group(1)} days is longer than any leave I can apply for — a single leave "
                    f"can't run longer than a year. How many days, or which dates, would you like?")
    for m in _EXPLICIT_YEAR_RE.finditer(query or ""):
        year = int(m.group(1))
        if abs(year - today.year) > 1:
            return (f"I can't apply leave for a date in {year} — leave can only be for dates around "
                    f"now. Which dates would you like?")
    return None


_NONE_OF_THESE_RE = re.compile(
    r"\bnone\s+of\s+(?:these|those|them)\b|\bnothing\s+(?:fits|matches)\b|\bneither\b", re.IGNORECASE)


def _display_leave_type_name(leave_type_slug: Optional[str]) -> str:
    """'casual_leave' -> 'Casual Leave'. From the slug rather than
    _SLUG_TO_LEAVE_TYPE_WORD, which maps to the single MATCH word ('casual')
    and reads as a half-finished sentence."""
    if not leave_type_slug:
        return ""
    return str(leave_type_slug).replace("_", " ").title()


#: The leave types Helix can APPLY for. erp-api also configures Comp Off and
#: Leave Without Pay, but those cannot be filed through Helix right now
#: (product rule) - so they are neither offered nor accepted by the apply flow.
#: Viewing, balance and cancellation are unaffected.
HELIX_APPLICABLE_LEAVE_TYPES = ("casual_leave", "sick_leave", "earned_leave", "short_leave")

#: The longest leave reason erp-api accepts. Checked before the read-back and
#: the confirmation card, not left to erp-api's rejection at submission.
MAX_LEAVE_REASON_LENGTH = 200

# Anyone else's leave balance, or the team's: only HR may see those (see
# permission_service.may_view_others_leave_balance).
OTHERS_BALANCE_REFUSAL = ("You can't see your team's leave balance or anyone else's leave "
                          "balance. If you need it, please contact HR.")


def _clear_abandoned_questions(company_id, conversation_id: str) -> None:
    """Close every OTHER question this conversation left unanswered - the
    cancel-leave card, a manager approve/reject card, "which employee?" -
    because the employee is applying for leave now, and any of them would
    otherwise claim the next bare "cancel" / "yes" / "no" meant for the apply
    card. Best-effort by design: each store is tried on its own, and a failing
    one is logged and skipped, never allowed to break the application."""
    def _try(label, fn):
        try:
            fn()
        except Exception as e:
            logger.warning("[Leave] could not clear an abandoned %s: %s", label, e)

    def _cancel():
        if leave_cancel_state.get_state(company_id, conversation_id):
            logger.info("[Leave] apply flow running - clearing an abandoned cancel-leave question")
            leave_cancel_state.clear_state(company_id, conversation_id)

    def _manager_card():
        if leave_slot_service.get_manager_action(company_id, conversation_id):
            logger.info("[Leave] apply flow running - clearing an abandoned manager approval card")
            leave_slot_service.clear_manager_action(company_id, conversation_id)

    def _selection():
        report = leave_slot_service.get_report_state(company_id, conversation_id) or {}
        if report.get("step") == "awaiting_employee_selection":
            # Only the open QUESTION is dropped; the remembered subject (used
            # for "and his attendance?"-style follow-ups) is kept.
            logger.info("[Leave] apply flow running - clearing an abandoned employee-selection question")
            leave_slot_service.set_report_state(
                company_id, conversation_id,
                {k: v for k, v in report.items() if k not in ("step", "candidates")})

    _try("cancel-leave question", _cancel)
    _try("manager card", _manager_card)
    _try("employee-selection question", _selection)


def _applicable_leave_types_sentence() -> str:
    names = [_display_leave_type_name(s) for s in HELIX_APPLICABLE_LEAVE_TYPES]
    return f"{', '.join(names[:-1])} or {names[-1]}"


def _applicable_only(known_leave_types: list) -> list:
    """The company's configured types, minus the ones Helix cannot file."""
    return [t for t in known_leave_types or [] if t.get("slug") in HELIX_APPLICABLE_LEAVE_TYPES]


def _reason_examples_for(leave_type_slug: Optional[str]) -> str:
    """' (e.g. Fever, Doctor's appointment, Medical checkup)' for the given
    type, or the neutral set when the type is unknown or unlisted. Returns
    the whole parenthetical so callers can append it unconditionally."""
    examples = _REASON_EXAMPLES_BY_SLUG.get(leave_type_slug or "", _REASON_EXAMPLES_FALLBACK)
    return f" (e.g. {', '.join(examples)})"


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())
    names_by_slug = {
        t["slug"]: t.get("name")
        for t in data.get("leave_settings", {}).get("leave_type", [])
        if t.get("slug")
    }
    # The company's CONFIGURED types count too, not only the ones this caller
    # happens to hold a quota row for. QA: "What type of leave would you like
    # to apply for — Casual Leave, Sick Leave, or Short Leave?" with Earned
    # Leave missing - erp-api sent no earned_leave quota for that employee
    # (a type that accrues or starts after confirmation), so it vanished from
    # the question and a typed "earned" would have been refused as unknown.
    # Quota keys still come first, so they keep their order.
    slugs = leave_quota_slugs + [s for s in names_by_slug if s not in leave_quota_slugs]
    if not slugs:
        return None
    return [
        {"slug": slug, "name": names_by_slug.get(slug) or slug.replace("_", " ").title()}
        for slug in 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] = [
    # {0,40}: "is my casual leave for 21st approved" is 27 characters between
    # "is" and "approved", and fell to the LIST path at {0,25}.
    re.compile(r"\b(is|was|has|did)\b[\w\s']{0,40}?\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),
    # A tag question asking to have a belief confirmed - "my leave on 2 nov
    # got approved right?", "it's approved, correct?". It was read as a LIST
    # of approved leaves, so the one asked about (still pending) was never
    # mentioned (negative run, 28 Oct, #56).
    re.compile(r"\b(approved|rejected|accepted|declined)\b[\w\s',]{0,15}?\b(right|correct|na|isn'?t it|no)\s*\?*\s*$",
               re.IGNORECASE),
    re.compile(r"\b(got|been|get|gotten)\s+(approved|rejected|accepted|declined)\b[^?]*\?\s*$", 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
    # A misspelt status word ("apporved", "canel", "canclled", "pendng") -
    # QA: each got the "just to make sure..." question instead of the list it
    # named. Same 5-character floor and 0.75 cutoff as _is_status_word below.
    for token in re.findall(r"[a-z]+", text):
        if len(token) < _MIN_STATUS_WORD_TYPO_LEN:
            continue
        match = difflib.get_close_matches(token, _STATUS_FILTER_TYPO_TARGETS, n=1,
                                          cutoff=_STATUS_WORD_TYPO_CUTOFF)
        if match:
            return _STATUS_FILTER_TYPO_TARGETS[match[0]]
    return None


#: Spellings a typo is measured against, and the filter each one means.
_STATUS_FILTER_TYPO_TARGETS = {
    "pending": "pending",
    "approved": "approved", "approve": "approved",
    "rejected": "rejected", "reject": "rejected",
    "cancelled": "cancelled", "canceled": "cancelled", "cancel": "cancelled",
}


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 _spoken_date(iso_date: Optional[str]) -> Optional[str]:
    """'2026-12-29' -> 'Tue, 29 Dec 2026' — the product's standard dated
    format (the same one the card renders), used in the SPOKEN sentences so
    the day a request actually landed on is always stated rather than echoed
    back as the word the employee typed.

    Naming the weekday alongside the date is what makes a wrong-but-valid
    date visible at a glance: "last monday" quietly resolving to a FUTURE
    Monday read as perfectly normal while the reply only ever said "Monday".
    """
    return _display_date(iso_date, with_weekday=True)


def _selected_date_label(card: dict) -> str:
    """The date shown in the spoken cancel-leave sentences. Now always the
    resolved calendar date(s) in _spoken_date's 'Monday, 14/09/2026' form —
    the card's own Figma-formatted `date_label` is still what the CARD
    renders, this only governs the chat text."""
    from_iso, to_iso = card.get("from_date"), card.get("to_date")
    spoken_from = _spoken_date(from_iso)
    if spoken_from:
        if to_iso and to_iso != from_iso:
            spoken_to = _spoken_date(to_iso) or to_iso
            return f"{spoken_from} to {spoken_to}"
        return spoken_from
    return (
        card.get("date_label")
        or _display_date_range(from_iso, to_iso)
        or f"{from_iso} to {to_iso}"
    )


# The exact strings the cancel-confirmation card's two buttons send. These
# are UI-generated sentinels, not something an employee types, and they mean
# one specific thing: an answer to THAT card. They must never be re-read as
# free text by another flow.
#
# "Keep Request" in particular matches _is_declining_or_cancelling (correctly
# — it declines a cancellation), which in the apply branch means "discard the
# draft". QA hit exactly that: pressing Keep Request discarded the in-progress
# application and reported "I've cancelled that leave request", while the
# request the card was actually about was left untouched.
_CANCEL_CARD_BUTTON_TEXTS = frozenset({"keep request", "confirm cancellation"})
_CANCEL_CARD_BUTTON_FUZZY_CUTOFF = 0.82


def _is_cancel_card_button(query: str) -> bool:
    """True for a press of the cancel-confirmation card's buttons.

    EXACT match on the whole message, and that is the point: the button sends
    a fixed string, so an exact match is the one input that is certainly a
    press and may be acted on without asking. A substring match would let a
    sentence merely containing "keep request" act on sight, and a fuzzy match
    would let a TYPO do the same -- see _resembles_cancel_card_button, which
    is what a typo actually means.
    """
    return (query or "").strip().rstrip(".!").strip().lower() in _CANCEL_CARD_BUTTON_TEXTS


def _resembles_cancel_card_button(query: str) -> bool:
    """A near-miss of a button's text: "kepp request", "confirm cancelation".

    A button cannot produce a typo, so this is always something a person
    TYPED, and it is treated as such -- the flow works out what they meant and
    asks them to confirm it, rather than acting the way a real press does.

    What it must never do again is fall through to the general classifier.
    Reported live with the request body: {"query": "kepp request"} came back
    "That's outside my HR expertise", so one transposed letter turned a clear
    instruction into a brush-off. Recognising it costs nothing; acting on it
    without asking is the part that would be unsafe.
    """
    text = (query or "").strip().rstrip(".!").strip().lower()
    if not text or text in _CANCEL_CARD_BUTTON_TEXTS:
        return False
    # Only a message about as long as a button label can be a mistyped one, so
    # a real sentence never slips through on ratio alone.
    if not (2 <= len(text.split()) <= 3):
        return False
    return any(
        difflib.SequenceMatcher(None, text, button).ratio()
        >= _CANCEL_CARD_BUTTON_FUZZY_CUTOFF
        for button in _CANCEL_CARD_BUTTON_TEXTS
    )


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")],
    )


# erp-api's own wording for this exact rejection (see leave_failure.py's
# _REASON_CODE_PATTERNS / ALREADY_CANCELLED) — reused verbatim here so the
# message reads identically whether it's short-circuited locally or actually
# came back from erp-api. Rejected has no observed erp-api wording of its own
# (a rejected leave never reaches /leave/cancel today, since the cancellable
# picker already excludes it), so this one is Helix's own, not a guess at
# erp-api's phrasing.
_ALREADY_CANCELLED_CANCEL_MESSAGE = "This leave request has already been cancelled."
_ALREADY_REJECTED_CANCEL_MESSAGE = "This leave request has already been rejected, so there's nothing to cancel."
_ALREADY_DECIDED_CANCEL_NEXT_ACTION = "Would you like to see your other leave requests?"


def _already_decided_cancel_card(selected: dict) -> tuple[dict, str]:
    """A specific match (by reference/date/type) can land on a request that's
    already cancelled or rejected — status known locally from the very
    /leave/applied fetch that built this candidate this turn, not guessed.
    Short-circuits the preview/confirm screen entirely for it: there's
    nothing to preview or confirm for a request already in a terminal state,
    and erp-api would only refuse it anyway (live bug report: repeatedly
    confirming looked like it "worked" each time since the preview kept
    reappearing). Returns (card, spoken_message)."""
    is_cancelled = selected.get("status_name") == "cancelled"
    message = _ALREADY_CANCELLED_CANCEL_MESSAGE if is_cancelled else _ALREADY_REJECTED_CANCEL_MESSAGE
    failure = leave_failure.local_failure(message, "ALREADY_CANCELLED" if is_cancelled else None)
    card = leave_failure.build_card(
        "cancel_leave", failure, next_action=_ALREADY_DECIDED_CANCEL_NEXT_ACTION,
        next_actions=[leave_failure.chip("View My Leave Requests", "view_leave_requests")],
    )
    return card, message


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}"


# erp-api's spellings for "why this request ended up decided against the
# employee" — rejection_reason on a rejected record, cancel_reason on a
# cancelled one (cancellation_reason/cancelled_reason are accepted too, since
# the /leave/applied and /leave/cancel payloads have not always agreed on the
# name). Order matters only in the impossible case of a record carrying more
# than one: the rejection is then the decision that stands.
_DECISION_REASON_KEYS = (
    "rejection_reason", "cancel_reason", "cancellation_reason", "cancelled_reason",
)


def _decision_reason(lv: dict):
    """The rejection or cancellation note on a leave record, whichever key
    erp-api used for it. Empty strings are treated as absent (erp-api sends
    "" as readily as null for "no note"), so a caller can test the value
    itself rather than having to trim it first."""
    for key in _DECISION_REASON_KEYS:
        value = lv.get(key)
        if isinstance(value, str):
            value = value.strip()
        if value:
            return value
    return None


# ── /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"),
        # The frontend's "Reason" tab reads ONE key for the decision-side
        # note on a record — rejection_reason — whatever the decision was.
        # erp-api, though, files a cancellation's note under its own
        # cancel_reason field (the same name /leave/cancel takes in its
        # request body), so a cancelled leave arrived here with
        # rejection_reason: null and the note the employee actually typed
        # never reached the tab. _decision_reason folds both spellings into
        # that one key; cancel_reason is also passed through unchanged for
        # any caller that wants the un-merged field.
        "rejection_reason": _decision_reason(lv),
        "cancel_reason": lv.get("cancel_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
    # A cancelled record folds its note in the same way a rejected one does
    # — both now arrive under rejection_reason (see _decision_reason), and
    # "is cancelled — plans changed" reads exactly like its rejected
    # counterpart. Every other status is left alone: `reason` (why the leave
    # was requested) is already in the card and is not this sentence's job.
    reason_suffix = (
        f" — {lv['rejection_reason']}"
        if status in ("rejected", "cancelled") 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")

# Naming the ARTIFACT — "my leave request(s)", "my applications" — is itself an
# answer to "balance, applied requests, or a status subset?". A balance is not
# a request, so "show my leave request" cannot mean the balance, and it names
# no status either: it is the applied-requests case, stated plainly.
#
# Without this it fell into the ambiguous branch and was answered with a
# clarifying question listing three options, one of which the user had already
# ruled out by their own wording. Asking a question whose answer is in the
# question is worse than a wrong default - the user has to restate what they
# just said.
#
# Deliberately the NOUN sense only. "request" as a verb ("can I request
# leave") is an apply-leave question that never reaches this branch, but the
# patterns are anchored to leave/possessive wording rather than the bare word
# so the distinction does not rely on routing alone.
_REQUEST_ARTIFACT_RE = re.compile(
    r"\b(?:leave|leaves)\s+(?:request|application)s?\b"        # "my leave request(s)"
    r"|\b(?:request|application)s?\s+(?:for|of)\s+leaves?\b"   # "requests for leave"
    r"|\bmy\s+(?:request|application)s?\b",                    # "show my requests"
    re.IGNORECASE,
)


def _names_request_artifact(query: str) -> bool:
    """True when the query names the submitted request(s) rather than asking
    about a balance or a status subset."""
    return bool(_REQUEST_ARTIFACT_RE.search(query))


#: "apply"/"appy"/"aply"/"aplied"/"applyed" in a STATUS query ("show my apply
#: leaves") mean the applied-requests list. Only read here, in the status
#: branch, where the apply-leave action has already been ruled out upstream.
_APPLIED_WORD_RE = re.compile(r"\ba+p+(?:l+[iy]|l*y)(?:e?d)?\b")


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


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


# "20 to 24 aug", "5th to 10th november", "1 oct till 5 oct" - two day
# numbers joined by a range word. Deliberately word-connectors only: a
# dash range ("05-11 to 10-11") is already resolved by
# date_resolver.resolve_numeric_date_range at the top of the chain, and
# matching "-" here would also fire on the middle of a plain ISO date.
_EXPLICIT_DAY_RANGE_PATTERN = re.compile(
    r"\b\d{1,2}(?:st|nd|rd|th)?\s*(?:[a-z]{3,9}\s*)?"
    r"(?:to|till|untill|until|through|thru)\s+(?:the\s+)?\d{1,2}(?:st|nd|rd|th)?\b",
    re.IGNORECASE,
)


def _single_date_anchor(query: str, today: Optional[date] = None) -> Optional[dict]:
    """An explicit calendar date or a today/yesterday-style word, in the shape
    _apply_deterministic_date_overrides' resolver chain expects.

    These three resolvers were already trusted for the cancel flow; this makes
    the apply flow use them too. Ordered narrowest-first: an absolute mention
    ("25 aug", "15th october") before a bare numeric one ("2026-10-15",
    "08/09/2026", day-first), with the relative day word last since the
    chain's own resolvers already cover today/tomorrow ahead of this."""
    # _resolve_numeric_date_mention is deliberately NOT used here. It is a
    # cancel-flow resolver tuned for day-first "12-08"/"08/09/2026", and on an
    # ISO date whose year isn't the current one it reads the tail as DD-MM and
    # silently substitutes today's year: "2030-06-04" came back 2026-04-06.
    # The apply flow does not need it — genuinely ambiguous slash/dash dates
    # are already resolved deterministically by
    # date_resolver.resolve_numeric_date_range at the top of this chain, and a
    # literal ISO date needs no arithmetic at all, so it is the one date form
    # a model does not get wrong. This anchor exists for the forms models DO
    # get wrong: weekday names and "25 aug"/"15th october".
    for resolver, kind in (
        (_resolve_absolute_date_mention, "absolute_date"),
        (_resolve_relative_day_date, "relative_day"),
    ):
        # An explicit two-ended range ("from 20 to 24 aug", "from 5th to
        # 10th november") is not a single date, and this anchor can only
        # return one. _resolve_absolute_date_mention happily matched the
        # date on ONE end of it and the chain then overwrote from_date with
        # it - "20 to 24 aug" came out as a one-day request on the 24th,
        # and "from 5th to 10th november" as from_date=10 Nov, to_date=10
        # Nov. Both silently shortened a range the user had stated
        # unambiguously.
        #
        # Only the absolute-date resolver is stood down: a relative day word
        # opening a range ("from tomorrow to friday") does correctly give
        # the range's START, and to_date is protected separately by
        # llm_gave_distinct_range.
        if kind == "absolute_date" and _EXPLICIT_DAY_RANGE_PATTERN.search(query):
            continue
        iso = resolver(query, today)
        if iso:
            return {"from_date": iso, "matched_phrase": iso, "matched_kind": kind}
    return None


# "last monday", "previous friday", "past tuesday" — a BACKWARD weekday
# reference. _resolve_weekday_mention reports only whether an explicit
# "next" was used, so without this the word is dropped and the weekday
# resolves to the upcoming occurrence instead of the most recent one.
_PAST_WEEKDAY_QUALIFIER = re.compile(
    r"\b(?:last|previous|past)\s+"
    r"(?:mon|tue|tues|wed|wednes|thu|thur|thurs|fri|sat|satur|sun)(?:day)?\b",
    re.IGNORECASE,
)


# "the monday after next", "the week after next" - a weekday pushed out by
# a WHOLE EXTRA WEEK. _resolve_weekday_mention only reports whether an
# explicit "next" was used and drops everything else, so "the monday after
# next" was read as the plain weekday name and resolved to the UPCOMING
# Monday - a week early, and confidently enough that tier 2 (which does
# understand the "next_to_next" relation) never ran and tier 3's
# ambiguous-phrase safety net never fired either.
#
# Vetoed rather than computed here: this anchor exists for the plain
# "...on sunday" case, and a phrase this layer cannot work out is exactly
# what the two layers behind it are for.
_WEEK_SHIFTED_WEEKDAY_QUALIFIER = re.compile(
    r"\b(?:(?:mon|tue|tues|wed|wednes|thu|thur|thurs|fri|sat|satur|sun)(?:day)?\s+|week\s+|fortnight\s+)?"
    r"after\s+(?:the\s+)?(?:next|this)\b",
    re.IGNORECASE,
)


def _bare_weekday_anchor(query: str, today: Optional[date] = None) -> Optional[dict]:
    """_resolve_weekday_date's answer in the shape
    _apply_deterministic_date_overrides' resolver chain expects
    ({from_date, matched_phrase, matched_kind}).

    Exists so the apply flow can treat a bare weekday name the way the
    cancel flow already does. Kept as the LAST candidate in that chain: every
    resolver above it recognises a more specific phrasing ("next monday",
    "first monday of october"), and this must not pre-empt them — it is only
    for the plain "...on sunday" case that previously matched nothing at all
    and was left to the model's own arithmetic."""
    if _WEEK_SHIFTED_WEEKDAY_QUALIFIER.search(query):
        return None
    # "<weekday> of this/current week" belongs to
    # date_resolver.resolve_this_week_weekday_phrase, which returns None ON
    # PURPOSE once that day has passed, so the back-date check answers it
    # ("past date"), same as "yesterday". Resolving the bare weekday here
    # instead picked the NEXT one: "monday of current week" asked on Tue
    # 25 Aug became Mon 31 Aug, a date nobody asked for.
    if date_resolver._THIS_WEEK_WEEKDAY_PATTERN.search(query):
        return None
    mention = _resolve_weekday_mention(query)
    iso = _resolve_weekday_date(query, today)
    if not iso:
        return None
    # _WEEKDAY_NAMES maps name -> index, so invert it for the log label.
    label = next(
        (name for name, idx in _WEEKDAY_NAMES.items() if mention and idx == mention[1]),
        "that weekday",
    )
    return {"from_date": iso, "matched_phrase": label, "matched_kind": "bare_weekday"}


_WEEKDAY_WORD_RE = re.compile(
    r"\b(?:mon|tues?|wed(?:nes)?|thu(?:rs)?|fri|sat(?:ur)?|sun)(?:day)?\b", re.IGNORECASE)


def _resolve_weekday_date(query: str, today: Optional[date] = None) -> Optional[str]:
    # "last Friday of Aug month" / "first Monday of the July month" name a
    # weekday WITHIN a month - date_query_resolver's ordinal case. QA: the
    # "last" below turned it into last week's Friday (18 Sep, not 28 Aug).
    for m in _WEEKDAY_WORD_RE.finditer(query or ""):
        if date_resolver._WEEKDAY_OF_MONTH_TAIL.match(query[m.end():]):
            return None
    resolved = _resolve_weekday_mention(query)
    if not resolved:
        return None
    explicit_next, target_weekday = resolved
    from datetime import timedelta
    # today: the caller's "now" when it has one (the apply flow's
    # _apply_deterministic_date_overrides is handed it); the clock otherwise.
    today = today or _today()
    # "last monday" / "previous friday" / "past sunday" — BACKWARD.
    # _resolve_weekday_mention reports only whether an explicit "next" was
    # used and drops "last" entirely, so without this the weekday resolved
    # to its UPCOMING occurrence. Live bug, in both flows: "cancel my leave
    # for last monday" (today Wed 9 Sep) offered the request on Mon 14 Sep,
    # a future date, and "apply casual leave for last monday" landed on the
    # same wrong day. Handled here rather than at either call site so the
    # apply and cancel paths cannot drift apart on it.
    if _PAST_WEEKDAY_QUALIFIER.search(query):
        return date_query_resolver.most_recent_weekday_before(today, target_weekday).isoformat()
    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, today: Optional[date] = None) -> 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 or _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)
# The whole day+month phrase ("20th nov", "nov 20th", "20 november"), so the
# year hint can go straight after it.
_DATE_PHRASE_FOR_YEAR_HINT = re.compile(
    r"\b\d{1,2}(?:st|nd|rd|th)?\s+(?:of\s+)?(?:" + _MONTH_NAME_ALTERNATION + r")\b\.?"
    r"|\b(?:" + _MONTH_NAME_ALTERNATION + r")\b\.?\s+\d{1,2}(?:st|nd|rd|th)?\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, today: Optional[date] = None) -> Optional[str]:
    from datetime import date
    today = today or _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
    # Right after the date, never at the end of the message. QA: "casul leave
    # on 20th nov for family function" became "... for family function 2026",
    # and the reason was saved as "Family function 2026".
    m = _DATE_PHRASE_FOR_YEAR_HINT.search(query)
    if m:
        return f"{query[:m.end()]} {d.year}{query[m.end():]}"
    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

    # Same top precedence, and for the same reason, as the numeric-date check
    # in _apply_deterministic_date_overrides — a leave-status query reads
    # "10/09/2026" day-first exactly as an apply-leave one does. Restored
    # 2026-09-07: dropped from BOTH functions in the same port from
    # hr_graph.py's deleted duplicate.
    numeric_range_result = date_resolver.resolve_numeric_date_range(query, today)
    if numeric_range_result and numeric_range_result[1] is not None:
        first, second = numeric_range_result
        return first["from_date"], second["from_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
        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 = (
        numeric_range_result[0] if numeric_range_result
        else 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=LLM_TASK_MAX_TOKENS, 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


# A day of the month with no month: "for 25th", "on the 21st", "for 3". Not a
# count or a time ("25 days", "3 months", "10 am", "25/09") and not a day that
# already has its month ("25th september" - resolved as a range upstream).
_BARE_DAY_OF_MONTH_RE = re.compile(
    r"\b(?:on|for|of|dated)\s+(?:the\s+)?(\d{1,2})(?:st|nd|rd|th)?\b"
    r"|\b(\d{1,2})(?:st|nd|rd|th)\b",
    re.IGNORECASE)
_NOT_A_BARE_DAY_RE = re.compile(
    r"^\s*(?:days?|weeks?|months?|years?|hours?|hrs?|am|pm|[:/.-]\d"
    r"|(?:of\s+)?(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*)\b",
    re.IGNORECASE)


def _bare_day_of_month(query: str) -> Optional[int]:
    for m in _BARE_DAY_OF_MONTH_RE.finditer(query or ""):
        if _NOT_A_BARE_DAY_RE.match(query[m.end():]):
            continue
        day = int(m.group(1) or m.group(2))
        if 1 <= day <= 31:
            return day
    return None


def _ordinal_suffix(day: int) -> str:
    if 11 <= day % 100 <= 13:
        return "th"
    return {1: "st", 2: "nd", 3: "rd"}.get(day % 10, "th")


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]

    # A bare number that didn't resolve as a position above (out of range,
    # or 3+ digits so the ordinal regex never even considered it) is very
    # plausibly the reference NUMBER's own digits, typed without the "LR-"
    # prefix — the card list prominently shows "Ref #LR-159", and typing
    # just the number seen on screen is the single most natural reply.
    # Live bug: "159" for a list showing "Ref #LR-159" fell through every
    # check above (_extract_request_id needs an "LR-"/"#"/"leave X"/
    # "request X" prefix it doesn't have, and the ordinal regex only ever
    # looks at 1-2 digit numbers) and got a generic "couldn't quite tell"
    # instead of matching the one obvious card. Only trusted when it
    # narrows to exactly one candidate — same "never guess" discipline as
    # every other match here.
    m_any_digits = re.search(r"\b(\d+)\b", text)
    if m_any_digits:
        by_bare_digits = [c for c in candidates if _card_matches_request_id(c, m_any_digits.group(1))]
        if len(by_bare_digits) == 1:
            return by_bare_digits[0]

    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] = {
    # A live typo ("show causal leave request of geo3") that otherwise
    # silently meant "every type". Harmless as an alias: "causal" is not an
    # HR word anyone means literally. Listed BEFORE the real spelling on
    # purpose: _SLUG_TO_LEAVE_TYPE_WORD inverts this dict and the last word
    # for a slug wins, so the canonical spelling must come last or replies
    # would print the typo back ("no pending causal requests").
    "causal": "casual_leave",
    "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",
    # QA: "apply for LOP next week" matched nothing and went on to ask for dates.
    "lop": "leave_without_pay",
    "loss of pay": "leave_without_pay",
    "compensatory": "comp_off",
}


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.

    Misspellings and codes ("cssul lavee", "rejected CL") are folded first by
    the same nlp_service.fold_leave_typos that classified the query, so a type
    the router recognised is never dropped here."""
    text = nlp_service.fold_leave_typos(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()


# Tuned against the real configured set (Casual / Sick / Earned / Short) plus
# the misspellings seen live. 0.78 forgives a slipped, doubled or transposed
# letter ("casul", "cassual", "sik", "ernd", "shrt") while still rejecting a
# word that is simply a different type. The margin keeps a near-tie from being
# resolved by a hundredth of a point: two types this close means ask, not
# guess. Raise the cutoff if a company's types are unusually similar.
_LEAVE_TYPE_FUZZY_CUTOFF = 0.78
_LEAVE_TYPE_FUZZY_MARGIN = 0.08


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

    # ── Nothing matched exactly. Try again allowing for a misspelling. ──────
    #
    # Live bug: "casul leave" was sometimes accepted and sometimes refused with
    # "We don't have a 'casul' leave type here". The inconsistency was the LLM
    # -- extraction resolves the typo on some runs and not others -- and this
    # matcher, the deterministic safety net underneath it, had no tolerance at
    # all: casul, casaul, sik, ernd, shrt ALL returned None. So whether an
    # employee could apply depended on a coin flip.
    #
    # Matched against the COMPANY'S OWN configured list, never a generic
    # vocabulary, so this can still only ever return a type that really
    # exists. The cutoff is deliberately strict: the aim is to forgive a
    # slipped or doubled letter, not to guess. Confusable real types must stay
    # apart -- "sick" must never resolve to "short" -- so anything that comes
    # close to TWO different types is rejected as ambiguous and left to the
    # caller to ask about.
    best: list[tuple[float, str]] = []
    for entry in known:
        slug = entry.get("slug") or ""
        forms = {
            _normalize_leave_type_phrase(slug),
            _normalize_leave_type_phrase(slug).removesuffix(" leave").strip(),
            _normalize_leave_type_phrase(entry.get("name") or ""),
            _normalize_leave_type_phrase(entry.get("name") or "").removesuffix(" leave").strip(),
        }
        forms.discard("")
        score = max(
            (difflib.SequenceMatcher(None, normalized_input, f).ratio() for f in forms),
            default=0.0,
        )
        if score >= _LEAVE_TYPE_FUZZY_CUTOFF:
            best.append((score, slug))

    if not best:
        return None
    best.sort(reverse=True)
    if len(best) > 1 and best[0][0] - best[1][0] < _LEAVE_TYPE_FUZZY_MARGIN:
        logger.info("[Leave] %r is too close to call between %s — not guessing",
                    text, [s for _, s in best[:2]])
        return None
    logger.info("[Leave] fuzzy-matched %r -> %s (%.2f)", text, best[0][1], best[0][0])
    return best[0][1]


# 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",
}

# Live bug (2026-09-08): "cancel my peding leaves" answered "'Peding Leave' is
# not supported in this portal." The exact-match set above is the right idea,
# but a misspelt status word slips past it, and the generic "<word> leaves"
# extractor then hands the typo over as if it were the NAME of a leave type
# nobody configured. A status word and a type name are different kinds of
# thing; one being misspelt must not turn it into the other.
#
# Same 0.75 difflib cutoff (and the same reasoning) as
# _mentions_unconfigured_leave / _match_configured_leave_types — reused rather
# than re-tuned. Swept over the realistic typos ("peding", "pendig", "pendign",
# "penidng", "aproved", "approced", "rejcted", "rejeted", "canceld", "aplied",
# "appled", "declind", "acepted", "outstading", "upcomming": all caught) and,
# in the other direction, over every word in _UNCONFIGURED_LEAVE_WORDS plus the
# common type names (casual, sick, earned, short, medical, religious,
# maternity, paternity, bereavement, study, sabbatical, compensatory, marriage,
# menstrual, adoption): NONE scores above the cutoff against any status word,
# so a genuinely unsupported type is still reported as unsupported.
#
# Fuzzy matching is gated at 5 characters. The short entries above ("all",
# "new", "old", "past") still match exactly; letting difflib near tokens that
# short is what the rest of this file's typo helpers already refuse to do,
# because at 3-4 characters the scores stop separating a typo from an
# unrelated word.
_MIN_STATUS_WORD_TYPO_LEN = 5
# The literal, not an import of leave_eligibility_service's
# _CONFIGURED_TYPE_TYPO_CUTOFF: that module is only ever imported lazily from
# inside functions here (see _unsupported_leave_type_message_for_status), to
# keep the two modules free of an import cycle. Kept numerically identical on
# purpose — if that sweep is ever re-tuned, re-tune this with it.
_STATUS_WORD_TYPO_CUTOFF = 0.75


def _is_status_word(candidate: Optional[str]) -> bool:
    """True when the word sitting before "leave(s)" is a STATUS/qualifier
    ("pending", "approved", "applied") rather than a leave-type name —
    tolerating a misspelling, which the exact set alone did not."""
    if not candidate:
        return False
    word = candidate.lower()
    if word in _STATUS_WORD_CANDIDATES:
        return True
    if len(word) < _MIN_STATUS_WORD_TYPO_LEN:
        return False
    return bool(difflib.get_close_matches(
        word, _STATUS_WORD_CANDIDATES, n=1, cutoff=_STATUS_WORD_TYPO_CUTOFF))


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 not _is_status_word(found) 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 _is_status_word(named):
        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)

# A mid-application reply that is nothing but a leave-type name is answering
# the open question, whatever a classifier makes of it on its own.
_BARE_LEAVE_TYPE_REPLY_MAX_WORDS = 4


def _names_only_a_leave_type(query: str) -> bool:
    """True when `query` is just a leave type being named — "earned",
    "earned leave", "use earned leave" — and carries nothing else.

    Live report: after "you don't have enough Casual Leave, try another
    type", the employee answered "earned". fast_classify has no keyword for
    a bare type word (it returns no intent at all, confidence 0.0), so the
    turn fell through to the LLM, which labelled it leave_eligibility — a
    perfectly reasonable reading of the word ON ITS OWN, but not of a reply
    to a question that had just asked for a leave type. It was treated as an
    interruption and answered with an eligibility card, and the application
    the employee was in the middle of never advanced.

    Deliberately independent of whichever intent was detected: the existing
    guard beside this one keys off leave_policy specifically, and the exact
    same shape of reply gets labelled leave_eligibility just as easily. What
    makes it a continuation is the CONTENT — one known leave type, no
    question asked — not the label.

    Requires exactly one recognised type, so "earned or casual" (a question
    about a choice) doesn't qualify; excludes anything carrying a policy or
    eligibility question marker, so "am I eligible for earned leave" stays a
    genuine interruption; and caps the length, so a real question that merely
    mentions a type in passing can't be swallowed by this."""
    if _looks_like_leave_policy_question(query):
        return False
    if len(query.split()) > _BARE_LEAVE_TYPE_REPLY_MAX_WORDS:
        return False
    return len(_extract_leave_type_filters(query)) == 1


# 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"
    # Typos and near-forms of the same answers ("apporved", "canel", "cancel",
    # "apply", "appy") - the same readers the status branch itself now uses,
    # so a reply resolves exactly as it would have as the original query.
    status = _match_status_word(query)
    if status:
        return status
    if _APPLIED_WORD_RE.search(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+|nope|nah)\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)


# "I don't need the leave anymore, withdraw it" typed while an application is
# still being filled in: withdraw THAT draft. QA: it matched none of the
# patterns above, so it was answered with "What type of leave would you like
# to apply for?" again - twice. Kept OUT of _CANCEL_REQUEST_PATTERNS on
# purpose: that list doubles as the DECLINE vocabulary at the cancel-leave
# confirmation step, where "withdraw it" means the opposite (yes, cancel).
# Only ever consulted with a draft open.
_DRAFT_WITHDRAWAL_PATTERNS: list[re.Pattern] = [
    re.compile(r"\b(?:withdraw|retract|take\s+back|drop)\s+(?:it|this|that|the\s+(?:leave|request|application)|my\s+(?:request|application))\b",
               re.IGNORECASE),
    re.compile(r"\b(?:don'?t|do\s+not)\s+(?:need|want)\b[\w\s']{0,15}?\bleaves?\b(?:\s+any\s*more)?", re.IGNORECASE),
]


# The whole reply is a plain no, at the confirmation card - an unambiguous
# decline there, since the card asks a yes/no question. Anything more ("no,
# make it 3 days") is a correction and goes the normal way.
_BARE_CONFIRMATION_DECLINE_RE = re.compile(
    r"^\s*(?:no+|nope|nah|no\s+thanks?|no\s+thank\s+you|don'?t\s+submit(?:\s+it)?"
    r"|discard(?:\s+it)?|scrap\s+it|delete\s+it|throw\s+it\s+away)\s*[.!]*\s*$",
    re.IGNORECASE)

# The amend / keep / discard question's own three answers, whole message.
_AMEND_CHOICE_WORD_RE = re.compile(
    r"^\s*(amend|keep|discard)(?:\s+(?:it|this|that|the\s+(?:original|request|change)))?\s*[.!]*\s*$",
    re.IGNORECASE)

# "change due to fever", "change the reason to fever", "update reason as
# family function", "reason: fever", "the reason should be fever" - a new
# REASON for the request on the confirmation card. A change that names no
# reason ("change the date to 30th") is not this and is left to extraction.
_REASON_CHANGE_RES = [
    re.compile(r"^\s*(?:please\s+|pls\s+)?(?:change|update|edit|modify|set|make|correct)\s+(?:it\s+|the\s+|my\s+)?"
               r"(?:reason\s+)?(?:to\s+|as\s+|into\s+)?(?:due\s+to|because\s+of|because|coz|cause)\s+(?P<r>.+?)\s*[.!]*\s*$",
               re.IGNORECASE),
    re.compile(r"^\s*(?:please\s+|pls\s+)?(?:change|update|edit|modify|set|make|correct)\s+(?:the\s+|my\s+)?reason\s+"
               r"(?:to|as|into|with|:|-)?\s*(?:due\s+to\s+|because\s+of\s+)?(?P<r>.+?)\s*[.!]*\s*$",
               re.IGNORECASE),
    # "reason should be CHANGED TO bank work" -- the copula is followed by a
    # change verb, and the wrapper used to be captured as part of the reason
    # ("Changed to bANk wOrK" went on the card). Optional, so "reason is bank
    # work" still works.
    re.compile(r"^\s*(?:the\s+|my\s+)?(?:new\s+)?reason\s*(?:is|should\s+be|will\s+be|=|:|-)\s*"
               r"(?:(?:changed?|updated?|modified?|set|corrected?)\s+(?:it\s+)?(?:to|as|into)\s+)?"
               r"(?P<r>.+?)\s*[.!]*\s*$",
               re.IGNORECASE),
]


_BARE_CONFIRMATION_AFFIRM_RE = re.compile(
    r"^\s*(?:y|yes+|yep|yeah|ya|ok(?:ay)?|k|sure|confirm(?:ed)?|submit(?:\s+it)?|go\s+ahead|proceed|do\s+it)\s*[.!]*\s*$",
    re.IGNORECASE)

# The apply card's confirmation question, in each of its forms.
_ASKED_TO_CONFIRM_RE = re.compile(
    r"shall i submit (?:this|it)|waiting for your confirmation|reply \**yes\** to submit", re.IGNORECASE)


def _last_reply_asked_to_confirm(context) -> bool:
    """The assistant's previous message put a leave request up for confirmation."""
    for msg in reversed(context or []):
        if isinstance(msg, dict) and msg.get("role") == "assistant":
            return bool(_ASKED_TO_CONFIRM_RE.search(str(msg.get("content") or "")))
    return False

# The words the confirmation questions themselves offer. Matching these
# without a model call is not the thing the banner above forbids: by the time
# one of these arrives Helix has already ASKED, and the employee is answering
# with the exact word it put in front of them -- the typed equivalent of
# pressing the button. What must never be deterministic is deciding that an
# unprompted message MEANS one of these.
#
# It also keeps the most important action in the flow working when the model
# is not. classify_choice fails closed to "I couldn't tell", which is right
# for a genuinely odd reply and very wrong for someone typing "submit" at a
# request that is ready to go -- without this they could not submit at all.
_ANSWER_SUBMIT_RE = re.compile(
    r"^\s*(?:yes|yeah|yep|ya|ok(?:ay)?|sure)?[\s,]*(?:please\s+)?"
    r"(?:submit|send)(?:\s+it)?(?:\s+please)?\s*[.!]*\s*$",
    re.IGNORECASE)
_ANSWER_NOT_YET_RE = re.compile(
    r"^\s*(?:not\s+yet|wait|hold\s+on|later|not\s+now)\s*[.!]*\s*$", re.IGNORECASE)
_ANSWER_DISCARD_RE = re.compile(
    r"^\s*(?:discard(?:\s+it)?|scrap\s+it|delete\s+it|throw\s+it\s+away)\s*[.!]*\s*$",
    re.IGNORECASE)
_ANSWER_THIS_ONE_RE = re.compile(
    r"^\s*(?:this\s+(?:one|request|submission|application)|the\s+new\s+one)\s*[.!]*\s*$",
    re.IGNORECASE)
_ANSWER_KEEP_RE = re.compile(
    r"^\s*(?:keep(?:\s+it)?|leave\s+it(?:\s+alone)?|carry\s+on(?:\s+with\s+it)?)\s*[.!]*\s*$",
    re.IGNORECASE)
_ANSWER_OTHER_LEAVE_RE = re.compile(
    r"^\s*(?:(?:cancel\s+)?an(?:other)?\s+(?:leave|one)|a\s+different\s+(?:one|leave)|"
    r"an\s+existing\s+leave|the\s+other\s+(?:one|leave))\s*[.!]*\s*$", re.IGNORECASE)


def is_bare_confirmation_answer(query: str) -> bool:
    """A whole-message yes or no - the answer to the confirmation card,
    never a new topic ("no thanks" is not small talk there)."""
    return bool(_BARE_CONFIRMATION_DECLINE_RE.match(query or "")
                or _BARE_CONFIRMATION_AFFIRM_RE.match(query or ""))


def _reason_change_from_reply(query: str) -> Optional[str]:
    for pattern in _REASON_CHANGE_RES:
        m = pattern.match(query or "")
        if m and m.group("r").strip():
            reason = m.group("r").strip().strip("\"'")
            return reason[:1].upper() + reason[1:] if reason else None
    return None


# "not cl", "no casual", "instead of sick", "except EL" - a type the reply
# REFUSES. Only the word(s) right after the marker are read.
_REFUSED_TYPE_RE = re.compile(
    r"\b(?:not|no|don'?t\s+want|instead\s+of|rather\s+than|except|skip)\s+(?:the\s+|a\s+|my\s+)?"
    r"([a-z]+(?:\s+leave)?)", re.IGNORECASE)


def _resolve_type_choice(query: str, offered: list) -> tuple:
    """(chosen_slug, None) or (None, options_still_open) for a reply to "I can
    process one leave request at a time. Would you like to start with X?",
    where X is offered[0]."""
    refused = set()
    for m in _REFUSED_TYPE_RE.finditer(query or ""):
        refused.update(_extract_leave_type_filters(m.group(1)))
    named = [s for s in _extract_leave_type_filters(query) if s not in refused]
    if len(named) == 1:
        return named[0], None
    if len(named) > 1:
        return None, [s for s in offered if s in named] or offered
    # No type named: a yes takes the offer, a no takes whatever is left.
    if _BARE_CONFIRMATION_AFFIRM_RE.match(query or ""):
        return offered[0], None
    remaining = [s for s in offered if s not in refused]
    if _BARE_CONFIRMATION_DECLINE_RE.match(query or "") or refused:
        remaining = [s for s in remaining if s != offered[0]] or remaining
        if len(remaining) == 1:
            return remaining[0], None
        return None, remaining
    return None, offered


def is_type_choice_reply(query: str) -> bool:
    """A reply the one-at-a-time question itself can resolve: yes, no, or a
    leave type."""
    return bool(is_bare_confirmation_answer(query) or _extract_leave_type_filters(query)
                or _REFUSED_TYPE_RE.search(query or ""))


def is_confirmation_card_answer(query: str) -> bool:
    """A reply the confirmation card itself handles: yes, no, or a new reason."""
    return is_bare_confirmation_answer(query) or _reason_change_from_reply(query) is not None


def is_draft_withdrawal(query: str) -> bool:
    return any(p.search(query or "") for p in _DRAFT_WITHDRAWAL_PATTERNS)


# "discard" / "Discard it" — the answer to "you have a leave application in
# progress ... carry on with it, or discard it?" (and its "Discard it" chip).
# Live: neither matched anything above, so fast_classify's cancel keyword sent
# the reply to the cancel_leave SEARCH flow, which listed the employee's
# pending leaves; the draft stayed open and the same question came back on the
# next turn. A bare "discard" once fell to the chat model instead, which
# answered "I've cleared the pending short-leave request" without clearing it.
# Whole message only, and only ever consulted with a draft open — the same
# reasoning as _DRAFT_WITHDRAWAL_PATTERNS. Kept out of _CANCEL_REQUEST_PATTERNS
# for the same reason too: that list is also the cancel-leave DECLINE vocabulary.
_DRAFT_DISCARD_RE = re.compile(
    r"^\s*(?:(?:yes|ok(?:ay)?|sure)\s*,?\s*)?(?:please\s+|pls\s+|just\s+)?"
    r"(?:discard|scrap|delete|remove|clear|bin|throw\s+away)"
    r"(?:\s+(?:it|this|that|(?:the|this|my)\s+(?:draft|application|request|form|leave(?:\s+(?:application|request))?)))?"
    r"(?:\s*(?:,|and)\s+.*)?\s*[.!]*\s*$",
    re.IGNORECASE)


def is_draft_discard(query: str) -> bool:
    return bool(_DRAFT_DISCARD_RE.match(nlp_service.fold_smart_punctuation(query or "")))


# ── "Which 'cancel' is this?" — one deterministic answer, shared ──────────────
# The word "cancel" carries two completely different intents in this product,
# and they were getting mixed:
#
#   apply_leave  — "discard the application I'm in the middle of writing"
#   cancel_leave — "withdraw a request I already submitted"
#
# Which one a message means is decided HERE, once, so classify_node (routing)
# and the cancel/apply branches below (execution) can never disagree about it.
# Routing used to guess from fast_classify's keyword hit alone, which sees only
# the word "cancel" and has no idea a draft is open — so a bare "cancel" typed
# mid-application (or the apply card's own Cancel button) was confidently sent
# into the cancel_leave SEARCH flow and answered with "which submitted request
# would you like to cancel?", leaving the draft the employee was actually
# trying to abandon still open behind it.
#
# The rule (2026-09-08 product direction): a "cancel" only reaches the
# cancel_leave flow when it names something that CANNOT be the draft on screen —
#   * a reference number         "cancel LR-2041", "cancel leave 78"
#   * a plural/collective object "cancel my leaves", "cancel all my leave"
#   * a status only a submitted request can carry  "cancel my pending leave"
# Everything else — a bare "cancel", "cancel it", "cancel this leave", "never
# mind", "forget it" — means the DRAFT, because that is what the employee is
# looking at. Deliberately narrow: a false positive here abandons a
# half-finished application to go hunting for a submitted one, which is the
# exact bug this exists to stop.
_SUBMITTED_LEAVE_TARGET_PATTERNS: list[re.Pattern] = [
    # A draft is exactly ONE request, so a plural object can only mean
    # already-submitted ones.
    re.compile(r"\b(cancel|withdraw|revoke)\b[\w\s']{0,25}?\bleaves\b", re.IGNORECASE),
    re.compile(r"\b(cancel|withdraw|revoke)\b[\w\s']{0,25}?\b(requests|applications)\b", re.IGNORECASE),
    # "all"/"every"/"each" — collective, same reasoning. Kept tighter (15 chars)
    # than the plural patterns since "all" is a common filler word.
    re.compile(r"\b(cancel|withdraw|revoke)\b[\w\s']{0,15}?\b(all|every|each)\b", re.IGNORECASE),
    # A status a draft has never had — it was never submitted, so it cannot be
    # pending/approved/applied/submitted.
    re.compile(r"\b(cancel|withdraw|revoke)\b[\w\s']{0,25}?\b(pending|approved|applied|submitted)\b", re.IGNORECASE),
]


def cancel_phrase_targets_submitted_request(query: str) -> bool:
    """True when a 'cancel' message unambiguously names an ALREADY-SUBMITTED
    leave request rather than an in-progress draft — see the comment above.
    Purely deterministic (no LLM, no conversation state), so routing and
    execution always reach the same verdict for the same text."""
    if _extract_request_id(query):
        return True
    return any(p.search(query) for p in _SUBMITTED_LEAVE_TARGET_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)

# An affirmative that merely RESTATES the action confirms it; one that carries
# a CHANGE does not. "Yes, cancel it" and "yes Cancel LR-32" are the same
# instruction said twice. "Yes but change the dates" is a different one.
#
# These used to be \b(confirm|proceed)\b and ^\s*(yes|...)\b -- a leading or
# embedded affirmative was enough on its own -- so at the cancellation card:
#
#   "yes but change the dates"           -> cancelled the leave
#   "yes but only the second one"        -> cancelled, possibly the wrong one
#   "should I confirm my leave tomorrow" -> a QUESTION cancelled a leave
#
# Cancelling a submitted leave cannot be undone from here. Anchoring the lead
# is what stops an affirmative buried mid-sentence counting as one; the change
# markers are what stop a real affirmative dragging an unrelated instruction
# through with it.
_CANCEL_CONFIRM_LEAD_RE = re.compile(
    r"^\s*(?:yes|yeah|yep|ya|sure|ok(?:ay)?|confirm(?:ed)?|proceed|"
    r"go\s+ahead|do\s+it)\b",
    re.IGNORECASE)

# A second instruction, a correction, or a question -- never part of a plain
# "yes, do the thing you just described".
_CANCEL_CONFIRM_CARRIES_A_CHANGE_RE = re.compile(
    r"\b(?:but|however|though|instead|rather|change|modify|edit|update|amend|"
    r"only|also|as\s+well|different|another|other\s+one|first|before|after|"
    r"wait|hold\s+on)\b|\?",
    re.IGNORECASE)


def _is_confirming(query: str) -> bool:
    q = query or ""
    return bool(_CANCEL_CONFIRM_LEAD_RE.match(q)
                and not _CANCEL_CONFIRM_CARRIES_A_CHANGE_RE.search(q))


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."""
    # A mistyped button text is a person typing, not a press, so it is read as
    # unclear and put back to them rather than acted on. "kepp request" almost
    # certainly means keep it, but almost is not the standard for cancelling
    # someone's leave -- and the two buttons sit next to each other, so a typo
    # close to one is not far from the other.
    if _resembles_cancel_card_button(query):
        return "ambiguous"
    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)

    # A "yes" to "Shall I submit this request?" with no draft left behind it -
    # expired (SLOT_TTL), or lost with Redis on another worker. It used to
    # start a brand-new application ("What type of leave would you like to
    # apply for?"), which reads as though the request was taken and the
    # assistant then forgot it (negative run, 28 Oct, #33 / #63a). Say what
    # happened instead; nothing is submitted.
    if (not existing_slots and _BARE_CONFIRMATION_AFFIRM_RE.match(query or "")
            and _last_reply_asked_to_confirm(state.get("context"))):
        return _finish(
            "There's no leave request waiting for confirmation any more — it may have "
            "expired, so nothing was submitted. Tell me the leave type and dates and "
            "I'll set it up again.",
            intent="apply_leave",
        )

    # 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 ""
        # A question, not a statement. "just reply to continue it" told the
        # employee the draft existed and then left it to them to notice; they
        # answered the thing they asked about and the half-filled application
        # sat there unmentioned again next turn. Asking forces the draft to be
        # dealt with one way or the other.
        resume_reminder = (f"\n\nYou still have a leave application in progress{draft_desc}. "
                           f"Would you like to carry on with it, or discard it?")

    # ── Balance branch (AC#2) ─────────────────────────────────────────────────
    if state["intent"] == "leave_balance":
        # A named person's balance ("Show me Rahul's leave balance"). Without
        # this the branch answered with the CALLER'S OWN balance under the
        # heading "Here's your current leave balance" - the wrong person's
        # numbers, presented as an answer. Everyone but a manager/HR user is
        # refused here, before any erp-api call; for those allowed, erp-api's
        # own scope check on employee_name stays authoritative.
        # The TEAM's balance ("team leave balance", "my team's casual leave
        # balance"). There is no team-balance lookup, and only HR may see
        # anyone else's balance — so it is refused, for every role. Live it was
        # answered with the team's PENDING LEAVE REQUESTS instead.
        if nlp_service.is_team_balance_request(query):
            return _finish(OTHERS_BALANCE_REFUSAL, intent=access_notice.RESTRICTED_INTENT,
                           extra_data=access_notice.refuse(writer, "team_leave_balance",
                                                           OTHERS_BALANCE_REFUSAL, other_employee=True))
        balance_target = nlp_service.extract_other_balance_target(query)
        if balance_target and employee_name and balance_target.lower() == str(employee_name).strip().lower():
            balance_target = None  # they named themselves
        if balance_target:
            # Only HR may see another employee's balance — a manager included
            # (permission_service.may_view_others_leave_balance). Before, a
            # manager's "show me Rahul's leave balance" fetched and showed it.
            _role_word = balance_target.lower() in {"manager", "boss", "hr", "lead", "team lead", "supervisor"}
            if _role_word or not permission_service.may_view_others_leave_balance(
                    state, context_data=context_result["body"].get("data", {})):
                return _finish(OTHERS_BALANCE_REFUSAL, intent=access_notice.RESTRICTED_INTENT,
                               extra_data=access_notice.refuse(writer, "leave_balance",
                                                               OTHERS_BALANCE_REFUSAL,
                                                               other_employee=True))
            writer({"type": "fetching_balance", "message": f"Checking {balance_target}'s leave balance..."})
            try:
                result = await erp_client.get_leave_balance(
                    bearer_token, company_id=company_id, conversation_id=conversation_id,
                    employee_name=balance_target)
            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")
            raw_body = result["body"]
            if not raw_body.get("success", False):
                return _finish(raw_body.get("message") or f"I couldn't fetch {balance_target}'s leave balance right now.",
                               intent="leave_balance")
            body = raw_body.get("data", {})
            if not body.get("leave_quota"):
                return _finish(f"I couldn't find any leave balance information for {balance_target}.",
                               intent="leave_balance")
            full_body = {**body, "employee_name": balance_target}
            writer({"type": "leave_balance", "data": full_body})
            return _finish(f"Here's {balance_target}'s current leave balance.", intent="leave_balance",
                           extra_data=full_body)

        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)
        # A bare day of the month ("for 21st", "on the 25th") is that day of
        # the CURRENT month and year - resolved here, deterministically and
        # before the LLM fallback below, so the list and the status-question
        # paths both search that one date. QA: "is my leave for 21st
        # approved" searched every leave on record.
        searched_date_label = None
        if date_from is None and date_to is None:
            asked_day = _bare_day_of_month(query)
            if asked_day:
                today = _today_in_app_timezone()
                try:
                    asked_date = today.replace(day=asked_day)
                except ValueError:
                    return _finish(
                        f"{today.strftime('%B %Y')} doesn't have a {asked_day}"
                        f"{_ordinal_suffix(asked_day)} — could you check the date?{resume_reminder}",
                        intent="leave_status")
                date_from = date_to = asked_date.isoformat()
                searched_date_label = f"{asked_date.day} {asked_date.strftime('%b %Y')}"
        # One explicit calendar date ("on 2 nov", "8th september") - resolved
        # here, deterministically, the way the apply flow already does. It was
        # left to the LLM fallback below, which only runs when classify_node
        # flagged a date: "my leave on 2 nov got approved right?" searched
        # every approved leave on record and never mentioned that the 2 Nov
        # one is still pending (negative run, 28 Oct, #56). Not for a range
        # ("between 1st oct and 5th oct"), which would collapse to its first
        # day - that stays with the fallback.
        if (date_from is None and date_to is None
                and not re.search(r"\b(?:between|from|to|till|until|through)\b", query, re.IGNORECASE)):
            asked_iso = _resolve_absolute_date_mention(query, _today_in_app_timezone())
            if asked_iso:
                asked_date = date.fromisoformat(asked_iso)
                date_from = date_to = asked_iso
                searched_date_label = f"{asked_date.day} {asked_date.strftime('%b %Y')}"
        # 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).
        # A named DATE is already a search: "show my leaves for 21st" means
        # every leave on that date, whatever its status - not a menu.
        if searched_date_label and not status_filter and not is_status_question:
            is_all_request = True
        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")

            leaves_on_record = result["body"].get("data", {}).get("leaves", [])
            all_leaves = leaves_on_record
            searched_label = searched_date_label or (
                (date_from if date_from == date_to else f"{date_from} to {date_to}")
                if date_from and date_to else None)
            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]

            # The user named a date or a leave type and nothing matches: say
            # so plainly, then offer what IS on record rather than a dead end.
            if not cards and (searched_label or leave_type_filters) and leaves_on_record:
                what = " ".join(p for p in (
                    ", ".join(s.replace("_", " ").title() for s in leave_type_filters) if leave_type_filters else None,
                    f"for {searched_label}" if searched_label else None,
                ) if p)
                offered = [_build_applied_leave_card(lv) for lv in leaves_on_record]
                status_data = {
                    "leaves": offered, "filter": None, "total_count": len(offered),
                    "display_limit": len(offered), "has_more": False,
                    "suggestions": list(_LEAVE_STATUS_FOLLOWUPS),
                }
                writer({"type": "leave_status", "data": status_data})
                return _finish(
                    f"I couldn't find any leave request {what}. Here are the leave requests on "
                    f"record — is it one of these?{resume_reminder}",
                    intent="leave_status", extra_data=status_data)

            # "Has my leave been approved?" with nothing narrowing it and
            # SEVERAL leaves of that status: answer the question - how many
            # are approved, and where the rest stand - instead of "which one
            # did you mean?" over every leave on record. QA: 24 leaves in one
            # "which one are you asking about?" sentence, for a yes/no
            # question. Exactly one match keeps the direct answer below, and a
            # "why/reason" question keeps "which one?" - it asks about ONE leave.
            question_status = _match_status_word(query) if len(cards) > 1 else None
            if (question_status and not (date_from or leave_type_filters)
                    and not re.search(r"\b(?:why|reason)\b", query, re.IGNORECASE)):
                matching = [c for c in cards if c.get("status_name") == question_status]
                if len(matching) > 1:
                    others = Counter(c.get("status_name") or "unknown" for c in cards
                                     if c.get("status_name") != question_status)
                    others_text = ", ".join(f"{n} {s}" for s, n in others.most_common())
                    msg = f"{len(matching)} of your {len(cards)} leave requests are {question_status}"
                    msg += f" ({others_text})." if others_text else "."
                    status_data = {
                        "leaves": matching, "filter": question_status, "total_count": len(matching),
                        "display_limit": len(matching), "has_more": False,
                        "suggestions": list(_LEAVE_STATUS_FOLLOWUPS),
                    }
                    writer({"type": "leave_status", "data": status_data})
                    return _finish(f"{msg}{resume_reminder}", intent="leave_status", extra_data=status_data)
            # 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)
                # The candidates go out as STRUCTURED data, the same way the
                # cancel flow's "which one?" does (see the
                # leave_cancellation_selection emission further down). These
                # are already _build_applied_leave_card output — full cards
                # carrying date_label, status_label, reference, approver and
                # reason — and were being flattened into one prose sentence
                # here: "Earned Leave (2026-08-12 to 2026-08-12) or Comp Off
                # (2026-07-30 to 2026-07-30) or ...". Identical question, same
                # data already in hand, two different presentations depending
                # on which flow asked it.
                writer({"type": "leave_cancellation_selection", "data": {"requests": cards}})
                msg = ("You have more than one leave request on record — which one did you "
                       "mean? You can tell me by leave type, date, number, or reference.")
                return _finish(f"{msg}{resume_reminder}", intent="leave_status",
                               extra_data={"requests": cards})
            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", [])
        # The STATUS filter is re-applied here, not just sent to erp-api.
        #
        # The leave_type and date filters below have always been enforced on
        # the rows; status was the one that was only ever *asked for*. When
        # erp-api answered a leave_status=approved request with unfiltered
        # rows, this service rendered pending and rejected leaves underneath
        # the header "Your approved leave requests" - a header that asserts
        # something false about the rows beneath it, which is worse than
        # showing nothing. The list and its label now cannot disagree.
        #
        # Keyed on api_status rather than status_filter so the implicit
        # default ("pending", when the query named no status at all) is
        # covered too. "all" is the one value that means "do not narrow".
        if api_status != "all":
            all_leaves = [lv for lv in all_leaves
                          if str(lv.get("status_name") or "").strip().lower() == api_status]
        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.
            # A named type must be in the reply: "show my cancelled CL" said
            # "You don't have any cancelled leave requests" to someone whose
            # history has cancelled SICK leaves - true of casual, false as said.
            type_label = " / ".join(s.replace("_", " ").title() for s in leave_type_filters)
            if type_label:
                msg = f"You don't have any {filter_label}{type_label} requests on record{range_label}."
            elif 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":

        # A card button pressed after the card is gone (TTL expired, the state
        # was lost, or an old card scrolled back to). classify_node now sends
        # every button press here; without an open card there is nothing to
        # keep or confirm, so say so instead of treating "Keep Request" as a
        # search for a leave to cancel. Same wording the apply branch uses.
        if _is_cancel_card_button(query) and not leave_cancel_state.get_state(company_id, conversation_id):
            return _finish(
                "That cancellation request is no longer open, so nothing was changed. "
                "Just tell me which leave you'd like to cancel and I'll pull it up again."
                f"{resume_reminder}",
                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=LLM_TASK_MAX_TOKENS, 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.
            resolved_date = (
                _resolve_weekday_date(q) or _resolve_relative_day_date(q)
                or _resolve_absolute_date_mention(q) or _resolve_numeric_date_mention(q)
            )
            # The resolvers OVERRIDE the model's date rather than only filling
            # in for it. The comment above has always claimed this branch
            # "never depend[s] on the model's own (previously proven
            # unreliable) date arithmetic", but the old `if not
            # extracted.get("date")` guard meant the resolvers ran only when
            # the model returned nothing — i.e. the protection covered an LLM
            # outage but not the case it was actually written for: a model
            # that answers confidently and wrongly.
            #
            # Live bug: "cancel my sunday leave" — gpt-4o-mini resolved
            # "sunday" to 2026-09-11, a FRIDAY (3/3 runs), and returned the
            # identical date for "cancel my friday leave", so it was not doing
            # weekday arithmetic at all. That date genuinely matched a pending
            # Friday request, so matching found exactly one candidate and
            # offered to cancel the wrong leave — under a card still labelled
            # "Sunday", because the label echoes the employee's own word.
            # Nothing downstream could catch it: a wrong-but-valid date looks
            # identical to a right one. _resolve_weekday_date returns the
            # correct 2026-09-13 for the same query.
            #
            # Only for a SINGLE date. An explicit two-date span from the model
            # ("from 25 Aug to 29 Aug") is left alone — these resolvers return
            # one date, so overwriting `date` there would silently re-anchor
            # the span against a `date_to` chosen for a different start.
            llm_gave_span = bool(
                extracted.get("date") and extracted.get("date_to")
                and extracted["date_to"] != extracted["date"]
            )
            if resolved_date and not llm_gave_span:
                if extracted.get("date") and extracted["date"] != resolved_date:
                    logger.info(
                        "[Graph] cancel-date override: model said %s, deterministic "
                        "resolver says %s for %r",
                        extracted["date"], resolved_date, q[:80],
                    )
                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")),
                # Same one-key rule the history cards follow (see
                # _decision_reason): the frontend reads rejection_reason for
                # the decision-side note, so this card carries the
                # cancellation note there too rather than only under
                # cancel_reason — otherwise the reason the employee just
                # typed shows on the Reason tab of every OTHER view but not
                # the success card that immediately follows it. Falls back to
                # the reason we sent when erp-api doesn't echo it back.
                "rejection_reason": _decision_reason(cancel_data) or cancel_reason,
                "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)

            # A specific match (fresh turn, selection-turn resolution, or a
            # resumed-after-decline reply) can land on a request that's
            # already cancelled/rejected — this layer already knows that
            # from the same fetch that built the candidate, so there's
            # nothing to preview or confirm. No erp-api round trip needed.
            if selected.get("status_name") in ("cancelled", "rejected"):
                leave_cancel_state.clear_state(company_id, conversation_id)
                card, message = _already_decided_cancel_card(selected)
                writer({"type": "leave_failure", "data": card})
                spoken = f"{message} {_ALREADY_DECIDED_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) ─────────────────────────
        # "okay, cancel it" following a duplicate-leave notice — the request
        # that notice named is exactly what "it" refers to, so go straight to
        # its confirmation card rather than re-asking which leave they mean.
        #
        # Deliberately a PREVIEW, never an immediate cancellation: "cancel it"
        # is a two-word reply and cancelling a submitted leave cannot be
        # undone from here, so it goes through the same Confirm/Keep card
        # every other cancel path uses.
        if cancel_state and cancel_state.get("step") == "duplicate_offer":
            duplicate_selected = cancel_state.get("selected")
            if duplicate_selected:
                return await _preview_cancel_request(duplicate_selected)
            # Nothing usable stored — fall through to normal matching rather
            # than guessing which request was meant.
            leave_cancel_state.clear_state(company_id, conversation_id)
            cancel_state = None

        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).
            # A plural/collective ask ("cancel my all leaves", "cancel all my
            # leave") counts as a new request too, even though it names no
            # leave_type/date/reference for the check above to see. Live bug:
            # asked at this confirmation prompt, its bare "cancel" fell into
            # _decide_cancel_confirmation's weak-decline fallback and answered
            # "Leave Request Kept" — reading the employee's request to cancel
            # MORE leaves as a decision to cancel none. It cannot be an answer
            # to "would you like to cancel THIS one?" either way: this prompt
            # is about a single, already-chosen request, so a plural object
            # can only mean "show me the others".
            names_new_criterion = bool(
                extracted.get("leave_type") or extracted.get("date")
                or extracted.get("request_id") or _extract_request_id(query)
                or cancel_phrase_targets_submitted_request(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)
            # Same plural/collective allowance as the confirmation turn above:
            # "cancel all my leaves" after a decline asks for the whole list
            # back, not for the one just-declined request to be re-offered.
            names_new_criterion = bool(
                extracted.get("leave_type") or extracted.get("date")
                or extracted.get("request_id") or _extract_request_id(query)
                or cancel_phrase_targets_submitted_request(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, regardless of its current
        # status, no client-side pending/approved pre-check here — a
        # specific date/ID/type match is always handed to
        # _preview_cancel_request. What THAT function does with an
        # already-cancelled/rejected match changed 2026-09-03 (live bug
        # report: repeatedly confirming an already-cancelled request kept
        # re-showing the preview, reading as though each confirm "worked"):
        # it now short-circuits straight to the "already cancelled/rejected"
        # message using the status this fetch already knows, instead of
        # rendering a preview/confirm screen for something erp-api was
        # always going to refuse. erp-api's own /leave/cancel remains the
        # authority for every OTHER eligibility question (ownership, lock
        # state, policy) that this layer can't know locally.
        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 routed to
        # _preview_cancel_request, which now short-circuits it to the
        # "already cancelled/rejected" message rather than a preview. 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

        # Nothing left to offer. Note this is `not matches` ALONE — it used to
        # be `not matches and not lead_msg`, which let the two lead_msg paths
        # above ("couldn't find a request matching that" / "that request's
        # already been decided") fall through to the selection card below with
        # an EMPTY candidate list whenever their `matches = cancellable_cards`
        # fallback was itself empty. Live bug: the employee had no pending or
        # approved requests at all, and got a "Cancel Leave Request" card with
        # no options in it, plus an awaiting_selection state parked in Redis
        # that no reply could ever resolve. The lead_msg is still spoken — it
        # explains WHY the search came up empty — it just no longer renders a
        # picker with nothing to pick.
        if not matches:
            return _finish(f"{lead_msg}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 ──────────────────────────────────────────────────────────
    # An unanswered cancel-leave question is abandoned once the employee is
    # applying instead. Left alive, it outranks the apply draft in
    # classify_node for every yes/no/cancel reply: QA saw the apply card's
    # Cancel button open the "Confirm Cancellation / Keep Request" card, and
    # "Yes, please submit it." to the APPLY card was routed to the cancel flow,
    # where a yes confirms cancelling a SUBMITTED leave. Cleared here so the
    # question on screen - this flow's - is the only one a reply can answer.
    # Same for a manager card left unanswered earlier (an approve/reject card,
    # or "which employee?"). classify_node hands a bare "cancel" / "yes" to
    # those BEFORE falling back, so QA's "cancel" on the apply card opened a
    # team member's leave-request card ("Leave Request — ABC Testing").
    _clear_abandoned_questions(company_id, conversation_id)

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

    # ═══════════════════════════════════════════════════════════════════════
    # HOW THIS CARD IS ALLOWED TO BE RESOLVED. Keep these three tiers.
    #
    #  1. A BUTTON the employee pressed -- the apply card sends "yes submit
    #     it" / "cancel", the cancellation card sends "confirm cancellation" /
    #     "keep request". A press is already an unambiguous answer. Act on it.
    #     Never ask a button to confirm itself.
    #
    #  2. A TYPED reply that is a whole-message yes or no and NOTHING ELSE
    #     ("yes", "ok", "no", "cancel"). Also unambiguous. Act on it.
    #     _BARE_CONFIRMATION_AFFIRM_RE / _BARE_CONFIRMATION_DECLINE_RE are
    #     anchored for exactly this reason.
    #
    #  3. ANYTHING ELSE -- and this is the load-bearing part. A yes or no with
    #     more attached is not agreement to the rest of the sentence: "yes but
    #     only half day" once submitted a FULL day, and "yes i think so but
    #     let me check my balance first" submitted the request the employee
    #     had just asked to hold. Both reached the approver and cannot be
    #     taken back. These go to classify_confirmation_reply, which can tell
    #     a go-ahead from an amendment, a question or a hesitation, and the
    #     card stays open until one of tiers 1-2 resolves it.
    #
    # So: do NOT widen tier 2 into "contains a yes somewhere" (that is bug 3
    # above), and do NOT narrow tiers 1-2 into asking anyway (a button that
    # asks you to confirm the button is the bug this comment replaced).
    #
    # Enforced by tests/test_confirmation_gate_is_load_bearing.py.
    # ═══════════════════════════════════════════════════════════════════════

    # 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.
    # A cancel-card button press is excluded even though "Keep Request"
    # legitimately reads as a decline: it is an answer to the CANCEL card,
    # never an instruction to discard this draft. classify_node now keeps
    # those replies out of the apply flow entirely while that card is still
    # awaiting an answer (see its cancel_question_pending guard); this is the
    # second line of defence for the case where the cancel state has already
    # expired, so a late button press can still never destroy a draft and
    # report the wrong outcome for it.
    # A listing request ("Show my cancel leave") is never a discard, same
    # rule as classify_node's is_apply_discard_reply.
    # Nor while the amend / keep / discard question is outstanding: the reply
    # belongs to it, and "keep it" - one of its own offered answers - reads
    # as a decline here and threw the draft away.
    if (existing_slots and not _is_cancel_card_button(query)
            and not existing_slots.get("_pending_amendment")
            and (_is_declining_or_cancelling(query) or is_draft_withdrawal(query)
                 or is_draft_discard(query))
            and not nlp_service.is_leave_listing_request(query)):
        leave_slot_service.clear_slots(company_id, conversation_id)
        if is_draft_withdrawal(query):
            # Their own word back to them: they asked to WITHDRAW it.
            return _finish(
                "No problem — I've withdrawn the current leave request. Nothing "
                "was submitted, and no existing leave was cancelled. Let me know "
                "if you'd like to start a new one."
            )
        return _finish(
            "No problem — I've discarded the leave application we were "
            "filling in. Nothing was submitted, and no existing leave was "
            "cancelled. Let me know if you'd like to start a new one."
        )

    # A cancel-card button that arrives with no cancel state left to answer
    # (TTL expired, or a stale card the employee scrolled back to) — say so
    # plainly instead of falling through to slot extraction, which finds
    # nothing in "Keep Request" and re-asks for whatever the draft is still
    # missing, reading as though the button did nothing at all.
    if _is_cancel_card_button(query) and not leave_cancel_state.get_state(company_id, conversation_id):
        return _finish(
            "That cancellation request is no longer open, so nothing was changed. "
            "Just tell me which leave you'd like to cancel and I'll pull it up again."
            f"{resume_reminder}",
            intent="cancel_leave",
        )

    # A type Helix cannot file, named in THIS message ("apply for LOP next
    # week", "comp off tomorrow"): refuse at once, before extraction and before
    # any date handling. QA: "next week" was answered with the date picker
    # first, because the type check further down only runs once the dates are
    # settled - so the employee picked dates for a leave that could not be
    # filed. A message that also names a fileable type is left alone.
    _named_here = _extract_leave_type_filters(query)
    _unfileable = [s for s in _named_here if s not in HELIX_APPLICABLE_LEAVE_TYPES]
    if _unfileable and not any(s in HELIX_APPLICABLE_LEAVE_TYPES for s in _named_here):
        slots["leave_type"] = None
        slots.pop("_type_choice", None)
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish(
            f"{_display_leave_type_name(_unfileable[0])} can't be applied through Helix right now. "
            f"You can apply for {_applicable_leave_types_sentence()} here — which one would you like?"
        )

    # ── The two replies to the confirmation card that must never depend on an
    # LLM verdict. QA: "change due to fever" at the card was answered "I
    # couldn't read that as an answer", and a plain "no" after it got the same
    # re-ask instead of discarding the request - the confirmation classifier
    # was never even shown the reason, and a failed call reads as "other".
    #
    # Skipped while an amendment choice is outstanding: that question was
    # asked more recently and offers three answers, so a reply here belongs
    # to it. Running this first would answer the wrong question and, for a
    # reason change, leave _pending_amendment behind in the slots to fire
    # again on some later turn.
    amend_note = ""
    explicit_reason_change = None
    if (slots.get("step") == "awaiting_confirmation"
            and not slots.get("_pending_amendment")):
        # Tier 2: the whole message is a no and nothing else, so it is the
        # answer to the card's own question and the draft goes. Anchored on
        # purpose -- "no but change the dates" carries a change and must not
        # land here; it goes to classify_confirmation_reply instead. See the
        # banner above.
        if _BARE_CONFIRMATION_DECLINE_RE.match(query or ""):
            leave_slot_service.clear_slots(company_id, conversation_id)
            return _finish(
                "No problem — I've discarded that leave request. Nothing was "
                "submitted."
            )
        new_reason = _reason_change_from_reply(query)
        if new_reason:
            # Held, not stored. The regex isolates WHICH words are the new
            # reason; it does not clean them, and on this phrasing it does not
            # even isolate them correctly -- "reason should be changed to bANk
            # wOrK" came out as "Changed to bANk wOrK", wrapper and all, on the
            # card. The first attempt at a reason goes through the extractor
            # and "BANK WORK" becomes "Bank work", so an explicit change must
            # get the same treatment or the same words produce different
            # results depending only on which turn they arrived on -- exactly
            # what HA-666 asks not to happen.
            #
            # The extraction call below already runs on this turn, so this
            # costs nothing extra. Its cleaned reason wins; this regex result
            # is the fallback for when the model is unreachable.
            explicit_reason_change = new_reason
            slots["reason_confirmed"] = True
            slots.pop("reason_confirm", None)
            slots.pop("reason_attempts", None)
            slots["step"] = "collecting"

    # A date that cannot exist ("31 February", "31/04/2026") is said so, not
    # silently dropped. QA HA884-TC-020: "Apply leave for 31 February" asked
    # for the leave type, then "What dates would you like to take off?" with
    # no word on why the date was not used. Deterministic - no model call.
    from services.regularisation_node import _invalid_date_mention, _invalid_date_message
    _bad_date = _invalid_date_mention(query, _today())
    if _bad_date:
        logger.info("[Leave] impossible date %r in %r - asking again", _bad_date, query[:80])
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish(_invalid_date_message(
            _bad_date, _today(), question="Which date would you like to take leave?",
            example=date.fromordinal(_today().toordinal() + 1).strftime("%d %b %Y")),
            extra_data={"invalid_date": _bad_date})

    # 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).
        # Loaded BEFORE extraction, not after it. Resolving shorthand only
        # once the model had already failed does not work, because the model
        # does not fail — it GUESSES. Live: "apply SHL today" came back as
        # leave_without_pay (refused, since this company has no such type),
        # and "apply shl today" came back as comp_off, which IS configured
        # here and so sailed through as a silently wrong request. Neither
        # ever reached the recovery path, because nothing looked unresolved.
        #
        # Telling the model the company's own abbreviations up front removes
        # the guess. Cached on the conversation, so this costs one GET on the
        # first turn of an apply flow and nothing on the turns after it.
        if "_leave_abbreviations" not in slots:
            _known_types = await _fetch_known_leave_types(
                erp_client, bearer_token, company_id, conversation_id,
            )
            _abbrev_payload = await _fetch_leave_abbreviations(
                erp_client, bearer_token, company_id, conversation_id,
            )
            # Cached even when empty — an unreachable endpoint or a company
            # that configured none should not be re-asked every turn.
            slots["_leave_abbreviations"] = _abbreviations_for_configured_types(
                _abbrev_payload, _known_types,
            )
            if slots["_leave_abbreviations"]:
                logger.info(
                    "[Leave] company abbreviations in play: %s",
                    ", ".join(f"{a}={s_}" for a, s_ in slots["_leave_abbreviations"].items()),
                )

        prompt = _build_leave_slot_extraction_prompt(
            _add_explicit_year_hint(query), slots,
            known_abbreviations=slots.get("_leave_abbreviations") or None,
        )
        # temperature=0: this output is PARSED into slots, never shown. At the
        # provider default the same reply came back differently run to run -
        # "Doctor appointment at 4pm" lost its time on some runs, "Car
        # breakdown" came back null on others, and capitalization drifted.
        # HA-666 asks for consistency and for the employee's own information
        # to survive intact; this is the engineering half of that.
        # 200 was enough on OpenAI, where completion tokens are all visible
        # output. race's gpt-oss-120b is reasoning-tier: it spends completion
        # tokens on a hidden reasoning pass BEFORE writing any content, and
        # returns content="" with finish_reason="length" if the budget runs
        # out first. This prompt is ~3.3k tokens, so 200 was exhausted every
        # single time -- extraction returned {}, leave_type stayed None, and
        # the flow re-asked "what type of leave?" forever. Measured on the
        # identical failure in policy_rag_node (hr_graph.py:981): 400 -> empty
        # every time, 1200 -> still truncated, 1800 -> finishes at ~1050.
        raw = await _call_llm(prompt, max_tokens=LLM_TASK_MAX_TOKENS, 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)
    if explicit_reason_change:
        # The extractor's cleaned wording wins; the regex capture is only the
        # fallback for a failed call. Then everything else this turn produced
        # is dropped: the reply was about the reason and nothing else, so
        # whatever extraction read into it ("change" as a date correction)
        # must not alter the rest of the request on screen.
        _cleaned = (extracted.get("reason") or "").strip()
        slots["reason"] = _cleaned or explicit_reason_change
        amend_note = f"Updated the reason to \"{slots['reason']}\". "
        extracted = {}

    # ── Amendment choice (asked last turn, answered this turn) ───────────────
    # We proposed three things to do about an amendment and must read the
    # answer to THAT question before anything else. Left to the confirmation
    # guard below, "amend" is classified as an answer to "shall I submit
    # this?", comes back "other", and is rejected -- the assistant asking a
    # question and then refusing its own answer. Worse, the amendment was
    # never stored, so a later "yes" submitted the UNAMENDED request: the
    # employee saw their change acknowledged and got the old dates anyway.
    if (slots.get("step") == "awaiting_confirmation"
            and slots.get("_pending_amendment")):
        _pending = dict(slots.get("_pending_amendment") or {})
        _pending_text = slots.get("_pending_amendment_text") or "what you asked for"
        _summary = (f"{slots.get('leave_type', 'leave').replace('_', ' ')} on "
                    f"{_display_date_range(slots.get('from_date'), slots.get('to_date'))}")
        _ask = (f"You have {_summary} waiting for confirmation, and you asked to "
                f"change it to \"{_pending_text}\".")
        # The three words the question itself offers, typed or chip-pressed,
        # resolve without the model: an outage must not strand the employee
        # on a question they have answered in its own terms.
        _offered = _AMEND_CHOICE_WORD_RE.match(query or "")
        _choice, _chusage = (_offered.group(1).lower(), None) if _offered else await classify_choice(
            question=_ask,
            options={
                "amend": ("apply the change to the request already on screen and "
                          "show it again for confirmation -- amend, edit it, "
                          "change it, update it, yes amend, yes change it"),
                "keep": ("leave it unchanged and go ahead with the original "
                         "request -- keep it, continue with the old one, submit "
                         "the original, carry on with it"),
                "discard": ("throw the original away and start a new request from "
                            "the change instead -- discard, scrap it, delete it, "
                            "start again, new request"),
            },
            reply=query,
        )
        if _chusage:
            usage_events.append({"source": "leave_amend_choice", "usage": _chusage})
        logger.info("[Leave] amend choice %r -> %s", query[:60], _choice)

        slots.pop("_pending_amendment", None)
        slots.pop("_pending_amendment_text", None)

        if _choice == "amend":
            # Apply the change on top of the request that exists, so anything
            # the amendment did not mention -- a reason given three turns ago
            # -- survives it. Stepping back to "collecting" drops out of the
            # confirmation guard below, so the flow re-validates and renders a
            # fresh card: they confirm the amended request, never this one.
            extracted.update(_pending)
            if _pending.get("reason"):
                slots.pop("reason_confirm", None)
            # An amendment that moves the START past the old END leaves a
            # range that reads backwards, and the flow answers "the end date
            # can't be before the start date" -- about dates the employee
            # never put together. The stale half goes instead, and the flow
            # asks for the one it now needs.
            _new_from = _pending.get("from_date")
            _new_to = _pending.get("to_date")
            if _new_from and not _new_to and (slots.get("to_date") or "") < _new_from:
                slots.pop("to_date", None)
            if _new_to and not _new_from and (slots.get("from_date") or "") > _new_to:
                slots.pop("from_date", None)
            slots["step"] = "collecting"

        elif _choice == "discard":
            # A new request rather than an edit, so the old field values go --
            # nothing from the abandoned one may leak into it. The cached
            # company config this turn already fetched is kept.
            for _f in ("leave_type", "from_date", "to_date", "session_type_slug",
                       "reason", "reason_confirm"):
                slots.pop(_f, None)
            extracted.update(_pending)
            slots["step"] = "collecting"

        elif _choice == "keep":
            # Deliberately NOT a submission. "no" at this question means "no,
            # don't amend it", which the classifier quite reasonably reads as
            # keep -- and if keep submitted, a bare "no" would file the leave
            # request. That is the exact opposite of what "no" has meant
            # everywhere else in this flow, and it is unrecoverable: the
            # request is with the approver before the employee can object.
            #
            # So keep only puts the original back in front of them. The card
            # is still on screen and the step is unchanged, so the yes that
            # follows goes through the ordinary confirmation path and submits
            # exactly as it would have.
            leave_slot_service.set_slots(company_id, conversation_id, slots)
            return _finish(
                f"Keeping the original then — {_summary}. Shall I submit it? "
                f"Reply **yes** to submit it, or **no** to discard it."
            )

        else:
            slots["_pending_amendment"] = _pending
            slots["_pending_amendment_text"] = _pending_text
            leave_slot_service.set_slots(company_id, conversation_id, slots)
            # Usually an unrelated request typed over the top of the
            # question -- "show me my leaves". Saying only "I couldn't tell
            # which you meant" reads as a parsing failure; what the employee
            # needs to know is that this one has to be settled first, and
            # what the three ways of settling it are.
            return _finish(
                f"I can't move on to anything else until this is settled — "
                f"{_ask.rstrip('.')}. Reply **amend** to apply that change, "
                f"**keep** to go ahead with the original as it stands, or "
                f"**discard** to throw it away and start a new request."
            )

    # Extraction reads the raw text, and a spaced or short code is not a type
    # to it: QA's "e l tomorrow" / "sh l tomorrow" came back with no
    # leave_type, so the draft asked "what type of leave?" of someone who had
    # just said. The deterministic reader folds codes first - only used when
    # the draft has no type yet and exactly one is named.
    # Only the part BEFORE the reason, and never over a type extraction named
    # and could not place: QA's "apply for LOP ... beyond my sick leave quota"
    # was turned into a Sick Leave request by the words in its reason.
    if isinstance(extracted, dict) and not amend_note and not extracted.get("leave_type") \
            and not extracted.get("unrecognized_leave_type") and not slots.get("leave_type"):
        _reason_at = nlp_service._REASON_CLAUSE_START_RE.search(query)
        _named_type = _extract_leave_type_filters(query[:_reason_at.start()] if _reason_at else query)
        if len(_named_type) == 1:
            extracted["leave_type"] = _named_type[0]

    # ── Confirmation-turn recognition ────────────────────────────────────────
    if slots.get("step") == "awaiting_confirmation":
        # A reply here that is neither yes nor a discard used to fall straight
        # through into ordinary slot extraction, which merged whatever it found
        # into the live application and re-rendered the card. Typing "sick" at
        # the summary of a CASUAL leave silently switched the leave type, with
        # no acknowledgement that anything had changed -- the employee's only
        # clue was a different word on a card that otherwise looked identical.
        #
        # Nothing about a request under review may change without being said
        # out loud, so the reply is read first and an amendment is offered
        # rather than applied.
        # A leading "yes" is not consent to what follows it. Extraction sets
        # is_affirmative from the word alone, so "yes but only half day"
        # submitted a FULL day, "yes what is my leave balance" submitted and
        # never answered the question, and "yes i think so but let me check my
        # balance first" submitted the request the employee had just asked to
        # hold. Each one is irreversible and reaches the approver.
        #
        # Only a whole-message affirmative goes straight through
        # (_BARE_CONFIRMATION_AFFIRM_RE is anchored). Anything with more in it
        # is judged by classify_confirmation_reply, which can tell a go-ahead
        # from an amendment, a question, or a hesitation -- see the banner near
        # the top of this function: a typed word is not a decision.
        _unambiguous_yes = bool(_BARE_CONFIRMATION_AFFIRM_RE.match(query or "")
                               or _ANSWER_SUBMIT_RE.match(query or ""))
        if not _unambiguous_yes and not _is_declining_or_cancelling(query):
            _summary = (f"{slots.get('leave_type', 'leave').replace('_', ' ')} on "
                        f"{_display_date_range(slots.get('from_date'), slots.get('to_date'))}")
            verdict, replacement, _cusage = await classify_confirmation_reply(
                question=f"To confirm: {_summary}. Shall I submit this request?",
                current_value=_summary, reply=query, field_label="leave request",
            )
            logger.info("[Leave] awaiting_confirmation reply %r -> %s", query[:60], verdict)
            # What this turn's extraction read as different from the card.
            _amendment = {
                _f: extracted[_f]
                for _f in ("leave_type", "from_date", "to_date", "session_type_slug", "reason")
                if extracted.get(_f) and extracted.get(_f) != slots.get(_f)
            }

            if verdict == "agree":
                # The pattern check said no but the model reads it as yes --
                # a typo ("yess", "yrs") or a short form the list never had
                # ("ok", "y", "ya"). Treat it as the confirmation it is,
                # rather than letting it fall through and be re-extracted.
                extracted["is_affirmative"] = True

            elif verdict == "decline":
                # Tier 2: the model read the whole reply as a no. Nothing else
                # is in it, so this is the answer and the draft goes.
                leave_slot_service.clear_slots(company_id, conversation_id)
                return _finish(
                    "No problem — I've discarded that leave request. Nothing was "
                    "submitted."
                )

            elif verdict == "replace" and _amendment:
                # They want an amendment, not a submission. Confirming a
                # request and editing it are different actions and must not
                # happen in one silent step, so it is offered rather than
                # applied -- and the offer is answered by the amendment-choice
                # block above, the only reader of _pending_amendment. This
                # branch is its only writer: 9165feb dropped it, and "yes but
                # make it 6 nov" was then answered "needs closing ... tell me
                # what you'd like to change" -- the change it had just been
                # told was ignored (negative run, 28 Oct, #30).
                slots["_pending_amendment"] = _amendment
                slots["_pending_amendment_text"] = (replacement or query).strip()[:120]
                leave_slot_service.set_slots(company_id, conversation_id, slots)
                return _finish(
                    f"Before I change anything — the request on screen is "
                    f"{_summary}. Would you like me to **amend** it to "
                    f"\"{slots['_pending_amendment_text']}\", **keep** the "
                    f"original and go ahead with it, or **discard** it and "
                    f"start a new request?"
                )

            else:  # "other" — unreadable as an answer to this question
                # (Also a "replace" that extraction found nothing usable in:
                # asking again is honest, claiming a change we do not have
                # is not.)
                #
                # Usually an unrelated request typed while the card is open:
                # "show me my leaves", "what's my balance". The card is the
                # live context, so nothing else can be answered until it is
                # resolved -- and the reply has to say THAT, not "I couldn't
                # read that", which reads as a parsing failure and leaves the
                # employee with no idea what is being asked of them.
                leave_slot_service.set_slots(company_id, conversation_id, slots)
                return _finish(
                    f"Before I can help with anything else, this leave request "
                    f"needs closing — {_summary}, waiting for your confirmation. "
                    f"Reply **yes** to submit it or **no** to discard it, or tell "
                    f"me what you'd like to change about it."
                )

        # Tier 1 and 2 land here: a button press ("yes submit it") and a
        # whole-message yes both match _unambiguous_yes, and both submit on
        # sight. A QUALIFIED yes never reaches this line -- the guard above
        # sent it to classify_confirmation_reply, which is what stops "yes but
        # only half day" submitting a full day. See the banner at the top.
        if _unambiguous_yes or extracted.get("is_affirmative"):
            # At most once per draft - see services/leave_submit_claim.py.
            _claim = (slots.get("leave_type"), slots.get("from_date"), slots.get("to_date"),
                      slots.get("session_type_slug"))
            if not leave_submit_claim.claim(company_id, conversation_id, _claim):
                logger.warning("[Leave] duplicate confirmation for %s ignored - already submitting", _claim)
                return _finish(
                    "That leave request is already being submitted — I won't send it twice. "
                    "You'll see it under your leave requests in a moment."
                )
            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:
                leave_submit_claim.release(company_id, conversation_id, _claim)
                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):
                leave_submit_claim.release(company_id, conversation_id, _claim)
                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):
                leave_submit_claim.release(company_id, conversation_id, _claim)
                # 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"
                # Frontend date-picker signal, decided by the same branch that
                # decides WHICH slot to re-collect: only the branches that
                # clear the dates and ask for new ones get a calendar. The
                # reason/session-type branches leave the dates alone (they were
                # never the problem), and the fallback deliberately offers no
                # date next_action at all — showing a picker there would imply
                # the dates were at fault when we don't know that.
                requires_date_input = False
                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")]
                    requires_date_input = True
                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)
                if requires_date_input:
                    card["requires_date_input"] = True
                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.")
            # They asked for more than one leave at the start ("apply cl /
            # need Sl / want EL") and were told one at a time - so offer the
            # next one now rather than forgetting it. A fresh draft holding
            # only the choice, so "yes" / "no" / a type name resolves it
            # exactly as the first choice did (and it replaces any stale
            # "submitted" marker left above, which is the safer state anyway).
            queued = [s for s in (slots.get("_queued_types") or []) if s != slots.get("leave_type")]
            if queued:
                leave_slot_service.set_slots(company_id, conversation_id, {
                    "step": "collecting", "leave_type": None, "from_date": None, "to_date": None,
                    "session_type_slug": None, "reason": None, "_type_choice": queued,
                    "_leave_abbreviations": slots.get("_leave_abbreviations") or {},
                })
                confirm_msg += (f" You also asked for {' and '.join(_display_leave_type_name(s) for s in queued)}"
                                f" — would you like to apply for {_display_leave_type_name(queued[0])} next?")
            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).
    # ---- One leave request at a time (CEO review point 6) ----------------
    # Checked on a FRESH request only — before this turn's extraction is
    # merged, while `slots` still describes what was known BEFORE the
    # message. Mid-flow the same two type names are ordinary ("I have no
    # casual leave, use sick leave instead" is one request changing type), so
    # the check would be wrong there.
    #
    # Not a nicety: extraction does not refuse a two-request message, it
    # BLENDS one. "I want casual leave tomorrow and sick leave on Friday"
    # came back as a single request carrying the type from the second and the
    # date from the first — sick leave tomorrow — which the employee never
    # asked for and which nothing downstream could notice was wrong.
    # The reply to that question. QA: "apply cl / need Sl / want EL" -> "Would
    # you like to start with Casual Leave?" -> "not cl but start with el" ->
    # the SAME question again, because the reply names two types and the
    # check below saw a fresh two-request message. The offer is now kept on
    # the draft and the reply read against it.
    pending_choice = slots.get("_type_choice")
    if pending_choice:
        chosen, still_open = _resolve_type_choice(query, pending_choice)
        if not chosen:
            slots["_type_choice"] = still_open
            leave_slot_service.set_slots(company_id, conversation_id, slots)
            labels = [_display_leave_type_name(s) for s in still_open]
            options = " or ".join(labels) if len(labels) <= 2 else ", ".join(labels[:-1]) + f", or {labels[-1]}"
            return _finish(f"Sure — which one would you like to start with: {options}?")
        slots.pop("_type_choice", None)
        slots["_queued_types"] = [s for s in pending_choice if s != chosen]
        # The reply may still name the refused type ("not cl but el"), so
        # the type comes from the choice, never from extraction's reading.
        extracted["leave_type"] = chosen
        logger.info("[Leave] one-at-a-time choice resolved -> %s | query=%r", chosen, query[:80])

    elif not slots.get("leave_type") and not slots.get("from_date"):
        # Types in the REASON are not requests: QA's "apply for LOP ... due to
        # medical treatment beyond my sick leave quota" was asked to pick
        # between Leave Without Pay and Sick Leave.
        _reason_at = nlp_service._REASON_CLAUSE_START_RE.search(query)
        _named_types = _extract_leave_type_filters(query[:_reason_at.start()] if _reason_at else query)
        if len(_named_types) >= 2:
            # Ordered by where each appears in the MESSAGE, not by the match
            # table's own order — offering to start with the second one they
            # mentioned reads as not having listened.
            _ql = query.lower()
            _named_types.sort(key=lambda slug: min(
                (_ql.find(w) for w, sl in _LEAVE_TYPE_FILTER_WORDS.items()
                 if sl == slug and _ql.find(w) != -1),
                default=len(_ql),
            ))
            _first_label = _display_leave_type_name(_named_types[0])
            logger.info(
                "[Leave] %s leave types named in one message (%s) — asking to take "
                "them one at a time. query=%r", len(_named_types), _named_types, query[:80],
            )
            slots["_type_choice"] = _named_types
            leave_slot_service.set_slots(company_id, conversation_id, slots)
            return _finish(
                f"I can process one leave request at a time. Would you like to start "
                f"with {_first_label}?"
            )

    had_leave_type_before = bool(slots.get("leave_type"))
    # The type as it stood BEFORE this turn's merge, so the reason gate below
    # can tell a type-switch message apart from a failed attempt at a reason.
    had_leave_type_value = slots.get("leave_type")

    # STEP 5's gates, enforced HERE rather than trusted to the model. The
    # prompt states them plainly and gpt-4o-mini still flagged words it had
    # just corrected ("persnal work" -> reason "Personal work", flagged
    # anyway), which would interrogate the employee about a word Helix
    # already got right. Two of the three gates are mechanically checkable,
    # so check them.
    # The model reconciles a self-contradicting message unless told not to:
    # "2 days leave from Thursday to Saturday" came back as Thu..Fri, the
    # count silently winning and Saturday dropped, so there was no conflict
    # left in the slots for the deterministic check below to find. The prompt
    # now reports it instead, and this is where that lands.
    if extracted.get("dates_contradict_duration"):
        logger.warning(
            "[Leave] message states a day count and a range that disagree — asking. query=%r",
            query[:80],
        )
        # No numbers: the model reports THAT the message disagrees with
        # itself, not a pair of day counts we could quote back. Whatever the
        # resolvers below make of the same phrase is a different reading of
        # it, so quoting their numbers would put a figure in front of the
        # employee that no part of their message actually said.
        slots["_duration_range_conflict"] = {"duration_days": 0, "range_days": 0}

    _drop_unusable_reason_uncertainty(extracted)

    # Merge this turn's extracted fields into the slots.
    #
    # `reason` is held back whenever a reason CONFIRMATION is outstanding.
    # While that question is on screen the reply is an ANSWER to it — yes,
    # no, or a replacement — and the handler below (which pops reason_confirm)
    # is the only thing entitled to decide what the reason becomes. Merging
    # here first let the extractor's reading of the reply overwrite the very
    # reason being confirmed: asked "reply yes to keep 'Medical emergency'",
    # the employee typed "YES", extraction returned reason="YES", this loop
    # stored it, and the handler's "agree — keep what we have" then kept
    # "YES". The card went out reading Reason: YES and that is what would
    # have been submitted.
    _reason_confirm_pending = bool(slots.get("reason_confirm"))
    _merge_fields = ("leave_type", "from_date", "to_date", "session_type_slug")
    if not _reason_confirm_pending:
        _merge_fields += ("reason",)

    # "CL for 0 days" / "SL for -1 days": a day count that cannot be a leave.
    # QA: the number was dropped without a word and the flow asked for dates,
    # as if nothing had been said. The type is kept; only the count is refused.
    _count = _NON_POSITIVE_DAY_COUNT_RE.search(query)
    if _count:
        if extracted.get("leave_type") and not slots.get("leave_type"):
            slots["leave_type"] = extracted["leave_type"]
        slots["step"] = "collecting"
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish(
            f"{_count.group(1)} day(s) isn't a leave I can apply for — a leave has to be at "
            f"least half a day. How many days, or which dates, would you like?",
            extra_data={"requires_date_input": True},
        )
    _impossible = _impossible_leave_span(query, _today())
    if _impossible:
        if extracted.get("leave_type") and not slots.get("leave_type"):
            slots["leave_type"] = extracted["leave_type"]
        slots["step"] = "collecting"
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish(_impossible, extra_data={"requires_date_input": True})

    # "Can I give the reason first?" on a fresh draft. QA: it went to the
    # policy search and came back "couldn't find anything in our policy
    # documents". The type is not known yet, so the examples are the neutral
    # set; the reason given next is kept and the type and dates asked after.
    if (nlp_service.asks_to_give_reason_first(query) and not slots.get("leave_type")
            and not slots.get("from_date") and not slots.get("reason")):
        slots["step"] = "collecting"
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish(
            f"Sure — tell me the reason first{_reason_examples_for(None)}, and I'll ask "
            f"for the leave type and dates after that."
        )

    _reason_before_merge = slots.get("reason")
    for field in _merge_fields:
        if extracted.get(field):
            slots[field] = extracted[field]

    # A DIFFERENT reason arriving needs its own approval — the employee
    # approved the previous wording, not this one. Covers the late change
    # ("actually, make the reason fever") arriving after the confirmation
    # card is already on screen.
    if slots.get("reason") and slots.get("reason") != _reason_before_merge:
        if _reason_matches_what_was_typed(query, slots["reason"]):
            # Helix stored what they typed. There is no AI modification to
            # approve, and the confirmation card names the reason anyway.
            slots["reason_confirmed"] = True
        else:
            slots.pop("reason_confirmed", None)
    # 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)

    # ---- Reply to the pending "did you mean ...?" ------------------------
    # Parked in `slots` rather than a Redis store of its own: it only exists
    # mid-application, which is exactly how long these slots live, so it is
    # cleared by the same clear_slots() every exit path already calls.
    pending_reason = slots.pop("reason_confirm", None)
    if pending_reason:
        as_typed = pending_reason.get("as_typed") or ""
        suggestion = pending_reason.get("suggestion") or ""
        # The reason the question SHOWED, not the post-merge slot. This turn's
        # extraction has already run on the reply and may have filed the reply
        # itself as the reason: QA saw the card read "Reason: Yess" after
        # "yess", and a garbled reply shown back as both unreadable and "the
        # reason I have so far". A yes confirms what was on screen. Slots
        # saved before "offered" existed hold the same value pre-merge.
        current = pending_reason.get("offered") or _reason_before_merge or slots.get("reason") or ""
        if _is_spelling_confirm(query):
            if as_typed and suggestion:
                slots["reason"] = _substitute_preserving_case(current, as_typed, suggestion)
                logger.info("[Leave] reason confirmed with spelling %r -> %r", as_typed, suggestion)
            else:
                slots["reason"] = current
                logger.info("[Leave] reason confirmed as recorded: %r", current)
            slots["reason_confirmed"] = True

        elif _is_spelling_decline(query):
            if as_typed and suggestion:
                # "no" to a SPELLING offer means the word was right as typed.
                # The reason itself is still theirs, so it stands.
                logger.info("[Leave] spelling correction declined, keeping %r", as_typed)
                slots["reason"] = current
                slots["reason_confirmed"] = True
            else:
                # "no" to the reason itself. Nothing here is worth guessing
                # at — drop it and ask again rather than submitting a reason
                # the employee has just said is wrong.
                logger.info("[Leave] reason rejected by the employee, asking again")
                slots["reason"] = None
                slots.pop("reason_confirmed", None)
                leave_slot_service.set_slots(company_id, conversation_id, slots)
                return _finish("No problem — what would you like the reason to say?")

        else:
            # Neither pattern matched. Before assuming this is a rewrite, ask
            # the model what the reply actually IS -- agreement, refusal, a new
            # reason, or something unrelated.
            #
            # Live bugs this closes: the employee typed "yess" to confirm and
            # the card came back reading "Reason: Yess"; the product told them
            # to type "continue" to resume and then recorded "Reason:
            # Continue". Both fell into this branch, which stored the reply
            # verbatim because it was short and was not on the yes list --
            # a list that also misses yrs, ya, ok, okay and y.
            verdict, replacement, _cusage = await classify_confirmation_reply(
                question=f"Just to confirm, did you mean \"{current}\"?",
                current_value=current, reply=query, field_label="reason",
            )
            logger.info("[Leave] reason-confirm reply %r -> %s", query[:60], verdict)

            if verdict == "agree":
                slots["reason"] = (_substitute_preserving_case(current, as_typed, suggestion)
                                   if as_typed and suggestion else current)
                slots["reason_confirmed"] = True
                leave_slot_service.set_slots(company_id, conversation_id, slots)

            elif verdict == "decline":
                slots["reason"] = None
                slots.pop("reason_confirmed", None)
                leave_slot_service.set_slots(company_id, conversation_id, slots)
                return _finish("No problem — what would you like the reason to say?")

            elif verdict == "other":
                # NOT the reason. Say where we are and ask again rather than
                # filing an unrelated word as why they need the leave.
                # The reply is not a reason, so whatever extraction filed from
                # it goes: the reason stays the one still awaiting a yes, and
                # the merge's "typed verbatim, nothing to approve" shortcut
                # must not have approved the unreadable text meanwhile.
                slots["reason"] = current
                slots.pop("reason_confirmed", None)
                slots["reason_confirm"] = pending_reason
                leave_slot_service.set_slots(company_id, conversation_id, slots)
                return _finish(
                    f"Sorry — I'm still waiting on the reason for this leave, and I "
                    f"couldn't read \"{query.strip()[:40]}\" as one. The reason I have "
                    f"so far is \"{current}\". Reply yes to keep it, or type the reason "
                    f"you'd like instead."
                )

            else:
                # verdict == "replace". Only replace: an "agree" used to run
                # this too, found the reply was not the stored reason, cleared
                # the approval and asked the same question again - forever.
                # Uses the model's cleaned value when it gave one.
                rewritten = (replacement or query).strip().rstrip(".!,")
                answering_a_word = (
                    bool(as_typed and suggestion)
                    and len(rewritten.split()) <= 2
                    and len(current.split()) > 2
                )
                if answering_a_word:
                    # The question named ONE word and they answered with one word.
                    # Swapping just that word keeps the rest of the reason they
                    # already gave — "Mtg w/ drs" answered "dentists" means
                    # "Mtg w/ dentists", not a reason that is only "Dentists".
                    slots["reason"] = _substitute_preserving_case(current, as_typed, rewritten)
                    logger.info("[Leave] reason word replaced -> %r", slots["reason"])
                elif extracted.get("reason"):
                    # Set explicitly rather than leaning on the merge above.
                    # While a reason is awaiting approval that merge now skips
                    # the reason field on purpose -- it is what stops a "YES"
                    # being filed as the reason -- so this turn's cleaned value
                    # would otherwise never reach the slot, and a genuine new
                    # reason ("Kidney stone") left the old one on the card.
                    slots["reason"] = extracted["reason"]
                    logger.info("[Leave] reason rewritten by the employee -> %r", slots["reason"])
                elif rewritten:
                    # Re-clean the edit instead of storing it verbatim. This branch
                    # used to do `rewritten[:1].upper() + rewritten[1:]` -- capitalise
                    # the first letter and save whatever they typed -- so an employee
                    # who RETYPED their reason got none of the cleaning the first
                    # attempt got: "feever" became "Fever" the first time and
                    # "Feever" on the edit, and "the reason is personal work" came
                    # back with the wrapper still attached. Same input, different
                    # result, depending only on which turn it arrived on.
                    #
                    # extracted["reason"] is this turn's cleaned value and is
                    # preferred when the extractor produced one; the raw text is
                    # the fallback for when it did not. The <= 8 word cap is gone
                    # with it -- a longer edit was silently dropped before, leaving
                    # the employee looking at the reason they had just replaced.
                    cleaned = (extracted.get("reason") or "").strip()
                    slots["reason"] = cleaned or (rewritten[:1].upper() + rewritten[1:])
                    logger.info("[Leave] reason edited -> %r (cleaned=%s)",
                                slots["reason"], bool(cleaned))
                # Helix cleans a rewrite exactly as it cleaned the first attempt
                # — "no, i have fever" becomes "Fever", filler stripped and
                # capital added — so a CHANGED rewrite is just as much an
                # AI-modified reason and gets its own approval. A rewrite Helix
                # stored verbatim needs none, by the same rule as the first pass.
                if _reason_matches_what_was_typed(query, slots.get("reason") or ""):
                    slots["reason_confirmed"] = True
                else:
                    slots.pop("reason_confirmed", None)

        leave_slot_service.set_slots(company_id, conversation_id, slots)

    # ── 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)

            # Not a full name or a near-miss of one — try the company's own
            # shorthand (HA-665). The ORDER is the design: find out which
            # leave types this company HAS, then ask whether what the employee
            # typed is one of that company's abbreviations for them. Helix
            # holds no opinion of its own about what "CL" means.
            #
            # Reached only when nothing else matched, so it costs nothing on
            # an ordinary turn. This is what makes "SHL", "LOP" and any
            # company-specific code work.
            if not matched_slug and candidate:
                abbrev_payload = await _fetch_leave_abbreviations(
                    erp_client, bearer_token, company_id, conversation_id,
                )
                abbrev_map = _abbreviations_for_configured_types(
                    abbrev_payload, known_leave_types,
                )
                if abbrev_map:
                    # Cached on the conversation so later turns can hand the
                    # same list to the extraction prompt without re-fetching.
                    slots["_leave_abbreviations"] = abbrev_map
                    _key = str(candidate).strip().strip(".").upper()
                    matched_slug = next(
                        (slug for abbrev, slug in abbrev_map.items()
                         if abbrev.upper() == _key),
                        None,
                    )
                    if matched_slug:
                        logger.info(
                            "[Leave] %r matched this company's abbreviation for %s",
                            candidate, matched_slug,
                        )

            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)

    # A reply accepting the month this assistant inferred for a bare
    # day-of-month — see the ambiguous_bare_day_of_month branch below, which
    # states that assumption and stores the date it named. Because the date
    # was named in the question, "yes" alone is a complete answer and needs
    # no date in this turn's text. Deterministic confirm check, never gated
    # behind the LLM's is_affirmative.
    #
    # Popped whichever way this turn goes: the question was asked once, and
    # a reply that carries its own date is the user taking the other half of
    # what was offered ("or would you like a different date?"), which must
    # win over the suggestion rather than sit behind it.
    suggested_from_date = slots.pop("suggested_from_date", None)
    if suggested_from_date and not extracted.get("from_date") and _is_confirming(query):
        # Single day on both ends: the branch that set this cleared both
        # date slots, and the bare-ordinal phrasing it fires on never names
        # a range.
        slots["from_date"] = suggested_from_date
        slots["to_date"] = suggested_from_date
        logger.info(
            "[Graph] Inferred-month date confirmed by the user -> %s", suggested_from_date,
        )

    # ── 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 == "ambiguous_bare_day_of_month":
            # The user named a day but no month, and that day has already
            # gone by this month — so a month WAS inferred, and the report
            # this branch answers (2026-09-09) is that the inference was
            # never mentioned until the final summary card. State it, with
            # the reason for it, and let a bare "yes" take it: unlike every
            # other branch here there is a specific date worth naming,
            # because only the MONTH was ever in doubt — the day number came
            # from the user verbatim and _next_date_on_day_of_month is plain
            # arithmetic, not the model's guess (which is why the other
            # branches deliberately suggest nothing).
            # Deferred import for the same circular-import reason as
            # evaluate_eligibility below — leave_eligibility_service imports
            # from this module at its own load time. Reused rather than
            # re-implemented so "22nd"/"23rd"/"11th" render identically
            # wherever they appear.
            from services.leave_eligibility_service import _ordinal_day

            suggestion = _next_date_on_day_of_month(needs_confirmation["day"], today)
            if suggestion is not None:
                slots["suggested_from_date"] = suggestion.isoformat()
                leave_slot_service.set_slots(company_id, conversation_id, slots)
                return _finish(
                    f"The {_ordinal_day(needs_confirmation['day'])} has already passed this "
                    f"month, so I've taken this as {_display_date(suggestion.isoformat())}. "
                    "Shall I go with that, or would you like a different date?",
                    extra_data={"requires_date_input": True},
                )
            return _finish(
                "I want to make sure I get the right day — which month did you mean? "
                "Tell me the exact date (or date range) you'd like.",
                extra_data={"requires_date_input": True},
            )
        if reason == "past_date" and _names_a_bare_week_span(query):
            # "CL for previous week": the model picked a day of that week, the
            # employee never named one. Ask, exactly as "next week" is asked,
            # rather than refusing a date they did not choose.
            return _finish(
                "Which exact dates would you like to take off?",
                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},
        )

    # ── Dates carried across a leave-type change after a balance rejection ──
    # Live report: "leave for the last week of this month" -> "sick leave" ->
    # "you don't have enough Sick Leave" -> "casual leave" -> "What dates
    # would you like to take off?". The dates the employee had already given
    # were gone, so the type they switched to was never checked against them.
    #
    # The balance rejection clears from_date/to_date on purpose (see the
    # anti-loop comment where it does): a reply carrying no new date would
    # otherwise re-validate the identical combination and repeat the same
    # rejection forever. But a reply naming a DIFFERENT leave type is not
    # that case at all — the combination genuinely changed, re-validating it
    # is the whole point, and it terminates. So the rejection now stashes the
    # dates instead of dropping them, and they come back only for the one
    # reply that can actually use them.
    #
    # Placed after every date resolver above has had its say, so a date given
    # in the same breath ("casual leave for 5th October") always wins over
    # the stash rather than being overwritten by it.
    rejected_leave_type = slots.get("balance_retry_leave_type")
    if rejected_leave_type:
        if slots.get("from_date"):
            _clear_balance_retry(slots)  # the user supplied their own dates
        elif slots.get("leave_type") and slots["leave_type"] != rejected_leave_type:
            slots["from_date"] = slots.get("balance_retry_from_date")
            slots["to_date"] = slots.get("balance_retry_to_date")
            _clear_balance_retry(slots)
            logger.info(
                "[Graph] Leave type changed after a balance rejection (%s -> %s) — "
                "restoring the dates already given: %s..%s",
                rejected_leave_type, slots["leave_type"], slots["from_date"], slots["to_date"],
            )

    # 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).
    # MUST stay above the conflict/holiday check below. "next week" is not a
    # request for a specific span — it is the employee gesturing at a period
    # they have not picked days in yet. Resolving it to Mon..Sun and then
    # checking that whole span for clashes rejects the request because of ONE
    # unrelated day already booked somewhere inside it ("You've already applied
    # for Short Leave on Wed, 30 Sep"), which is both wrong and baffling to
    # read. It also assumes a working week the employee may not have — shift
    # patterns differ per person.
    #
    # This guard used to sit ~200 lines further down, so the conflict check got
    # there first and the guard became unreachable whenever anything at all was
    # already booked inside the named period. Clearing the speculative dates
    # HERE means the conflict check only ever sees dates the employee actually
    # chose.
    if _names_a_bare_week_span(query) and slots.get("from_date"):
        logger.info(
            "[Leave] vague period with no day named — clearing the resolved "
            "dates and asking. query=%r resolved=%s..%s",
            query[:80], slots.get("from_date"), slots.get("to_date"),
        )
        slots["from_date"] = None
        slots["to_date"] = None
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish(
            "Which exact dates would you like to take off?",
            extra_data={"requires_date_input": True},
        )

    # A type this company does not have is refused before any date check: QA's
    # "apply for LOP tomorrow" / "apply PL for tomorrow" were told "you've
    # already applied for Casual Leave on 25 Sep" - true, but not the problem.
    if slots.get("from_date") and slots.get("to_date") and not unrecognized_leave_type_denial:
        # 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)
            # Live bug: the frontend renders its date picker off this flag, so
            # a blocked-date rejection showed the card with no calendar to act
            # on even though next_action asks for new dates — exactly the same
            # signal the duplicate/insufficient-balance rejections below send.
            # Set on the card itself (not just the done payload) so a client
            # rendering from the leave_failure event alone sees it too.
            card["requires_date_input"] = True
            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",
            )
            # Remember WHICH request this notice was about, so a follow-up
            # "okay, cancel it" can act on that request instead of being read
            # as "discard the draft I was building".
            #
            # QA bug: the conflicting record was rendered into the message and
            # then thrown away, so the next turn had no idea what "it" meant.
            # "cancel it" matched _is_declining_or_cancelling, hit the apply
            # branch's draft discard, and answered "I've cancelled that leave
            # request" — having cleared an unsubmitted draft while the real
            # request stayed exactly where it was.
            leave_cancel_state.set_state(
                company_id, conversation_id,
                {"step": "duplicate_offer", "selected": _build_applied_leave_card(conflict)},
            )
            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)
            card["requires_date_input"] = True
            writer({"type": "leave_failure", "data": card})
            return _finish(
                f"{failure.display_message} {next_action}", intent="apply_leave",
                extra_data=card,
            )

    # 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:
                # Close to one or two real types but not close enough to take
                # (the matcher above auto-accepts from 0.78): ask which, rather
                # than list everything. QA: "apply for cslk leave" should be
                # "did you mean Casual Leave or Sick Leave?".
                _typed = _normalize_leave_type_phrase(str(candidate)).removesuffix(" leave").strip()
                _near = sorted(
                    ((difflib.SequenceMatcher(
                        None, _typed,
                        _normalize_leave_type_phrase(t["name"]).removesuffix(" leave").strip()).ratio(),
                      t["name"]) for t in known_leave_types if t.get("name")),
                    reverse=True)
                _near = [name for score, name in _near if score >= 0.5][:2]
                if _near:
                    leave_slot_service.set_slots(company_id, conversation_id, slots)
                    return _finish(
                        f'I couldn\'t tell which leave type "{candidate}" is — did you mean '
                        f'{" or ".join(_near)}?'
                    )
                names = [t["name"] for t in (_applicable_only(known_leave_types) or 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}."
                )
            # No list means erp-api could not be reached, so nothing here knows
            # whether the type exists. QA, during a rate-limit: "I want CL
            # tomorrow" was told 'We don't have a "casual_leave" leave type
            # here' - a denial of a type the company has.
            return _finish("I'm unable to reach the HR system right now to check the leave "
                           "types — please try again shortly.")
        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 (_applicable_only(known_leave_types) or 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?")

    # ── Only the four leave types Helix can file (product rule) ──────────────
    # Comp Off and Leave Without Pay are configured in erp-api, so the
    # configured-type check above accepts them - and QA saw a Comp Off request
    # go all the way to the summary card. They cannot be applied through Helix
    # right now, so say so and offer the four that can, keeping the draft so
    # the next reply ("casual") simply continues it.
    if slots.get("leave_type") and slots["leave_type"] not in HELIX_APPLICABLE_LEAVE_TYPES:
        refused = _display_leave_type_name(slots["leave_type"])
        slots["leave_type"] = None
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish(
            f"{refused} can't be applied through Helix right now. You can apply for "
            f"{_applicable_leave_types_sentence()} here — which one would you like?"
        )

    # Probation-eligibility pre-check — runs the moment leave_type is known,
    # BEFORE dates/half-day/reason are ever asked, so a probation-blocked
    # employee finds out immediately instead of discovering it only at final
    # submission (mirrors why the back-date, holiday/conflict and balance
    # checks below were each moved as early as their own required slots
    # allow). evaluate_eligibility() is the ONLY place this rule is
    # implemented (services/leave_eligibility_service.py) — imported here
    # deferred, not at module level, because that module itself imports
    # _extract_leave_type_filters/_LEAVE_TYPE_CODES FROM this one; a
    # top-level import here would be circular.
    from services.leave_eligibility_service import evaluate_eligibility

    try:
        probation_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):
        # Advisory only, same posture as every other pre-check in this
        # flow — erp-api's own apply() call remains the authoritative gate,
        # so a transient failure here must not block the conversation.
        pass
    else:
        configured = {
            t.get("slug"): t
            for t in probation_balance_result["body"].get("data", {}).get(
                "leave_settings", {}).get("leave_type", [])
            if t.get("slug")
        }
        leave_type_cfg = configured.get(slots["leave_type"])
        if leave_type_cfg:
            verdict = evaluate_eligibility(leave_type_cfg, context_result["body"].get("data") or {})
            # Only an explicit False blocks the flow — eligible=None means
            # "could not be determined" and, per evaluate_eligibility's own
            # docstring, must never be rendered as a denial. Fail open on
            # uncertainty, same as everywhere else in this file.
            if verdict["eligible"] is False:
                leave_slot_service.clear_slots(company_id, conversation_id)
                card = leave_failure.build_card(
                    "apply_leave",
                    leave_failure.local_failure(verdict["reason"], verdict["reason_code"]),
                )
                writer({"type": "leave_failure", "data": card})
                return _finish(verdict["reason"], extra_data=card)

    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})

    # ---- Dates are validated the moment they are known -------------------
    # CEO review point 9 puts validation BEFORE the remaining questions, not
    # just before the card: asking "full day or half day?" about a request
    # whose dates contradict each other wastes the employee's turn on a
    # request that cannot be submitted either way. Everything below this
    # point assumes from_date/to_date describe a real span.
    # CEO review point 9: validate, THEN confirm. This runs on the FINAL slot
    # values — after extraction, the deterministic resolvers and the duration
    # logic have all had their say — because each can introduce a problem the
    # others never see:
    #
    #   "2 days leave from Thursday to Saturday"     -> 0.0 day(s), submittable
    #   "casual leave from next Monday to yesterday" -> -1.0 day(s), submittable
    #
    # Both reached the confirmation card with a Submit button under them.
    # Dates are cleared rather than repaired: which end is wrong is exactly
    # what is unclear, and guessing is what this whole story forbids.
    _conflict = slots.pop("_duration_range_conflict", None)
    if _conflict:
        # Asked before the inversion check below, because "you said 2 days but
        # named 3" is the real diagnosis; the backwards range it can turn into
        # downstream is only a symptom.
        _n = _conflict["duration_days"]
        _covered = _conflict["range_days"]
        slots["from_date"] = None
        slots["to_date"] = None
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        # Numbers are quoted back only when they are real ones. The flag from
        # extraction carries none, and once a resolver has inverted a range
        # the span can be 0 or negative — "the dates you gave cover 0"
        # explains nothing.
        if _n >= 1 and _covered >= 1:
            _lead = (f"You mentioned {_n} day{'s' if _n != 1 else ''}, but the dates "
                     f"you gave cover {_covered}.")
        elif _n >= 1:
            _lead = (f"You mentioned {_n} day{'s' if _n != 1 else ''}, but the dates "
                     f"you gave don't match that.")
        else:
            _lead = "The number of days and the dates you gave don't match."
        return _finish(
            f"{_lead} Could you tell me the exact dates you'd like to take off?",
            extra_data={"requires_date_input": True},
        )

    if slots.get("from_date") and slots.get("to_date"):
        try:
            _from_d = date.fromisoformat(slots["from_date"])
            _to_d = date.fromisoformat(slots["to_date"])
        except (TypeError, ValueError):
            _from_d = _to_d = None
        if _from_d and _to_d and _to_d < _from_d:
            logger.warning(
                "[Leave] final validation: range ends before it starts (%s -> %s) "
                "— clearing both and asking. query=%r",
                slots["from_date"], slots["to_date"], query[:80],
            )
            slots["from_date"] = None
            slots["to_date"] = None
            leave_slot_service.set_slots(company_id, conversation_id, slots)
            return _finish(
                "The end date can't be before the start date. Could you tell me "
                "the exact dates you'd 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"

    # Short leave is always part of ONE day, so the question is which half,
    # never "full day or half day?". It was never asked at all: the flow went
    # straight to the reason, and a "first half" typed there was stored
    # silently and refused as a reason. erp-api's session_type list offers
    # first_half_day/second_half_day for every type, short leave included.
    if (slots["leave_type"] == "short_leave" and _is_single_day(slots)
            and slots.get("session_type_slug") not in ("first_half_day", "second_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?")

    # "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 simply drops it, and since the CEO review
                # gets no replacement chip either (see below).
                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"))
                # No "Use Another Leave Type" chip on a zero balance: same
                # rule as the message above (CEO review point 7). The employee
                # can name another type themselves whenever they want one.
                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.
                #
                # Parked rather than discarded, though: switching leave TYPE
                # is the one reply that changes the rejected combination
                # without naming a new date, and making the employee retype
                # dates they already gave (only to have the new type checked
                # against nothing) was its own live report. Captured before
                # the zero-balance branch below clears leave_type, so the
                # type that was actually rejected is the one recorded.
                slots["balance_retry_from_date"] = slots["from_date"]
                slots["balance_retry_to_date"] = slots["to_date"]
                slots["balance_retry_leave_type"] = slots.get("leave_type")
                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())
                    # Names the types that DO have balance right now, sourced
                    # from the same leave_quota/leave_settings fetch above so
                    # no extra erp-api round trip is spent on it.
                    #
                    # HA-499 briefly dropped this, citing CEO review point 7
                    # (Helix should not steer an employee toward a leave type).
                    # Reinstated on the 2026-09-23 sprint4-5-race merge: a
                    # zero-total type is a dead end, and saying which types are
                    # usable is information, not advice. Revisit with the CEO
                    # review if that reading is wrong.
                    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,
                )
                # On the card itself so the leave_failure event carries it too
                # — a client rendering from that event alone would otherwise
                # get no calendar. Stays off entirely for the zero-balance
                # case above, where no date could fix the request.
                if requires_date_input:
                    card["requires_date_input"] = True
                writer({"type": "leave_failure", "data": card})
                return _finish(f"{reason_text} {next_action}", extra_data=card)
        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.
        # A message that CHANGED the leave type was about the type, not the
        # reason — so it does not count as a failed attempt at giving one,
        # and must never be stored as one.
        #
        # Live (HA-665's own mid-flow-switch case): "apply SL tomorrow" ->
        # "full day" -> "actually make it CL" ended up saving the reason as
        # "actually make it CL" and going straight to the confirmation card.
        # The type switch had already consumed one attempt, so the raw-text
        # fallback below fired on the very next turn. Resetting the counter
        # re-asks with the NEW type's examples, which is exactly what that
        # edge case asks for.
        if extracted.get("leave_type") and extracted["leave_type"] != had_leave_type_value:
            slots.pop("reason_attempts", None)

        attempts = slots.get("reason_attempts", 0) + 1
        if attempts == 1:
            slots["reason_attempts"] = attempts
            leave_slot_service.set_slots(company_id, conversation_id, slots)
            # Named type, so the examples can match it. Re-read from slots
            # each time rather than captured earlier: an employee who
            # switches type mid-conversation gets the new type's examples on
            # the next turn, which is what the story's mid-flow-switch case
            # asks for.
            _type_name = _display_leave_type_name(slots.get("leave_type"))
            _for_type = f" for your {_type_name}" if _type_name else ""
            return _finish(
                f"What's the reason{_for_type}?"
                f"{_reason_examples_for(slots.get('leave_type'))}"
            )
        # HA-666 edge case: a reply that is ONLY conversational filler ("my
        # reason is that", "I am applying because") strips to nothing, and
        # this used to fall through to storing the RAW text — so the filler
        # itself became the reason the manager read. The loop this guarded
        # against is real, so the second ask is reworded rather than removed:
        # it names what is missing instead of repeating the question, and the
        # attempt counter keeps rising so the wording stays put however many
        # times it takes. Nothing is ever saved unasked.
        slots["reason_attempts"] = attempts
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        # Replies ABOUT the examples, not failed reasons. QA: "Do you have
        # other reasons?" and "None of these fit" were both told "I couldn't
        # pick out a reason from that".
        if _MORE_REASONS_RE.search(query):
            more = _MORE_REASON_EXAMPLES_BY_SLUG.get(slots.get("leave_type") or "",
                                                     _MORE_REASON_EXAMPLES_FALLBACK)
            return _finish(f"A few more: {', '.join(more)}. Or just type the reason in your own words.")
        if _NONE_OF_THESE_RE.search(query):
            return _finish("No problem — just type the reason in your own words, whatever it is.")
        return _finish(
            "I couldn't pick out a reason from that. Please enter a valid reason "
            "for your leave request — just the cause itself is enough, like "
            "\"fever\" or \"personal work\"."
        )

    # ---- The reason must fit erp-api's limit ------------------------------
    # erp-api refuses a reason longer than MAX_LEAVE_REASON_LENGTH characters,
    # but only at submission - so the employee answered every question,
    # approved the reason, confirmed the card, and was then told the request
    # could not be applied. Checked here instead, on the exact text that
    # would be submitted and before the read-back or the card, so a long
    # reason is asked for again at the moment it is given. Every path to the
    # card passes this point: a first reason, an edit, a card amendment.
    if slots.get("reason") and len(slots["reason"]) > MAX_LEAVE_REASON_LENGTH:
        too_long = len(slots["reason"])
        logger.info("[Leave] reason is %s characters (limit %s) - asking for a shorter one",
                    too_long, MAX_LEAVE_REASON_LENGTH)
        slots["reason"] = None
        slots.pop("reason_confirmed", None)
        slots.pop("reason_confirm", None)
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish(
            f"Your reason is {too_long} characters long, but it can be at most "
            f"{MAX_LEAVE_REASON_LENGTH}. Please share a shorter reason for your leave."
        )

    # ---- The reason is read back for approval before anything is submitted
    # CEO review point 1: no AI-cleaned reason is saved without the employee
    # confirming it, and they must be able to edit it. Asked on EVERY
    # application, not only when a word was ambiguous — Helix has stripped
    # filler, fixed spelling and recapitalised by this point and the employee
    # has seen none of it.
    #
    # Asked LAST, once every other slot is settled, so it is one short
    # question immediately before the confirmation card rather than an
    # interruption mid-collection. Asked once per WORDING: every branch of
    # the reply handler above either sets reason_confirmed or clears it, and
    # the merge clears it whenever the reason itself changes — so an edit is
    # approved on its own terms and cannot loop.
    if slots.get("reason") and not slots.get("reason_confirmed"):
        as_typed = extracted.get("reason_uncertain_as_typed") or ""
        suggestion = extracted.get("reason_uncertain_suggestion") or ""
        # "offered" is the reason exactly as this question shows it - what a
        # "yes" to it means. See the reply handler.
        slots["reason_confirm"] = {"as_typed": as_typed, "suggestion": suggestion,
                                   "offered": slots["reason"]}
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        if as_typed and suggestion:
            # One word we genuinely could not read. Name it, rather than
            # showing a reason that still contains it as if it were settled.
            return _finish(
                f"Just to check — by \"{as_typed}\" did you mean \"{suggestion}\"? "
                f"Reply yes to use it, no to keep it as you wrote it, "
                f"or type the reason the way you'd like it to read."
            )
        return _finish(
            f"Just to confirm, did you mean \"{slots['reason']}\"? "
            f"Reply yes to use it, or type the reason the way you'd like it to read."
        )

    slots["step"] = "awaiting_confirmation"
    leave_slot_service.set_slots(company_id, conversation_id, slots)
    # Underscore-prefixed slots are Helix's own bookkeeping (the cached
    # abbreviation map) and are not part of the contract with the client —
    # kept off the card rather than shipped and ignored.
    confirmation_data = {
        **{k: v for k, v in slots.items() if not k.startswith("_")},
        "total_days": requested_days,
    }
    writer({"type": "leave_confirmation", "data": confirmation_data})
    # Short leave is part of one day, so "1.0 day(s) of short leave from X to
    # X" said neither what it is nor which half. Name the half instead.
    _half = {"first_half_day": "first half", "second_half_day": "second half"}.get(
        slots.get("session_type_slug"))
    if slots["leave_type"] == "short_leave" and _is_single_day(slots) and _half:
        _what = f"short leave on {slots['from_date']} ({_half})."
    else:
        _what = (f"{requested_days} day(s) of {slots['leave_type'].replace('_', ' ')} "
                 f"from {slots['from_date']} to {slots['to_date']}.")
    return _finish(
        f"{amend_note}To confirm: {_what}"
        f"{(' Reason: ' + slots['reason'] + '.') if slots.get('reason') else ''} "
        f"Shall I submit this request?",
        extra_data=confirmation_data,
    )