"""HEL-280 — Leave eligibility: answers "am I eligible for X leave?" as a
pure policy-qualification question, distinct from leave_balance (a quantity)
and leave_action_service's apply/status/cancel flows (which never reference
eligibility). Split out of hr_graph.py so that file stays graph orchestration
only, mirroring how leave_action_node already lives in leave_action_service.py.
"""

from __future__ import annotations

import asyncio
import difflib
import logging
import re
from datetime import date
from typing import Optional

from langgraph.types import StreamWriter

from schema.agent import HRState

import services.erp_client as erp_client
import services.leave_failure as leave_failure
from services.leave_action_service import _extract_leave_type_filters, _LEAVE_TYPE_CODES

logger = logging.getLogger(__name__)


# ── Node 5: Leave eligibility (HEL-280) ──────────────────────────────────────
# Answers "am I eligible for X leave?" — policy qualification only, never
# balance (AC#5: an employee with 0 days remaining is still policy-eligible).
# The single configured eligibility rule is erp-api's per-leave-type
# benefit_start: "joining" (available from day one) or "confirmation"
# (available only once probation is complete). Whether THIS employee is
# confirmed comes from erp-api's own is_confirmed flag rather than comparing
# today's date against probation_end_date — if confirmation is a separate
# step in their flow, date arithmetic here would disagree with what
# applyUsersLeave() enforces, and we'd tell someone they're eligible moments
# before their application is rejected.

# Leave types employees commonly ask about that have no policy configured in
# erp-api. Without this, "am I eligible for maternity leave?" matches nothing
# in _LEAVE_TYPE_FILTER_WORDS and falls through to the "which leave type did
# you mean?" clarification — which reads as the bot ignoring a question that
# named its leave type perfectly clearly. These resolve to the correct
# "that leave type isn't in your policies" answer instead.
_UNCONFIGURED_LEAVE_WORDS = {
    "maternity", "paternity", "sabbatical", "bereavement",
    "compassionate", "marriage", "adoption", "menstrual", "study",
}

# comp_off and leave_without_pay are quota-tracked (present in leave_quota)
# but have no leave_settings.leave_type[] entry, so no benefit_start rule
# exists to evaluate. Product direction, 2026-08-25: eligibility questions
# about these two get the same "Unsupported leave type" framing as a
# genuinely-unconfigured type (Maternity, Sabbatical, ...) rather than the
# distinct "no eligibility rule configured" wording — an explicit choice to
# keep the eligibility answer's vocabulary limited to "supported" vs "not
# supported", even though these two do still carry a real balance
# elsewhere (leave_balance/apply_leave are unaffected by this).
_UNSUPPORTED_FOR_ELIGIBILITY_SLUGS = {"comp_off", "leave_without_pay"}

# HEL-280's documented target for the eligibility question specifically —
# tighter than erp_client's shared client default (read=10.0), which exists
# for calls with no such SLA. See erp_client._request's timeout_seconds.
_ELIGIBILITY_TIMEOUT_SECONDS = 3.0


def _parse_flexible_date(value: Optional[str]) -> Optional[date]:
    """Parses a date value erp-api may not send as plain ISO — the same
    class of inconsistency _parse_bool_ish exists for on the boolean side.
    Tries, in order: ISO (date.fromisoformat on the first 10 chars, so an
    ISO datetime with time/timezone still works), YYYY/MM/DD (unambiguous
    slash variant), then DD-MM-YYYY / DD/MM/YYYY — day-first, matching this
    codebase's established convention for ambiguous numeric dates. Never
    guesses at MM/DD/YYYY. Returns None if nothing matches."""
    if not value:
        return None
    text = str(value).strip()
    try:
        return date.fromisoformat(text[:10])
    except ValueError:
        pass
    m = re.match(r"^(\d{4})/(\d{1,2})/(\d{1,2})$", text)
    if m:
        try:
            return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
        except ValueError:
            return None
    m = re.match(r"^(\d{1,2})[-/](\d{1,2})[-/](\d{4})$", text)
    if m:
        day, month, year = int(m.group(1)), int(m.group(2)), int(m.group(3))
        try:
            return date(year, month, day)
        except ValueError:
            return None
    return None


# A chat query can embed a DOJ claim in prose ("am I eligible for casual
# leave (doj = 2025-06-14)", "my date of joining is 14-06-2025") — never
# trusted as real employee data (that only ever comes from erp-api's own
# /leave/context, never from free text: letting a chat message edit a
# compliance-sensitive HR record would be a data-integrity hole, not a
# feature), but when it disagrees with the actual record, the reply says
# so explicitly instead of silently substituting the real value with no
# explanation, which reads as the system having ignored the question.
_DOJ_CLAIM_PATTERN = re.compile(
    r"\b(?:doj|date\s+of\s+joining|joining\s+date|joined\s+on)\b\s*(?:is|was|[:=])?\s*"
    r"(\d{4}[/-]\d{1,2}[/-]\d{1,2}|\d{1,2}[/-]\d{1,2}[/-]\d{4})",
    re.IGNORECASE,
)


def _extract_claimed_doj(query: str) -> Optional[str]:
    match = _DOJ_CLAIM_PATTERN.search(query)
    return match.group(1) if match else None


def _doj_mismatch_note(query: str, actual_doj: Optional[str]) -> Optional[str]:
    """None when the query names no DOJ, the claim is unparseable, or it
    already agrees with the real record — the note is only ever added when
    there's something concrete to correct."""
    claimed_raw = _extract_claimed_doj(query)
    if not claimed_raw:
        return None
    claimed = _parse_flexible_date(claimed_raw)
    actual = _parse_flexible_date(actual_doj)
    if not claimed or not actual or claimed == actual:
        return None
    return (
        f"The date of joining you mentioned ({_format_date(claimed_raw)}) doesn't match our "
        f"records — your recorded date of joining is {_format_date(actual_doj)}, which is what's "
        f"used below."
    )


def _tenure_label(doj: Optional[str], today: Optional[date] = None) -> Optional[str]:
    """'2025-06-14' -> '1 yr 2 mos'. Pure date arithmetic on erp-api's doj —
    unlike confirmation status, this is not a policy determination, so it is
    safe to compute here rather than asking erp-api for it."""
    start = _parse_flexible_date(doj)
    if not start:
        return None
    now = today or date.today()
    if start > now:
        return None
    months = (now.year - start.year) * 12 + (now.month - start.month)
    if now.day < start.day:
        months -= 1
    months = max(months, 0)
    years, rem = divmod(months, 12)
    parts = []
    if years:
        parts.append(f"{years} yr{'s' if years != 1 else ''}")
    if rem or not years:
        parts.append(f"{rem} mo{'s' if rem != 1 else ''}")
    return " ".join(parts)


def _format_date(value: Optional[str]) -> Optional[str]:
    """'2025-09-14' -> '14 Sep 2025' for the user-facing reason text."""
    if not value:
        return None
    parsed = _parse_flexible_date(value)
    if parsed:
        return parsed.strftime("%d %b %Y")
    return str(value)


def _ordinal_day(day: int) -> str:
    """14 -> '14th', 1 -> '1st', 22 -> '22nd'. The 11th-13th are irregular
    (never 'th' by the usual last-digit rule)."""
    suffix = "th" if 11 <= day % 100 <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(day % 10, "th")
    return f"{day}{suffix}"


def _display_doj(iso_date: Optional[str]) -> Optional[str]:
    """'2025-06-14' -> '14th June 2025' for the employee card, distinct from
    _format_date's '14 Sep 2025' used in reason text — doj is a one-off
    display fact here, not part of a sentence, so the fuller ordinal form
    reads better on its own."""
    if not iso_date:
        return None
    d = _parse_flexible_date(iso_date)
    if not d:
        return str(iso_date)
    return f"{_ordinal_day(d.day)} {d.strftime('%B %Y')}"


def _probation_countdown_label(probation_end_date: Optional[str], today: Optional[date] = None) -> Optional[str]:
    """'2026-11-01' (today=2026-08-25) -> '2 months remaining'. Preferably
    months, per the product ask — falls back to days once under a month
    away, so "ends in 12 days" doesn't round down to a meaningless "0
    months remaining". If the end date has already passed (a data lag —
    is_confirmed hasn't caught up to it yet), says so plainly instead of a
    negative countdown; this never overrides the is_confirmed verdict
    itself (see evaluate_eligibility's own comment on why not), it only
    describes the date honestly against today."""
    end = _parse_flexible_date(probation_end_date)
    if not end:
        return None
    now = today or date.today()
    if end <= now:
        return "already past this date"
    months = (end.year - now.year) * 12 + (end.month - now.month)
    if end.day < now.day:
        months -= 1
    if months >= 1:
        return f"{months} month{'s' if months != 1 else ''} remaining"
    days = (end - now).days
    return f"{days} day{'s' if days != 1 else ''} remaining"


def evaluate_eligibility(leave_type_cfg: dict, employee: dict) -> dict:
    """The ONLY place a leave eligibility rule is applied. Returns
    {eligible: bool|None, reason_code: str, reason: str, probation: bool},
    where eligible=None means "could not be determined" and must never be
    rendered as a verdict. `probation` reflects THIS employee's CURRENT
    status — True only when they are actually being denied for still being
    on probation (reason_code REQUIRES_CONFIRMATION); False whenever
    eligible is True, including a confirmation-gated type once probation
    has already been cleared. (Changed 2026-08-27 — previously reflected
    the type's policy shape (benefit_start == "confirmation") regardless of
    verdict, which read as "probation: true" even for an eligible,
    already-confirmed employee.)

    Deliberately pure (no I/O, no LLM): the story forbids the model from
    interpreting policy, and keeping every rule here means that when erp-api
    eventually exposes a decision endpoint, only this body changes — the node,
    the SSE contract and the tests all stay put."""
    slug = leave_type_cfg.get("slug") or ""
    name = leave_type_cfg.get("name") or slug.replace("_", " ").title() or "This leave type"
    benefit_start = str(leave_type_cfg.get("benefit_start") or "").strip().lower()

    if benefit_start == "joining":
        return {
            "eligible": True,
            "reason_code": "AVAILABLE_FROM_JOINING",
            "reason": f"{name} is available from your date of joining, so you are eligible for it.",
            "probation": False,
        }

    if benefit_start == "confirmation":
        # erp-api calls this rule "confirmation", but employees experience it
        # as the end of their probation period — that's the word on their
        # offer letter and in the HR portal. The user-facing text therefore
        # says "probation" throughout; only the machine-readable reason_code
        # keeps erp-api's vocabulary, so the frontend contract stays stable.
        # _parse_bool_ish, not a raw truthiness check: erp-api mixes real
        # JSON booleans and string-encoded ones across leave_settings/
        # context fields (is_carry_forward, back_date_leave_allow, ...),
        # and a bare `if employee.get("is_confirmed"):` would silently
        # treat the STRING "false" (or "0") as truthy — i.e. confirmed,
        # eligible — exactly backwards from an employee genuinely still on
        # probation. Bug found 2026-08-25 verifying this exact ticket.
        is_confirmed = _parse_bool_ish(employee.get("is_confirmed"))
        # None is NOT False: "we don't know" must fail closed, not deny.
        if is_confirmed is None:
            return {
                "eligible": None,
                "reason_code": "EMPLOYEE_DATA_UNAVAILABLE",
                "reason": f"{name} becomes available after your probation ends, but your "
                          f"probation status is unavailable right now.",
                "probation": False,
            }
        if is_confirmed:
            return {
                "eligible": True,
                "reason_code": "CONFIRMED",
                "reason": f"{name} becomes available after your probation ends. Your probation "
                          f"is complete, so you are eligible for it.",
                "probation": False,
            }
        until = _format_date(employee.get("probation_end_date"))
        countdown = _probation_countdown_label(employee.get("probation_end_date"))
        # Sprint 2 spec wording (Scenario B): names the end date AND says
        # plainly that eligibility follows once it passes, rather than
        # leaving the employee to infer that. Countdown kept as an extra
        # (not in the spec's example, but doesn't contradict it either).
        if until and countdown:
            tail = f" Your probation ends on {until} ({countdown}), after which you will become eligible."
        elif until:
            tail = f" Your probation ends on {until}, after which you will become eligible."
        else:
            tail = " You are still on probation."
        return {
            "eligible": False,
            "reason_code": "REQUIRES_CONFIRMATION",
            "reason": f"Employees currently under probation cannot apply for {name}.{tail}",
            "probation": True,
        }

    # Unrecognised or missing benefit_start — a rule we don't understand.
    # Fail closed rather than guess: a wrong "yes" here sends someone to apply
    # for leave they can't take.
    logger.warning("[Eligibility] Unrecognised benefit_start=%r for slug=%r", benefit_start, slug)
    return {
        "eligible": None,
        "reason_code": "RULE_NOT_UNDERSTOOD",
        "reason": f"I couldn't work out the eligibility rule for {name} — it doesn't look right on your company's side.",
        "probation": False,
    }


def _parse_bool_ish(value) -> Optional[bool]:
    """erp-api's leave_settings mixes real JSON booleans (is_carry_forward)
    with string-encoded ones elsewhere in the same payload (is_combine:
    "true", back_date_leave_allow: "1") — a plain `if value:` truthiness
    check is unsafe here because bool("false") is True in Python. Returns
    None (rather than guessing) for anything that isn't recognisably a
    boolean, so display code can omit the fact instead of showing it wrong."""
    if isinstance(value, bool):
        return value
    if value is None:
        return None
    text = str(value).strip().lower()
    if text in ("true", "1", "yes"):
        return True
    if text in ("false", "0", "no", ""):
        return False
    return None


def _parse_int_ish(value) -> Optional[int]:
    """quota/max_apply_in_month/oneTypeMax arrive as JSON numbers on some
    fields and numeric strings on others in the same payload."""
    if value is None:
        return None
    try:
        return int(str(value).strip())
    except (ValueError, TypeError):
        return None


def _policy_details(leave_type_cfg: dict) -> dict:
    """Entitlement/config facts about the leave TYPE itself, read from the
    same leave_settings entry evaluate_eligibility already has in hand — no
    extra erp-api call. Deliberately distinct from leave_quota (the
    employee's remaining balance), which this story must never read (AC 5):
    quota here is the policy's annual allotment ("how much do I get"), not
    what's left ("how much do I have"), so surfacing it does not blur that
    boundary. Display-only — never consulted by evaluate_eligibility, so it
    cannot influence the eligible/not-eligible verdict."""
    return {
        "quota": _parse_int_ish(leave_type_cfg.get("quota")),
        "max_apply_in_month": _parse_int_ish(leave_type_cfg.get("max_apply_in_month")),
        "one_type_max": _parse_int_ish(leave_type_cfg.get("oneTypeMax")),
        "is_carry_forward": _parse_bool_ish(leave_type_cfg.get("is_carry_forward")),
        "notice_period_applicable": _parse_bool_ish(leave_type_cfg.get("notice_period_applicable")),
        "salary_settlement": _parse_bool_ish(leave_type_cfg.get("salary_settlement")),
    }


def _policy_summary_sentence(policy: dict, leave_type_name: str = "leave") -> str:
    """Renders _policy_details into one prose sentence for the chat answer.
    Omits any fact erp-api didn't give a parseable value for, and omits
    booleans that are simply False (unremarkable defaults not worth stating).

    Names the actual leave type in each figure ("12 Casual Leaves a year")
    rather than the generic "days"/"applications" — clearer when someone is
    asking about one specific type, which is the only case this is used for
    (see the len(results) == 1 caller)."""
    def _counted(n) -> str:
        return f"{n} {leave_type_name}" if n == 1 else f"{n} {leave_type_name}s"

    parts = []
    if policy.get("quota") is not None:
        parts.append(f"you're entitled to {_counted(policy['quota'])} a year")
    if policy.get("max_apply_in_month") is not None:
        parts.append(f"up to {_counted(policy['max_apply_in_month'])} a month")
    if policy.get("one_type_max") is not None:
        parts.append(f"a maximum of {_counted(policy['one_type_max'])} per application")
    if policy.get("is_carry_forward"):
        parts.append("unused days carry forward")
    if policy.get("notice_period_applicable"):
        parts.append("a notice period applies")
    if policy.get("salary_settlement"):
        parts.append("it is settled in your final settlement if unused")
    if not parts:
        return ""
    if len(parts) == 1:
        return parts[0][0].upper() + parts[0][1:] + "."
    body = "; ".join(parts[:-1])
    return body[0].upper() + body[1:] + f"; and {parts[-1]}."


def _match_configured_leave_types(query: str, configured: dict) -> list[str]:
    """Matches the query against the ACTUAL leave types this company has
    configured (by slug or display name) — not just the hardcoded common-
    synonym list in _extract_leave_type_filters (casual/sick/earned/short/
    comp off/leave without pay). HA-160 gap (2026-08-25): a company that
    genuinely configures Paternity Leave (or any type outside that fixed
    list) could never have it recognised by name — "am I eligible for
    paternity leave?" always fell through to "not part of your company's
    leave policy" via _mentions_unconfigured_leave's hardcoded word list,
    even when the company's real erp-api data says otherwise. Checked in
    ADDITION to the hardcoded list, not instead of it, since that list also
    covers synonyms ("unpaid", "lwp") that don't literally appear in
    erp-api's own type name.
    """
    text = query.lower()
    matched = []
    for slug, cfg in configured.items():
        name = (cfg.get("name") or slug.replace("_", " ")).lower().strip()
        candidates = {
            name,
            name.removesuffix(" leave").strip(),
            slug.replace("_", " ").strip(),
            slug.removesuffix("_leave").replace("_", " ").strip(),
        }
        for candidate in candidates:
            if candidate and re.search(r"\b" + re.escape(candidate) + r"\b", text):
                matched.append(slug)
                break
    return matched


def _mentions_unconfigured_leave(query: str) -> Optional[str]:
    """Returns the leave word the employee actually named, so the reply can
    name it back ("Maternity leave is not...") instead of the vague "this
    leave type".

    Live bug repro: "show my meternity leave eligibity" — the typo'd
    "meternity" never matched the exact word list, so the query fell
    through to the ambiguous "please specify a leave type" clarification
    even though a type was clearly named, just misspelled. Falls back to a
    close-match per query token when the exact match finds nothing, so a
    real typo is still recognised.

    cutoff=0.75, not the difflib default of 0.6: swept empirically against
    both real typos and plausible false-positive words. 0.75 still catches
    heavier typos than a single edit (e.g. "metrenity" vs "maternity"
    scores 0.778 — a transposition plus a substitution) with zero false
    matches among unrelated query words ("eligibility", "show", "casual",
    "today"). Dropping further to 0.7 starts false-matching real English
    words that aren't typos at all — "material" and "maternal" both cross
    0.7 against "maternity", "paternal" against "paternity" — so 0.75 is
    the actual safe floor, not an arbitrary middle ground."""
    text = query.lower()
    for word in sorted(_UNCONFIGURED_LEAVE_WORDS):
        if re.search(r"\b" + word + r"\b", text):
            return word
    for token in re.findall(r"[a-z]+", text):
        close = difflib.get_close_matches(token, _UNCONFIGURED_LEAVE_WORDS, n=1, cutoff=0.75)
        if close:
            return close[0]
    return None


# Single word immediately before "leave"/"leaves" — deliberately narrow (not
# 2-3 words) to keep false positives rare: a wider window would swallow
# "what kind of leaves", "which leave types", "any kind of leaves" etc. as if
# they named a real type.
_GENERIC_LEAVE_MENTION_PATTERN = re.compile(r"\b([a-z]+)\s+leaves?\b", re.IGNORECASE)

# Grammar/question words and common English function words that can land
# directly before "leave(s)" without naming any real type — must never be
# misread as a type name. Bug found 2026-08-26: "check leave eligibility" /
# "show leave eligibility" (no possessive in between, unlike "check MY leave
# eligibility") matched "check"/"show" as if they were unrecognised type
# names; broader sweep then found the same failure for "can I take leave?"
# ("take"), "do I get leave?" ("get"), "give me leave eligibility" ("me"),
# "ask about leave eligibility" ("about"), and more. A single word
# immediately before "leave" is far more often a verb, pronoun, or
# preposition than an actual type name, so this list is deliberately broad:
# standard English closed-class words (pronouns, prepositions, articles,
# auxiliary/modal verbs) PLUS every verb this codebase's own leave-related
# phrasing already recognises elsewhere (_LEAVE_ELIGIBILITY_PATTERNS'
# take/get/avail/use, apply_leave's apply/book/request/raise) plus their
# plain-English synonyms (check/show/view/verify/confirm/explain/tell/
# know/find/give/ask/submit/need/want/grant/approve/allow). A real type
# name is essentially never one of these.
_GENERIC_LEAVE_MENTION_STOPWORDS = {
    # articles, quantifiers, determiners
    "a", "an", "any", "some", "this", "that", "these", "those", "the",
    "such", "all", "every", "no", "each", "either", "neither",
    "other", "another", "different", "certain", "many", "more", "most",
    "additional", "extra", "specific", "particular", "same", "own",
    # question/relative words
    "which", "what", "who", "whom", "whose", "when", "where", "why", "how",
    "kind", "type", "types", "of",
    # pronouns
    "i", "me", "my", "mine", "you", "your", "yours", "he", "him", "his",
    "she", "her", "hers", "it", "its", "we", "us", "our", "ours",
    "they", "them", "their", "theirs", "someone", "anyone", "everyone",
    # prepositions/conjunctions
    "for", "on", "to", "in", "at", "by", "with", "from", "about", "as",
    "and", "or", "but", "if", "so", "than", "then",
    # auxiliary/modal verbs
    "is", "am", "are", "was", "were", "be", "been", "being",
    "do", "does", "did", "done",
    "have", "has", "had", "having",
    "can", "could", "may", "might", "shall", "should", "will", "would", "must",
    # leave-related action verbs — the whole point of a query like "check
    # leave eligibility" or "can I take leave" is the ACTION, not a type
    "take", "taking", "get", "getting", "avail", "availing", "use", "using",
    "apply", "applying", "book", "booking", "request", "requesting",
    "raise", "raising", "submit", "submitting", "need", "needing",
    "want", "wanting", "check", "checking", "show", "showing", "view",
    "viewing", "see", "seeing", "verify", "verifying", "confirm",
    "confirming", "explain", "explaining", "tell", "telling", "know",
    "knowing", "find", "finding", "give", "giving", "ask", "asking",
    "grant", "granting", "approve", "approving", "allow", "allowing",
    "permit", "permitting", "require", "requiring", "let", "letting",
    # single-token forms of the real, already-recognised vocabulary
    # (_LEAVE_TYPE_FILTER_WORDS' real types) — must never be re-flagged a
    # second time by this more permissive fallback.
    "casual", "sick", "earned", "short", "comp", "off", "unpaid", "lwp",
    "without", "pay",
} | _UNCONFIGURED_LEAVE_WORDS


def _extract_unrecognised_leave_mention(query: str, configured: dict) -> Optional[str]:
    """Fallback for '<word> leave' phrasing outside BOTH this company's
    configured types AND the fixed _UNCONFIGURED_LEAVE_WORDS vocabulary —
    'medical leave', 'religious leave', any name Helix AI has never heard
    of. Without this, a type named in perfectly plain English but outside
    that closed list fell through to the ambiguous 'please specify a leave
    type' clarification — identical to a query naming no type at all, even
    though one was clearly named, just not one this portal recognises.
    Only called after _mentions_unconfigured_leave finds nothing, so it
    never overrides the fixed list's typo-tolerant matching."""
    for match in _GENERIC_LEAVE_MENTION_PATTERN.finditer(query):
        candidate = match.group(1).lower()
        if candidate in _GENERIC_LEAVE_MENTION_STOPWORDS:
            continue
        if any(candidate == (configured[s].get("name") or "").lower().split()[0] for s in configured):
            continue
        return candidate
    return None


# "what kind of leaves am I eligible for?" / "which leave types am I
# eligible for?" / "what am I eligible for?" — a genuine, answerable
# question about every configured type, not an ambiguous one. Checked only
# when no specific type was named (see leave_eligibility_node) — a query
# that already names one or more real types never reaches this. Answered
# briefly (just the codes) rather than the full per-type breakdown the
# explicit "show me all ... eligibility" phrasing below gets, since this
# phrasing reads like someone skimming for a quick answer, not asking for
# the full policy rundown.
_GENERAL_ELIGIBILITY_PATTERN = re.compile(
    r"\b(what|which)\b[\w\s']{0,10}?\b(kind|type)s?\s+of\s+leaves?\b[\w\s']{0,20}?\beligib"
    r"|\b(what|which)\b[\w\s']{0,10}?\bleaves?\s+types?\b[\w\s']{0,20}?\beligib"
    r"|\b(what|which)\s+leaves?\b[\w\s']{0,20}?\b(am|are)\s+i\s+eligib"
    r"|\bwhat\s+am\s+i\s+eligible\s+for\b",
    re.IGNORECASE,
)

# "show me all leave types eligibility" / "eligibility for all leaves" —
# a genuine, answerable question about every configured type (see
# all_types_mode below), same recognition condition as before; the
# response itself is no longer differently-detailed for this phrasing
# (see _consolidated_multi_type_response) — kept only for the "evaluate
# every configured type" trigger, not for message-formatting anymore.
_ALL_LEAVE_TYPES_DETAILED_PATTERN = re.compile(
    r"\ball\b[\w\s']{0,10}?\bleave\s*types?\b"
    r"|\ball\b[\w\s']{0,15}?\bleaves?\b[\w\s']{0,15}?\beligib"
    r"|\bevery\b[\w\s']{0,10}?\bleave\s*types?\b",
    re.IGNORECASE,
)

# Section headings for the consolidated multi-type response (product
# direction, 2026-08-27) — used both as the combined "title" field and as
# the lead-in for each section's sentence in the "answer" text itself, so
# a plain-text consumer still gets the same structure a UI would render
# under separate headings.
_TITLE_ELIGIBLE = "You're eligible for these leaves"
_TITLE_INELIGIBLE = "You're not eligible for these leaves"
_TITLE_UNSUPPORTED = "Access check failed"


def _join_names(names: list[str]) -> str:
    """['Casual Leave'] -> 'Casual Leave'; ['Casual Leave', 'Sick Leave'] ->
    'Casual Leave, and Sick Leave' — same Oxford-comma-for-two convention
    already used by `available_list`/`types_list` elsewhere in this file, so
    the title's phrasing matches the answer body's."""
    if not names:
        return ""
    if len(names) == 1:
        return names[0]
    return f"{', '.join(names[:-1])}, and {names[-1]}"


def _consolidated_multi_type_response(
    results: list[dict], not_in_policy_labels: list[str], no_rule_labels: list[str],
    available: list[str],
) -> tuple[str, str]:
    """Groups a multi-type eligibility query into up to three sections —
    eligible, not-yet-eligible (denied, always with its own reason and any
    probation end-date guidance), and access-check-failed (unsupported /
    not in this company's policy) — and renders ONE short title plus ONE
    short answer covering all of them, regardless of how many types or
    which mix of outcomes were involved.

    Product direction, 2026-08-27: asking about several types at once —
    whether a general "what am I eligible for?", an explicit "show me all
    leave types", or a compound list ("casual, sick, earned, short, comp
    off, and LWP") — used to get either a long per-type breakdown (a full
    sentence per type) or a bare "X: eligible. Y: not eligible." with no
    reasons for the denied half. Every such query now gets this same
    compact, titled format instead. A single real type mixed with an
    unsupported one ("casual and maternity leave?") also lands here, not
    in the single-type branch, since that's already a two-section case."""
    def _label(r: dict) -> str:
        leave_type = r["leave_type"]
        code = leave_type.get("leave_code")
        name = leave_type.get("name") or leave_type["slug"].replace("_", " ").title()
        return f"{name} ({code})" if code else name

    def _name(r: dict) -> str:
        leave_type = r["leave_type"]
        return leave_type.get("name") or leave_type["slug"].replace("_", " ").title()

    eligible = [r for r in results if r["eligible"] is True]
    ineligible = [r for r in results if r["eligible"] is False]
    undetermined = [r for r in results if r["eligible"] is None]

    # The title names the actual leave types involved ("You're eligible for
    # Sick Leave") rather than the generic "these leaves" the body text
    # below still uses — product feedback 2026-09-01: a title that doesn't
    # name the type read as the bot not having understood which leave was
    # asked about, especially for the (very common) single-section case.
    # Built as clauses joined into one flowing sentence, not headings, so a
    # three-section mix reads as prose instead of three stacked headers.
    title_clauses: list[str] = []
    parts: list[str] = []

    if eligible:
        names = ", ".join(_label(r) for r in eligible)
        parts.append(
            f"{_TITLE_ELIGIBLE}: {names}. (Note: this confirms policy eligibility based on "
            f"your role and tenure — it does not reflect your available leave balance.)"
        )
        title_clauses.append(f"You're eligible for {_join_names([_name(r) for r in eligible])}")
    if ineligible:
        reasons = " ".join(f"{_label(r)} — {r['reason']}" for r in ineligible)
        parts.append(f"{_TITLE_INELIGIBLE}: {reasons}")
        lead = "but not eligible for" if title_clauses else "You're not eligible for"
        title_clauses.append(f"{lead} {_join_names([_name(r) for r in ineligible])}")
    if undetermined:
        names = ", ".join(_label(r) for r in undetermined)
        parts.append(f"I couldn't determine eligibility for {names} right now.")
    if no_rule_labels:
        # Rare in practice (comp_off/leave_without_pay are pinned to the
        # unsupported bucket below instead — see
        # _UNSUPPORTED_FOR_ELIGIBILITY_SLUGS), kept for any future
        # quota-only slug erp-api might introduce. Not one of the three
        # named sections, so it adds no title of its own.
        subject = " and ".join(no_rule_labels) if len(no_rule_labels) <= 2 else ", ".join(no_rule_labels)
        pronoun = "it" if len(no_rule_labels) == 1 else "them"
        parts.append(
            f"{subject} {'has' if len(no_rule_labels) == 1 else 'have'} no eligibility rule "
            f"configured in your company's policy — you can request {pronoun} directly, subject to your balance."
        )
    if not_in_policy_labels:
        # Same "Unsupported leave type" wording every other branch uses
        # (standalone all-unsupported query, single-plus-unsupported mix,
        # ...) — QA's bug reports check this exact phrase, so the
        # consolidated section text above never replaces it, only the title
        # clause built alongside it does.
        supported_list = (
            f"{', '.join(available[:-1])}, and {available[-1]}" if len(available) > 1
            else (available[0] if available else "no leave types yet")
        )
        quoted = ", ".join(f"'{l}'" for l in not_in_policy_labels)
        parts.append(
            f"Helix AI currently supports {supported_list}. {quoted} "
            f"{'is' if len(not_in_policy_labels) == 1 else 'are'} not supported in this portal. "
            f"Please contact HR for assistance."
        )
        lead = "and for" if title_clauses else "For"
        title_clauses.append(
            f"{lead} {_join_names(not_in_policy_labels)} our access check failed as our Helix "
            f"HR currently supports only these {len(available)} leave type"
            f"{'s' if len(available) != 1 else ''}"
        )

    title = " ".join(title_clauses)
    if not_in_policy_labels:
        title += ". Please contact your HR for assistance."
    return title, " ".join(parts)


async def leave_eligibility_node(state: "HRState", writer: StreamWriter) -> dict:
    query = state["query"]
    bearer_token = state.get("bearer_token")
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    usage_events = list(state.get("usage_events", []))
    # Set once the real employee record is fetched below; None until then and
    # whenever the query names no conflicting DOJ, so every _finish() call
    # site — including the early erp-api-failure returns above it — is safe
    # to leave untouched (Python closures resolve this by name at call time,
    # not at def time, so the late assignment further down still applies).
    doj_note: Optional[str] = None

    def _finish(message: str, extra_data: Optional[dict] = None) -> dict:
        if doj_note:
            message = f"{doj_note} {message}"
        data = {"answer": message}
        if extra_data:
            data.update(extra_data)
        writer({"type": "done", "intent": "leave_eligibility", "is_hr": True,
                "data": data, "message": message, "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    writer({"type": "checking_eligibility", "message": "Checking your leave eligibility..."})

    # Both calls are independent; running them in series would put two erp-api
    # round trips on the critical path of a 3s SLA. The shared erp_client's
    # default timeout (read=10.0) exceeds that budget on its own, so both
    # calls override it explicitly rather than relying on the default.
    try:
        context_result, balance_result = await asyncio.gather(
            erp_client.get_leave_context(bearer_token, company_id=company_id,
                                         conversation_id=conversation_id,
                                         timeout_seconds=_ELIGIBILITY_TIMEOUT_SECONDS),
            erp_client.get_leave_balance(bearer_token, company_id=company_id,
                                         conversation_id=conversation_id,
                                         timeout_seconds=_ELIGIBILITY_TIMEOUT_SECONDS),
        )
    except erp_client.ErpApiUnauthorized:
        return _finish("Sorry, your session has expired — please log in again to continue.")
    except erp_client.ErpApiTimeout:
        return _finish("I couldn't reach the HR system in time to check your eligibility — please try again in a moment.")
    except erp_client.ErpApiUnavailable:
        return _finish("I'm unable to reach the HR system right now to check your eligibility — please try again shortly.")

    employee = context_result["body"].get("data") or {}
    doj_note = _doj_mismatch_note(query, employee.get("doj"))
    # leave_quota's remaining-balance NUMBERS are deliberately never read for
    # a verdict — AC#5 requires balance can never influence policy
    # eligibility. Its KEYS are read below, for a narrower, different
    # purpose: telling apart a real leave type that just has no eligibility
    # rule configured (comp_off, leave_without_pay — present here, absent
    # from leave_settings.leave_type[] entirely) from one this company
    # doesn't offer at all (maternity, sabbatical — absent from both). That
    # distinction is about which MESSAGE to show, never about whether an
    # actual policy-gated type is eligible.
    balance_data = balance_result["body"].get("data") or {}
    leave_quota = balance_data.get("leave_quota") or {}
    leave_settings = balance_data.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 _finish("I couldn't check your eligibility — your company's leave policy "
                       "information isn't available right now.")

    requested = list(dict.fromkeys(
        _extract_leave_type_filters(query) + _match_configured_leave_types(query, configured)))
    known = [s for s in requested if s in configured]
    # Slugs named directly (comp_off, leave_without_pay, ...) that erp-api
    # lists a quota for but has no policy entry for. Kept separate from
    # `named` below so a compound query mixing a configured and an
    # unconfigured type ("casual and comp off leave?") doesn't go quietly
    # answered-in-half when `known` is non-empty (see the tail note after
    # `results` is built).
    unresolved = [s for s in requested if s not in configured]
    named = _mentions_unconfigured_leave(query) or _extract_unrecognised_leave_mention(query, configured)

    available = [configured[s].get("name") or s.replace("_", " ").title() for s in configured]

    # "what kind of leaves am I eligible for?" / "show me all leave types
    # eligibility" — a genuine, answerable question about every configured
    # type, only recognised when no specific type (real or unconfigured)
    # was already named; a query that DOES name one always takes that more
    # specific path instead, regardless of also matching these patterns.
    all_types_mode = None
    if not requested and not named:
        if _ALL_LEAVE_TYPES_DETAILED_PATTERN.search(query):
            all_types_mode = "detailed"
        elif _GENERAL_ELIGIBILITY_PATTERN.search(query):
            all_types_mode = "brief"
    if all_types_mode:
        known = list(configured.keys())

    if not known:
        # A requested-but-not-configured type lands here for two DIFFERENT
        # reasons, but as of 2026-08-25 both get the SAME "Unsupported leave
        # type" message (product direction — see
        # _UNSUPPORTED_FOR_ELIGIBILITY_SLUGS above for why comp_off/
        # leave_without_pay are pinned to the unsupported bucket even though
        # erp-api does track a balance for them):
        #   1. erp-api tracks a balance for it (comp_off, leave_without_pay)
        #      but has no entry for it in leave_settings.leave_type[] at
        #      all — no eligibility RULE exists to check.
        #   2. Nothing at all knows about it (maternity, sabbatical) — a
        #      real leave type, just not one this company offers.
        no_rule = [
            s for s in requested
            if s in leave_quota and s not in _UNSUPPORTED_FOR_ELIGIBILITY_SLUGS
        ]
        unknown_slugs = [
            s for s in requested
            if s not in leave_quota or s in _UNSUPPORTED_FOR_ELIGIBILITY_SLUGS
        ]
        no_rule_labels = [s.replace("_", " ").title() for s in no_rule]
        unknown_labels = [s.replace("_", " ").title() for s in unknown_slugs]
        if named and not requested:
            unknown_labels = [f"{named.title()} Leave"]

        if no_rule_labels or unknown_labels:
            reason_parts = []
            if no_rule_labels:
                subject = " and ".join(no_rule_labels) if len(no_rule_labels) <= 2 else ", ".join(no_rule_labels)
                pronoun = "it" if len(no_rule_labels) == 1 else "them"
                reason_parts.append(
                    f"{subject} {'has' if len(no_rule_labels) == 1 else 'have'} no eligibility rule "
                    f"configured in your company's policy — you can request {pronoun} directly, "
                    f"subject to your balance."
                )
            if unknown_labels:
                # Live bug fix (staging, 2026-08-25): "Am I eligible for
                # Maternity Leave?" must clearly say the type isn't
                # supported, not a vague "I couldn't find X" — this is the
                # exact "Unsupported leave type" wording QA's bug report
                # checks for. Still fully dynamic — the supported-types list
                # is THIS company's real configured types (never a
                # hardcoded 4), so a company that genuinely configures
                # Paternity Leave still gets a real verdict for it via
                # _match_configured_leave_types and never reaches this
                # branch — only a truly unconfigured name lands here.
                supported_list = (
                    f"{', '.join(available[:-1])}, and {available[-1]}" if len(available) > 1
                    else (available[0] if available else "no leave types yet")
                )
                quoted = ", ".join(f"'{l}'" for l in unknown_labels)
                reason_parts.append(
                    f"Helix AI currently supports {supported_list}. {quoted} "
                    f"{'is' if len(unknown_labels) == 1 else 'are'} not supported in this portal. "
                    f"Please contact HR for assistance."
                )
            reason_text = " ".join(reason_parts)
            # A pure no-rule case (comp_off alone, say) gets its own code —
            # it isn't a policy rejection, there's simply nothing to check.
            # Any genuinely-unknown type in the mix keeps the existing code,
            # since that half of the message IS the not-in-policy case.
            reason_code = (
                "NO_ELIGIBILITY_RULE_CONFIGURED" if no_rule_labels and not unknown_labels
                else "LEAVE_TYPE_NOT_IN_POLICY"
            )
            # The unsupported-type wording above already names the
            # available types inline — a separate next_action would just
            # repeat the same list a second time. Only the pure no-rule
            # case (comp_off alone) still needs it spelled out separately.
            next_action = (
                f"The leave types available to you are: {', '.join(available)}."
                if no_rule_labels and not unknown_labels else None
            )
            # Configured types come from leave_settings, so naming this as the
            # reason reports policy data rather than interpreting a rejection.
            card = leave_failure.build_card(
                "leave_eligibility",
                leave_failure.local_failure(reason_text, reason_code),
                next_action=next_action,
            )
            writer({"type": "leave_failure", "data": card})
            extra_data = {"available_leave_types": available, **card}
            if unknown_labels:
                extra_data["title"] = f"Access check failed for {_join_names(unknown_labels)}"
            return _finish(
                f"{reason_text}{f' {next_action}' if next_action else ''}",
                # reason_code no longer needs setting here — build_card()
                # now surfaces the primary reason's code/badge_label at the
                # top level of `card` itself (**card below), so this stays
                # in sync automatically instead of being duplicated by hand.
                extra_data=extra_data,
            )
        types_list = (
            f"{', '.join(available[:-1])}, and {available[-1]}" if len(available) > 1
            else available[0]
        )
        return _finish(
            f"Sure — your company offers {len(available)} leave types: {types_list}. "
            f"From these, you can ask me about any leave eligibility you'd like to check.",
            extra_data={"reason_code": "LEAVE_TYPE_NOT_SPECIFIED",
                        "available_leave_types": available},
        )

    results = [{"leave_type": {"slug": slug, "name": configured[slug].get("name"),
                                "leave_code": _LEAVE_TYPE_CODES.get(slug)},
                "policy": _policy_details(configured[slug]),
                **evaluate_eligibility(configured[slug], employee)}
               for slug in known]

    # A compound query can name one configured type alongside one that isn't
    # ("casual and comp off leave?", "casual and maternity leave?"). `known`
    # only covers the configured half — without this, the unconfigured half
    # is silently dropped with no acknowledgement it was ever asked about,
    # which reads as Helix AI ignoring part of the question.
    #
    # `named` comes from the FIXED _UNCONFIGURED_LEAVE_WORDS list, so it
    # still fires for "paternity" even when this company genuinely HAS
    # paternity_leave configured (caught instead by
    # _match_configured_leave_types, landing it in `known`). Bug found
    # 2026-08-25 while verifying HA-160 Scenario A: without this guard, a
    # real "Paternity Leave: eligible" verdict got a contradictory "I
    # couldn't find Paternity Leave..." tail appended right after it.
    # Skipped whenever the same word is already answered by a real result.
    # Same split as the standalone branch above — comp_off/leave_without_pay
    # are pinned to the unsupported bucket regardless of their leave_quota
    # presence, per _UNSUPPORTED_FOR_ELIGIBILITY_SLUGS above.
    no_rule_labels = [
        s.replace("_", " ").title() for s in unresolved
        if s in leave_quota and s not in _UNSUPPORTED_FOR_ELIGIBILITY_SLUGS
    ]
    not_in_policy_labels = [
        s.replace("_", " ").title() for s in unresolved
        if s not in leave_quota or s in _UNSUPPORTED_FOR_ELIGIBILITY_SLUGS
    ]
    already_answered = named is not None and any(
        named in known_slug.replace("_", " ")
        or named in (configured.get(known_slug, {}).get("name") or "").lower()
        for known_slug in known
    )
    if named and not already_answered and f"{named.title()} Leave" not in not_in_policy_labels:
        not_in_policy_labels.append(f"{named.title()} Leave")

    employee_card = {
        "name": employee.get("name"),
        # "2025-06-14" -> "14th June 2025" — tenure_label below is computed
        # from erp-api's own raw doj (employee.get("doj")), not this
        # formatted value, so reformatting here doesn't affect that math.
        "doj": _display_doj(employee.get("doj")),
        "tenure_label": _tenure_label(employee.get("doj")),
        # erp-api's /leave/context now returns emp_no (e.g. "geo3") — the
        # real, human-readable employee code, same field cancel-leave's
        # employee identity block reads. No "EMP-" prefix (removed
        # 2026-08-27) — shown exactly as erp-api sends it.
        "emp_code": employee.get("emp_no"),
    }
    payload = {"results": results, "employee": employee_card}
    if not_in_policy_labels:
        payload["not_in_policy"] = not_in_policy_labels
    if no_rule_labels:
        payload["no_eligibility_rule"] = no_rule_labels

    # Undetermined is not a verdict — show the fallback, and emit no card, so
    # the UI can never render a half-answered eligibility result.
    if all(r["eligible"] is None for r in results):
        return _finish("I couldn't check your eligibility — some of your employee "
                       "information isn't available right now.")

    writer({"type": "leave_eligibility", "data": payload})

    title: Optional[str] = None
    if len(results) == 1 and not not_in_policy_labels and not no_rule_labels:
        # HA-160 Scenario A/B/C: a leading Eligible/Not Eligible verdict
        # word, ahead of the reason sentence — `eligible` is never None
        # here, the all-undetermined case already returned above.
        verdict_label = "Eligible" if results[0]["eligible"] else "Not Eligible"
        message = f"{verdict_label} — {results[0]['reason']}"
        # A single-type answer has room for the entitlement facts alongside
        # the verdict ("...eligible for it. You're entitled to 24 days a
        # year..."); a multi-type answer stays terse below so it doesn't
        # turn into a wall of text — the same facts are still on the card.
        result_leave_type = results[0]["leave_type"]
        type_name = result_leave_type.get("name") or result_leave_type["slug"].replace("_", " ").title()
        summary = _policy_summary_sentence(results[0]["policy"], type_name)
        if summary:
            message = f"{message} {summary}"
        # HA-160 Scenario D: an eligible verdict never implies anything
        # about remaining balance (AC#5) — said explicitly so an employee
        # at 0 days doesn't read "Eligible" as "I have days left".
        if results[0]["eligible"]:
            message += (
                " (Note: this confirms policy eligibility based on your role and tenure "
                "— it does not reflect your available leave balance.)"
            )
        # Names the actual leave type asked about ("You're eligible for Sick
        # Leave") rather than the generic _TITLE_ELIGIBLE/_TITLE_INELIGIBLE
        # phrasing — that generic form still backs the multi-type body text
        # in _consolidated_multi_type_response, just not this single-type
        # title, which is by far the most common eligibility query shape.
        title = (
            f"You're eligible for {type_name}" if results[0]["eligible"]
            else f"You're not eligible for {type_name}"
        )
    else:
        # Product direction, 2026-08-27: any query touching 2+ leave types
        # at once — a general "what am I eligible for?", an explicit "show
        # me all leave types", or a compound list ("casual, sick, earned,
        # short, comp off, and LWP") — gets ONE short, titled, consolidated
        # answer instead of a long per-type breakdown or a bare list of
        # verdict words with no reasons. A single real type mixed with an
        # unsupported one ("casual and maternity leave?") lands here too.
        title, message = _consolidated_multi_type_response(
            results, not_in_policy_labels, no_rule_labels, available)
    logger.info("[Graph] Eligibility complete | types=%s unresolved=%s", ",".join(known), ",".join(not_in_policy_labels))
    return _finish(message, extra_data={"title": title, **payload})
