import asyncio
import inspect
import logging
import os
import re
from datetime import datetime as _dt
from typing import Optional

from langgraph.graph import StateGraph, START, END
from langgraph.types import StreamWriter
try:
    from langgraph.types import RetryPolicy
except ImportError:  # LangGraph 0.2.x
    from langgraph.pregel import RetryPolicy
import httpx
from schema.agent import HRState
from services.nlp_service import (
    fold_holiday_typos,
    check_custom_guardrail, fast_classify, _looks_like_genuine_query, mentions_summary,
    is_chat_summary_request,
    _looks_like_eligibility_question, mentions_eligibility, is_policy_overview_request,
    extract_employee_lookup_target, requested_reply_language,
)
from services.chat_service import history_text
from services.punch_details import punch_details_node as punch_details_node_impl
from services.attendance import attendance_node as attendance_node_impl, _route_after_attendance, _build_attendance_date_extraction_prompt
import services.attendance as attendance_mod
from services.ownership_guard import ownership_guard_node as ownership_guard_node_impl, _route_after_ownership
from services.regularisation_node import (
    regularisation_node as regularisation_node_impl, REGULARIZATION_CONFIG,
    _build_regularisation_pending_hint, _loads_query_object,
    regularisation_eligibility_node as regularisation_eligibility_node_impl,
    _route_after_regularisation_eligibility,
)
from services.attendance_explain import attendance_explain_node as attendance_explain_node_impl
from services.classify_node import classify_node , _VALID_INTENT_LABELS
from services.safety_node import safety_node
from services import graph_checkpointer
from services import flow_interrupts
from langgraph.errors import GraphBubbleUp

from services.ai_service import (
    needs_live_search,
    LLM_TASK_MAX_TOKENS,
    _check_moderation,
    GENERAL_CHAT_SYSTEM_PROMPT,
    GENERAL_CHAT_WEB_SEARCH_PROMPT,
    _call_llm,
    _call_llm_stream,
    _extract_text,
    _safe_json_parse,
    _build_user_message,
    _get_fallback_redirect,
    _build_leave_slot_extraction_prompt,
    _build_date_range_extraction_prompt,
    extract_structured_date_fields,
    _normalize_usage,
    estimate_tokens,
    classify_intent_structured,
 
    INTENT_MODEL,
    ACTIVE_LLM_PROVIDER,
    HR_SYSTEM_PROMPT,
    POLICY_ANSWER_FORMAT,
    LLM_MAX_TOKENS,
    SMALL_TALK_TURN_INSTRUCTION,
)
import services.ai_service as ai_service
import services.live_info as live_info
import services.live_requests as live_requests
import services.compound_query as compound_query
import services.erp_client as erp_client
import services.race_rag_service as race_rag_service
import services.team_leave_filter as team_leave_filter
import services.access_notice as access_notice
import services.leave_slot_service as leave_slot_service
import services.regularisation_store as regularisation_store
import services.date_resolver as date_resolver
from services.shift_query import shift_query_node
from services.policy_draft import policy_draft_node as policy_draft_node_impl
from services.my_regularisation_view import my_regularisation_view_node
from services.regularisation_cancel import regularisation_cancel_node
import services.individual_report as individual_report
import services.permission_service as permission_service
from services.individual_report import (
    individual_report_node,
    leave_request_node,
    attendance_explanation_node,
)
import services.leave_approval as leave_approval
from services.leave_approval import leave_approval_node
import services.regularisation_approval as regularisation_approval
from services.regularisation_approval import regularisation_approval_node
import services.reporting_manager as reporting_manager
from services.complex_manager_router import (
    COMPLEX_MANAGER_INTENTS,
    route_complex_manager_task,
    log_task_routed,
)
import services.date_query_resolver as date_query_resolver
import services.leave_history_clarify_state as leave_history_clarify_state
import services.leave_cancel_state as leave_cancel_state
import services.leave_disambiguation_state as leave_disambiguation_state
from services.leave_action_service import (
    leave_action_node as leave_action_node_impl,
    # Both of these are pure helper functions with their own direct unit
    # tests (TestMatchKnownLeaveType / TestQueryNeedsRelativeDateScrutiny in
    # test_leave_action.py) written against hr_graph._match_known_leave_type
    # / hr_graph._query_needs_relative_date_scrutiny — kept re-exported here
    # for that reason alone, same as erp_client/_call_llm/etc. above. The
    # real implementations (and their actual call sites) live in
    # leave_action_service.py; this module never calls either itself.
    _looks_like_leave_policy_question,
    _names_only_a_leave_type,
    _resolve_leave_history_clarification,
    _rewrite_query_for_history_clarify_resolution,
    _match_known_leave_type,
    _query_needs_relative_date_scrutiny,
    # The apply-vs-cancel "cancel" split. Imported rather than reimplemented
    # so routing here and execution in leave_action_service.py decide it from
    # exactly the same predicates — the two disagreeing is what produced the
    # mixed-intent bugs these guard against (see classify_node below).
    _is_declining_or_cancelling,
    _is_cancel_card_button,
    cancel_phrase_targets_submitted_request,
)
from services.leave_eligibility_service import (
    leave_eligibility_node as leave_eligibility_node_impl, evaluate_eligibility, _tenure_label, _probation_countdown_label,
    _parse_bool_ish, _parse_int_ish, _policy_details, _policy_summary_sentence,
    _ELIGIBILITY_TIMEOUT_SECONDS, _parse_flexible_date, _format_date, _display_doj,
    _extract_claimed_doj, _doj_mismatch_note, _mentions_unconfigured_leave,
    _extract_unrecognised_leave_mention,
)
from services import slot_store
logger = logging.getLogger(__name__)
import services.date_resolver as date_resolver

logger = logging.getLogger(__name__)

# Plain-name aliases for the nodes that live in their own modules and are
# imported here under an _impl name. build_hr_graph registers the _impl
# reference, but this module's own docs and the test suites refer to these
# nodes by their bare names (tests/test_leave_eligibility.py's own module
# docstring cites "services/hr_graph.py::leave_eligibility_node", and its
# tests both call and monkeypatch that attribute). The rename to _impl left
# no alias behind, so every one of those references raised AttributeError.
#
# Aliases rather than a second definition on purpose: one implementation with
# two spellings, so these cannot drift apart the way the duplicated classifier
# in this file already has.
leave_eligibility_node = leave_eligibility_node_impl
punch_details_node = punch_details_node_impl
attendance_explain_node = attendance_explain_node_impl
attendance_node = attendance_node_impl
regularisation_node = regularisation_node_impl

# What Helix AI can ACTUALLY do, in one line, in the order an employee is
# most likely to want it. The old redirect advertised "payroll, recruitment,
# hiring, compliance, employee relations" — none of which is a flow this
# graph has a node for — so someone who took it at its word asked a second
# question that got redirected too. These are the real ones: apply/cancel
# leave (leave_action_node), balance (leave_balance), eligibility
# (leave_eligibility_node), policies (hr_response_node), attendance
# (attendance_node), punch times (punch_details_node), shift
# (shift_query_node), regularization (regularisation_node).
_EMPLOYEE_CAPABILITIES = (
    "help you apply for or cancel leave, check your leave balance, eligibility or leave "
    "policies, look up your attendance, punch times and shift, or raise an attendance "
    "regularization"
)
# Only ever appended for a caller erp-api has confirmed is a manager — see
# manager_gate_node. Offering a non-manager an approval queue they'll be
# refused at is worse than not mentioning it.
_MANAGER_CAPABILITIES = (
    ", and on the manager side review or act on your team's leave and regularization requests"
)

#: Merged pool. Each entry is the two VARYING halves of one redirect - the
#: opener and the closing invitation - taken from the original whole-message
#: pool. The part that used to sit between them, each entry's own
#: hand-written list of HR areas, is gone: it is now injected at call time
#: from one accurate source, so the variety survives without five separate
#: chances for the capability list to drift.
#:
#: Order is unchanged from both predecessors, so the hash-to-index pick keeps
#: landing on the same-numbered line for a given query.
_NON_HR_FALLBACKS = [
    ("That's outside my area — I'm Helix AI, your HR assistant.",
     "Ask me about any of those and I'll get you sorted."),
    ("I only cover HR and workforce topics, so I'll have to pass on that one.",
     "If you have a question on any of those, I'm here to help."),
    ("My expertise is HR — that one's outside it.",
     "That's exactly what I'm here for — what would you like to do?"),
    ("That's not something I can help with; I focus purely on HR.",
     "Try me on any of those. What do you need?"),
    ("I specialise in HR only, so that one isn't mine to answer.",
     "Ready when you are — what would you like to do?"),
]

# Both predecessors, kept rather than deleted.
#
# 1. The original whole-message pool. Its per-entry lists named payroll,
#    recruitment, hiring, compliance and employee relations, none of which
#    this graph has a node for - so an employee who took the list at its
#    word asked a follow-up and was redirected all over again. non_hr_node's
#    own LLM prompt forbids exactly those words on the primary path, so the
#    pool contradicted the path it was the fallback for.
#
# _NON_HR_FALLBACKS = [
#     "That's outside my area — I'm an HR specialist. Ask me about leave policies, payroll, recruitment, or compliance and I'll get you sorted.",
#     "I only cover HR and workforce topics. If you have questions on compensation, onboarding, performance, or employee benefits, I'm here to help.",
#     "My expertise is HR only. Feel free to ask about leave policies, payroll, hiring, or employee management — that's exactly what I'm here for.",
#     "That's not something I can help with — I focus purely on HR topics. Try me on attendance, compliance, recruitment, or employee relations.",
#     "I specialise in HR only. Questions on workforce management, payroll, benefits, or compliance? I'm ready.",
# ]
#
# 2. The split-opener version that replaced it. Its openers are carried into
#    the merged pool above verbatim; what it lost, and the merge restores,
#    is the per-entry closing invitation.
#
# _NON_HR_OPENERS = [
#     "That's outside my area — I'm Helix AI, your HR assistant.",
#     "I only cover HR and workforce topics, so I'll have to pass on that one.",
#     "My expertise is HR — that one's outside it.",
#     "That's not something I can help with; I focus purely on HR.",
#     "I specialise in HR only, so that one isn't mine to answer.",
# ]
_OTHER_PEOPLE_RE = re.compile(
    r"\b(everyone|everybody|all\s+(employees|staff|team|colleagues)|others|other\s+employees|colleagues|team\s+members|someone\s+else|another\s+employee|their\s+attendance|their\s+punch)\b",
    re.IGNORECASE,
)
_MANAGER_RE = re.compile(r"\b(my\s+manager|manager's|my\s+boss|boss's|manager|boss)\b", re.IGNORECASE)
_REG_MID_FLOW_CONTINUATION_RE = re.compile(
    r"\b(confirm|proceed|submit)\b|\bgo\s+ahead\b|^\s*(yes|yeah|yep|sure|ok(?:ay)?)\b",
    re.IGNORECASE,
)

# The mid-flow regularisation shape tests moved to their own module so
# classify_node can use them too — it runs the live classifier and needs
# the same guard, but cannot import from here (this module imports
# classify_node, so the dependency only runs one way). Re-exported rather
# than just moved: tests/test_regularisation_mid_flow_routing.py and
# tests/test_regularisation_other_topic_interruption.py import both names
# from services.hr_graph.
from services.regularisation_guards import (  # noqa: F401 — re-exported
    _REG_TIME_RANGE_RE,
    _REG_REASON_WORDING_RE,
    _REG_ENTRY_CORRECTION_RE,
    _OTHER_TOPIC_WORD_RE,
    _looks_like_regularisation_entry_content,
    _looks_like_other_hr_topic,
)

_BARE_APPLY_RE = re.compile(
    r"^\s*(i\s+(?:want|need)\s+to\s+|i'd\s+like\s+to\s+|can\s+i\s+)?apply(\s+for)?\s*[.!?]?\s*$",
    re.IGNORECASE,
)

def _detect_bare_apply_query(query: str) -> bool:
    return bool(_BARE_APPLY_RE.match(query.strip()))

def _helix_capability_line(state: dict) -> str:
    """The "here's what I CAN do" half of a non-HR redirect.

    Manager extras only when erp-api has actually confirmed the caller is one
    — state["is_manager"] is also set to individual_report.MANAGER_UNKNOWN
    when the lookup failed, which `is True` deliberately excludes."""
    capabilities = _EMPLOYEE_CAPABILITIES
    if state.get("is_manager") is True or state.get("is_manager_jwt"):
        capabilities += _MANAGER_CAPABILITIES
    return f"I can {capabilities}."


def _in_progress_nudge(state: dict) -> str:
    """"You've still got a leave application open" — appended when the
    off-topic message arrived in the MIDDLE of a flow.

    Without it the redirect reads as though the half-finished application
    never existed, and the employee has no way to know it is still waiting.
    Both stores fail closed to None (no Redis, no mid-flow state), so this
    simply adds nothing when there is nothing to say."""
    company_id, conversation_id = state.get("company_id"), state.get("conversation_id")
    if not conversation_id:
        return ""
    leave_slots = leave_slot_service.get_slots(company_id, conversation_id) or {}
    if leave_slots.get("step") in ("collecting", "awaiting_confirmation"):
        return " Your leave application is still open, by the way — say \"continue\" and we'll pick it up."
    reg_slots = regularisation_store.get_slots(company_id, conversation_id) or {}
    if reg_slots.get("step") in ("collecting", "awaiting_confirmation"):
        return " Your regularization request is still open, by the way — say \"continue\" and we'll pick it up."
    return ""


# Both predecessors of the function below, kept rather than deleted.
#
# 1. The original: same hash pick, but it returned a whole canned message
#    from the pool and interpolated a "{topic}" label built from the query.
#    No entry ever contained "{topic}", so the label and the .replace() were
#    dead weight; the merge drops both.
#
# def _get_fallback_redirect(query: str) -> str:
#     import hashlib
#     idx = int(hashlib.md5(query.lower().encode()).hexdigest(), 16) % len(_NON_HR_FALLBACKS)
#     words = [w for w in query.split() if len(w) > 3]
#     topic = " ".join(words[:3]) if words else "that topic"
#     return _NON_HR_FALLBACKS[idx].replace("{topic}", topic)
#
# 2. The split-opener version, which added the state-aware capability line
#    and the mid-flow nudge. The merge keeps both of those.
#
# def _get_fallback_redirect(query: str, state: Optional[dict] = None) -> str:
#     import hashlib
#     state = state or {}
#     idx = int(hashlib.md5(query.lower().encode()).hexdigest(), 16) % len(_NON_HR_OPENERS)
#     return (f"{_NON_HR_OPENERS[idx]} {_helix_capability_line(state)}"
#             f"{_in_progress_nudge(state)} What would you like to do?")


def _get_fallback_redirect(query: str, state: Optional[dict] = None) -> str:
    """One redirect, assembled from both flows.

    From the original pool: a varied opener and that opener's own closing
    invitation, picked by the same hash-to-index so one topic always gets one
    message. From the version that replaced it: the capability sentence built
    for THIS caller (manager extras only when erp-api confirmed it) and the
    mid-flow nudge, so an off-topic message sent in the middle of a leave
    application still says the application is waiting.

    `state` stays optional so the query-only call shape keeps working; it
    then yields the employee-level line with no nudge.
    """
    import hashlib
    state = state or {}
    idx = int(hashlib.md5(query.lower().encode()).hexdigest(), 16) % len(_NON_HR_FALLBACKS)
    opener, invitation = _NON_HR_FALLBACKS[idx]
    return (f"{opener} {_helix_capability_line(state)}"
            f"{_in_progress_nudge(state)} {invitation}")
async def ownership_guard_node(state: dict, writer: StreamWriter) -> dict:
    """Pre-classify node: detect queries that clearly request OTHER
    employees' attendance/punch data and block them with a polite message.

    If the query mentions a manager/boss, allow it to proceed only when
    the caller has a privileged role — otherwise deny it here to avoid
    routing to the graph and LLM.
    """
    query = state.get("query", "") or ""
    bearer = state.get("bearer_token")

    # Prefer provider-backed classification (OpenAI) for robust detection
    # of whether the user asks about themselves or others. Falls back to
    # deterministic regex when OpenAI isn't the active provider.
    labels = frozenset({"self", "other", "group", "manager", "unknown"})
    prompt = (
        "You are classifying the INTENT of a workplace query about attendance/punch data.\n"
        "Categories:\n"
        "- self: the user is asking about their OWN attendance (no other name/employee mentioned, "
        "uses 'my', 'me', 'I', or no subject at all)\n"
        "- other: the user names or clearly refers to ONE specific other employee (by name or "
        "explicit reference like 'John's attendance')\n"
        "- group: the user asks about multiple employees, a team, department, or 'all employees'\n"
        "- manager: the user asks about their manager's/boss's attendance\n"
        "- unknown: intent cannot be determined\n\n"
        "IMPORTANT: If no employee name is mentioned and no group/manager keywords appear, "
        "default to 'self'.\n\n"
        "Examples:\n"
        "Query: 'give me attendance for last week' -> {\"intent\": \"self\"}\n"
        "Query: 'show my punch details for July' -> {\"intent\": \"self\"}\n"
        "Query: 'what is John's attendance this month' -> {\"intent\": \"other\"}\n"
        "Query: 'attendance for the sales team' -> {\"intent\": \"group\"}\n"
        "Query: 'when did my manager clock in yesterday' -> {\"intent\": \"manager\"}\n\n"
        "Respond ONLY with JSON: {\"intent\": \"self|other|group|manager|unknown\"}.\n"
        f"Current query: {query}"
    )

    try:
        label, usage, _ = await classify_intent_structured(prompt, labels, fallback_label="unknown")
    except Exception as e:
        logger.warning(f"[Guard] ownership classifier failed: {e}")
        label = "unknown"

    # Block or allow based on label
    if label in ("other", "group"):
        writer({
            "type": "guardrail",
            "stage": "input",
            "status": "failed",
            "categories": ["privacy"],
            "message": "Sorry, I can only share attendance details for your own account — for someone else's, please check with HR or your manager.",
        })
        return {"blocked": True}

    if label == "manager":
        # Allow only if caller is privileged
        try:
            claims = attendance_mod._decode_jwt_claims(bearer)
            role = claims.get("role") or claims.get("roles") or claims.get("role_id")
            roles = role if isinstance(role, (list, set, tuple)) else [role]
            if any(r is not None and str(r).strip().lower() in attendance_mod.PRIVILEGED_ROLES for r in roles):
                return {"blocked": False}
        except Exception:
            pass
        writer({
            "type": "guardrail",
            "stage": "input",
            "status": "failed",
            "categories": ["privacy"],
            "message": "Sorry, I can only share attendance details for your own account — for someone else's, please check with HR or your manager.",
        })
        return {"blocked": True}

    # self or unknown → continue to classification (unknown is allowed to proceed)
    return {"blocked": False}


def _route_after_ownership(result: dict) -> str:
    """Routes to END when ownership guard blocked, otherwise to classify_node."""
    if result.get("blocked"):
        return END
    return "classify_node"

# ── Manager gate (runs ahead of classification) ──────────────────────────────

async def manager_gate_node(state: HRState, writer: StreamWriter) -> dict:
    """Decide whether the caller is a manager, before anything looks at what
    they asked.

    Ordering is the point: the individual-report feature must know "is this
    person allowed to ask about a colleague at all" before it spends a call
    deciding WHICH kind of colleague question this is. Putting the gate ahead
    of classify_node also means a non-manager never reaches the sub-intent
    classifier, so the role check cannot be skipped by any future routing
    change.

    Two properties this node must have, because it is now on the path of
    EVERY message:

    1. It never blocks. An erp-api outage must not break "what is the sick
       leave policy" — a question with no permission dimension at all. On
       failure it records MANAGER_UNKNOWN and lets the graph continue; only
       the individual-report nodes care, and they refuse rather than guess.
    2. It costs at most one round trip per conversation. A JWT that carries
       a manager role claim needs none at all; otherwise the answer is
       cached per conversation (it is a property of the caller, not of the
       question, and cannot change mid-conversation).
    """
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")

    # is_hr rides along with is_manager because erp-api answers both in ONE
    # response and the role question is the same question. It is NOT the
    # state's `is_hr`, which means "the QUERY is HR-related" — a completely
    # different thing that happens to share a word, hence is_hr_role. Read by
    # shift_query_node's permission gate: an HR caller sees a team member's
    # shift on the same footing as a manager.
    #
    # A JWT that names the role still short-circuits the round trip, but it
    # can only answer the manager half (is_manager_role's value set covers
    # the HR role names too, so an "hr" token resolves to is_manager=True
    # here, which is the same ALLOW). is_hr_role stays unresolved in that
    # case rather than being guessed at — nothing reads it as a DENY.
    if state.get("is_manager_jwt"):
        return {"is_manager": True,
                "is_hr_role": leave_slot_service.get_hr_flag(company_id, conversation_id)}

    cached = leave_slot_service.get_manager_flag(company_id, conversation_id)
    cached_hr = leave_slot_service.get_hr_flag(company_id, conversation_id)
    if cached is not None:
        logger.info("[ManagerGate] cached is_manager=%s is_hr=%s", cached, cached_hr)
        return {"is_manager": cached, "is_hr_role": cached_hr}

    try:
        context_result = await erp_client.get_leave_context(
            state.get("bearer_token"), company_id=company_id, conversation_id=conversation_id,
        )
    except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable) as e:
        # Deliberately not an error on the state: ordinary HR chat carries on.
        logger.warning("[ManagerGate] erp-api unreachable (%s) - manager status unknown", type(e).__name__)
        return {"is_manager": individual_report.MANAGER_UNKNOWN,
                "is_hr_role": individual_report.MANAGER_UNKNOWN}

    context_data = context_result["body"].get("data") or {}
    is_manager = bool(context_data.get("is_manager", False))
    is_hr = bool(context_data.get("is_hr", False))
    leave_slot_service.set_manager_flag(company_id, conversation_id, is_manager)
    leave_slot_service.set_hr_flag(company_id, conversation_id, is_hr)
    logger.info("[ManagerGate] erp is_manager=%s is_hr=%s (cached for this conversation)",
                is_manager, is_hr)
    return {"is_manager": is_manager, "is_hr_role": is_hr}


# ── Shared intent helpers ─────────────────────────────────────────────────────
#
# The classifier itself lives in services/classify_node.py — the module the
# graph actually registers as "classify_node" (see build_hr_graph). A second,
# complete copy of it used to live right here: the sprint-1-2-3 / sprint-4
# merge kept BOTH and wired only the classify_node.py one, so this copy's ten
# manager/shift labels sat unreachable while _route_after_classify below
# happily routed to nodes the live classifier could never name. Every
# sprint-4 feature was dead on arrival as a result.
#
# Re-exported rather than redefined so there is exactly one taxonomy to keep
# in sync, and so tests reaching for hr_graph._build_intent_prompt /
# _is_leave_approval_query / _is_shift_lookup_query keep resolving.
# _VALID_INTENT_LABELS already arrives via the line-17 import — the old copy
# below it was shadowing that import, which is what let the two drift apart.
import services.classify_node as classify_node_mod
from services.classify_node import (  # noqa: F401  — re-exported for tests
    _build_intent_prompt,
    _is_leave_approval_query,
    _is_shift_lookup_query,
)

# hr_graph.classify_node stays a valid name because tests reach for it, but it
# now points at the ONE classifier the graph actually runs. Previously this
# name resolved to the local duplicate above — so those tests were exercising
# dead code that no request ever reached, which is precisely how the copy was
# able to drift out of sync unnoticed.
# classify_node = classify_node_impl

# Same reasoning for the nodes that live in their own modules and are imported
# here under an _impl alias: the graph registers the alias, but the test suites
# and this module's own docs refer to them by their plain names. Aliasing keeps
# one implementation with two spellings rather than inviting a second copy.
leave_eligibility_node = leave_eligibility_node_impl
punch_details_node = punch_details_node_impl
attendance_explain_node = attendance_explain_node_impl
attendance_node = attendance_node_impl
regularisation_node = regularisation_node_impl
ownership_guard_node = ownership_guard_node_impl
leave_action_node = leave_action_node_impl

_HR_CONTEXT_SIGNALS = {
    "salary", "leave", "payroll", "recruitment", "hiring", "benefits",
    "performance", "attendance", "onboarding", "training", "compliance",
    "hr", "employee", "appraisal", "compensation", "policy", "interview",
    "job", "skills", "experience", "developer", "manager", "role",
    "kpi", "pip", "bonus", "increment", "allowance", "insurance",
    "termination", "grievance", "induction", "timesheet", "shift","regularisation",
    # Punch-details vocabulary. Its absence was load-bearing by accident: a
    # punch conversation only counted as HR context because the answer
    # happens to contain "shift" ("Shift: General-Shift (09:00-18:30)"),
    # and punch_details only emits that line when erp-api returns a shift.
    # A no-punch-records day emits none — "No punch records found for
    # 2026-08-18." matches nothing above, so has_hr_context went False and
    # a follow-up to it was treated as a brand-new off-topic question.
    "punch", "check in", "check-in", "checked in", "check out", "check-out",
    "work hours", "working hours",
}

_NON_HR_TRIGGERS = {"weather", "sport", "recipe", "cook", "game", "movie", "music", "news"}


def _context_has_hr_signal(recent: list) -> bool:
    text = " ".join(m.get("content", "") for m in recent).lower()
    return any(signal in text for signal in _HR_CONTEXT_SIGNALS)


def _is_bare_date_fragment(query: str, has_date_expression: bool) -> bool:
    """True when `query` is a date reference and nothing else — the shape a
    follow-up takes when it re-targets an earlier date-driven lookup at a
    different day ("4th Wednesday of August 2026", "26 august", "last
    friday").

    Consults BOTH date layers on purpose. has_date_expression comes from
    date_resolver (the leave side's), which does not recognize every
    attendance phrasing — confirmed: it returns False for a bare "last
    friday", which is exactly the kind of follow-up this needs to catch.
    date_query_resolver is the attendance family's own resolver and covers
    those, so either one recognizing the phrase is enough.
    """
    if has_date_expression:
        return True
    try:
        return date_query_resolver.resolve(query, _today_in_app_timezone()) is not None
    except Exception:
        return False


def _build_intent_prompt(
    query: str, recent: list, has_hr_context: bool,
    awaited_slot_description: Optional[str] = None,
    pending_flow_hint: str = "",
) -> str:
    context_block = ""
    if recent:
        lines = [
            f"{m.get('role', 'user').upper()}: {m.get('content', '')[:200]}"
            for m in recent
        ]
        context_block = (
            "Recent conversation (read this to understand follow-up queries — "
            "do NOT classify these lines, classify only the Current Query below):\n"
            + "\n".join(lines)
            + "\n\n"
        )

    followup_directive = ""
    if has_hr_context:
        followup_directive = (
            "NOTE: The conversation above is HR-related. "
            "If the current query is a SHORT follow-up or refinement of an earlier HR question "
            "(e.g. adding a country, date, or clarification), classify it as the matching HR intent. "
            "But if the current query is a NEW, clearly off-topic question — classify it as non_hr regardless of prior context.\n\n"
        )

    # Without this, a bare, context-free reply mid-flow (e.g. "vocation" as
    # an answer to "what's the reason for this leave request?") reads to a
    # general-purpose classifier as an off-topic word and comes back
    # non_hr — silently discarding the whole in-progress application. Telling
    # it exactly what question it's judging the reply against fixes the
    # blind guess without weakening genuine-interruption detection: a real
    # topic switch ("generate a jd for ai engineer") still doesn't look like
    # a plausible answer to "what dates would you like," so the "unmistakably
    # a new question" escape hatch still lets it through.
    awaited_directive = ""
    if awaited_slot_description:
        awaited_directive = (
            "CRITICAL CONTEXT: The user has an in-progress leave application. "
            f"The assistant's last message was asking them for: {awaited_slot_description}. "
            "If the CURRENT USER QUERY could plausibly be answering that — even "
            "a single word, a date, or an odd/unclear reply — classify it as "
            "apply_leave.\n"
            "EXCEPTION: if the query names a DIFFERENT concrete HR action or object — "
            "e.g. cancelling/withdrawing a leave, checking leave status, punch/attendance "
            "details, regularisation, leave policy/eligibility/balance questions, or any "
            "clearly off-topic request — classify it under THAT intent instead, even "
            "though it arrives mid-flow. Only fall back to apply_leave when the query "
            "genuinely contains no other identifiable intent (bare words, dates, "
            "fragments, unclear text).\n\n"
        )

    return f"""You are a strict intent classifier for Helix AI — an HR-only assistant.

Classify the CURRENT USER QUERY into exactly one label.

Conversational intents (always HR-side — never non_hr):
  greeting             — hi, hello, hey, good morning, how are you, how's it going
  small_talk           — thanks, great job, you're helpful, bye
  capabilities_inquiry — what can you do, what do you help with, tell me about yourself,
                         are you a bot/AI/real person, what's your name
  conversation_meta    — about THIS CHAT itself: my last query, what did I ask, summarize
                         our conversation. NEVER their own HR records — "show my leave
                         application history" is leave_status (their leave records), not
                         conversation_meta, even though it contains the word "history".

HR domain intents (must relate directly to managing employees or workplace policies):
  leave_balance        — asking about THEIR OWN remaining/available leave days (e.g.
                         "what's my leave balance", "how many sick leaves do I have left")
  apply_leave          — wanting to APPLY FOR / BOOK / REQUEST leave for themselves
                         (e.g. "I want to apply for leave", "book a casual leave tomorrow")
  leave_status         — checking the STATUS/OUTCOME of a leave request they already
                        submitted, INCLUDING pending, approved, cancelled, or rejected ones
                        (e.g. "is my leave approved", "status of my leave request", "do I have
                        any pending leave requests", "show me my pending leaves", "view pending
                        leave request", "show my cancelled leaves", "show my cancel leave",
                        "what leaves have I cancelled", "show my leave application history") —
                        this is a VIEWING/LISTING request about the STATE of already-submitted
                        request(s), never an instruction to act on one. NOT a question about
                        remaining/available day counts (that's leave_balance).
  cancel_leave         — wanting to CANCEL/WITHDRAW a leave request they already submitted, i.e.
                        an ACTION to perform NOW (e.g. "cancel my leave", "withdraw my pending
                        request", "cancel LR-2041", "please cancel it"). The word "cancel"
                        alone does NOT mean this intent — "show me my CANCELLED leaves" is
                        asking to VIEW past cancellations (leave_status), not to cancel
                        anything; only an imperative asking the assistant to actually perform
                        the cancellation belongs here.
  leave_eligibility    — asking whether THEY THEMSELVES QUALIFY for a leave type under
                        company policy (e.g. "am I eligible for casual leave",
                        "do I qualify for earned leave", "can I take sick leave")  
  
  leave_policy         — general leave TYPES, RULES, or POLICY questions not about their
                        own balance, eligibility, or applying, including how a leave type's
                        accrual/entitlement works (e.g. "what is the maternity leave policy",
                        "how does compensatory off accrual work", FMLA, PTO rules, approval
                        process in general). Never work-from-home, attendance, or absence
                        rules — those are attendance, even when the query says "...policy".
  payroll              — payroll processing, pay slip, deductions, salary disbursement,
                         professional tax deduction, and the SETTLEMENT CALCULATION/AMOUNT
                         of a full and final settlement (the offboarding STEPS around it are
                         employee_management; the number-crunching itself is payroll)
  salary               — salary range, CTC, compensation, increment, bonus, pay raise
  recruitment          — the hiring PROCESS/STRATEGY/LOGISTICS: current job openings,
                         candidate sourcing (incl. passive candidates), screening approach,
                         resume red flags, background checks, time-to-hire (a
                         recruitment-specific metric, not a general_hr one), counter-offer
                         handling, candidate rejection communication, applicant tracking.
                         NOT the specific interview questions/rounds/panel to use (that's
                         interview_questions) and NOT writing a JD, job posting, or offer
                         letter (that's job_description, and ONLY those three document
                         types — an experience/relieving letter is employee_management, a
                         rejection email is recruitment, not job_description).
  benefits             — health insurance, provident fund, gratuity, perks, allowances,
                         reimbursement claims (e.g. medical expense reimbursement)
  performance          — KPI, appraisal, performance review (mid-year/annual), PIP, rating,
                         self-assessment forms, OKRs, constructive feedback approach,
                         promotion process, 360/peer feedback
  attendance           — attendance tracking,  attendance records ,attendance status,

                           punch/check-in/check-out times for a specific day (that's
                           punch_details), NOT why a specific day was marked a certain way
                           (that's attendance_explain), and NOT submitting a regularisation
                           request for a missed punch (that's regularisation).
  punch_details        — asking for THEIR OWN punch/check-in/check-out times, shift timing, or
                           worked hours for a specific day (e.g. "what time did I check in today",
                           "my shift timing", "how many hours did I work yesterday", "punch details
                           for 21 July")
  attendance_explain   — asking WHY their attendance on a specific day was marked a certain
                           way (Present, Half Day, Late, Absent, Missing Punch) — wants the
                           reasoning/explanation for a classification, not just a status lookup
                           (e.g. "why was I marked late today", "explain my attendance for Monday",
                           "why does it show missing punch")
  regularisation       — wanting to SUBMIT/APPLY a regularisation request for a missed or
                           incorrect punch (e.g. "regularise my attendance for yesterday",
                           "apply for attendance regularization", "missed punch regularisation")  
  employee_management  — termination, resignation and its notice period, disciplinary action,
                         show-cause notices, grievance, conflict, harassment complaint
                         escalation, layoff/retrenchment process, exit process,
                         experience/relieving letters
  onboarding           — new hire formalities, induction, probation (including how
                         probation confirmation should be communicated), day one checklist,
                         feedback collected FROM NEW HIRES about their own first days/weeks
                         (NOT the same as measuring a training program's effectiveness).
  training             — training programs, certifications to sponsor, L&D, upskilling,
                         development plans, leadership development, mentorship programs,
                         training budget (a training-specific cost, not a general_hr one),
                         measuring a TRAINING PROGRAM's effectiveness, learning platforms,
                         the skill-gap ANALYSIS PROCESS for a team
  compliance           — labor law, employment contract, statutory compliance, HR audit,
                         records required for a statutory audit, documenting workplace
                         safety incidents
  job_description      — writing JDs, role profiles, responsibilities for a position,
                         writing an attractive job posting, what an offer letter should
                         include
  interview_questions  — WHAT QUESTIONS to ask a candidate (technical, behavioral, or about
                         a specific skill), how many interview rounds, interview panel
                         structure, interview guides/scorecards, culture-fit questions
  skills               — WHAT SKILLS are required for a specific HR-managed role or team
                         (not what questions to ask about those skills — that's
                         interview_questions), skill-gap identification for a role
  experience           — experience requirements for a role being hired or evaluated
  general_hr           — HR industry trends/news, market insights, HR department structure,
                         HR metrics/KPIs, HR strategy, HR software/tools — genuinely
                         topic-agnostic questions with NO specific operational anchor. A
                         "how should we..." / "what's a good process for..." / "how do we
                         measure..." question that NAMES a specific topic already covered
                         above (a performance review, a recruitment/screening step, a
                         training program, an interview panel) belongs to THAT intent, not
                         here — general_hr is the fallback ONLY when no specific intent above
                         fits at all.

Non-HR — use when the query is NOT about managing employees, workplace, or HR processes:
  non_hr               — general knowledge, science, cooking, weather, sports, coding tutorials,
                         "how to become X", career advice for personal growth, software development,
                         math, politics, geography, entertainment, anything unrelated to running HR

HARD RULES:
- Output ONLY a JSON object of the exact shape {{"intent": "<label>"}} — no explanation,
  no markdown fences, no other text.
- "How to become a software developer" → non_hr (personal career advice, not HR management)
- Skills/competencies/qualifications/tools required for ANY job role or team
  (e.g. "skills for a QA automation engineer", "what skills does a developer need",
  "key skills for an AI engineer") → skills, even if worded like a job-seeker question —
  do NOT classify these as non_hr. Only "how do I become X" (no role skills asked) is non_hr.
- Experience/seniority required for ANY role (e.g. "experience needed for a data analyst",
  "years of experience for a senior QA") → experience.
- "What skills should I look for when hiring a developer" → skills
- "Write python code / give me code" → non_hr (coding request)
- "Latest HR hiring trends" → general_hr
- "What are the current recruitment market trends" → general_hr
- "How should we structure our HR department" → general_hr
- "What HR metrics or KPIs should we track" → general_hr
- A bare "check my leave" / "check my leaves" (no status word like
  pending/approved/rejected, no date) → leave_balance, matching this app's own
  established convention for that exact ambiguous phrase — not leave_status.
- Metric/benchmark/budget questions naming a specific function's own activity stay
  with that function, never general_hr: "time-to-hire benchmark" → recruitment;
  "training budget per employee" → training; "a fair process for promotion
  decisions" → performance; "documenting workplace safety incidents" → compliance.
- "How should probation confirmation be communicated" → onboarding (probation is
  explicitly an onboarding topic even when the question is about internal
  communication process, not employee_management).
- "What are the job openings currently" → recruitment (not non_hr).
- "What's a good candidate rejection email template" → recruitment, NOT
  job_description — job_description is ONLY a JD, role profile, job posting, or
  offer letter; any other hiring communication (rejection emails) is recruitment.
- "What should an experience letter include" → employee_management, NOT
  job_description — an experience/relieving letter is issued when someone LEAVES,
  unlike an offer letter issued when hiring them.
- "How many working hours per day" / "what are our office hours" → attendance, not
  non_hr — a plain workplace-logistics question is still HR even with no HR jargon.
- "What labor law changes affect our leave policy this year" → compliance, not
  leave_policy — a question about LAW/REGULATORY CHANGES is compliance even when it
  names leave as the affected area; leave_policy is for the leave RULES themselves.
- "How does compensatory off accrual work" → leave_policy, NOT compliance — accrual
  RULES for a leave type are leave_policy; compliance is about labor LAW obligations,
  not how a specific leave type's balance is earned.
- "What's included in the full and final settlement" → payroll, NOT
  employee_management or compliance — the settlement's CONTENTS/CALCULATION is
  payroll's domain even though it happens during offboarding.
- Salary/compensation questions naming ANY job role, tech stack, or location
  (e.g. "AWS DevOps salary in Singapore", "latest salary for a Python developer")
  → salary, even if worded like a job-seeker question — do NOT classify these as non_hr.
  Only treat it as personal career advice (non_hr) when there's no salary/compensation
  figure being asked for (e.g. "how do I become an AWS DevOps engineer").
- "What is latest aws devops salary in Singapore" → salary
- "Salary range for python engineer according to India" → salary
- "Latest salary trends for backend developers in the US" → salary, NOT general_hr —
  the word "trends" alone doesn't mean general_hr when a role/tech/location is named;
  general_hr trends are broad HR-industry/strategy trends with no specific role.
- "How does an annual increment usually work" → salary (increment is a compensation
  topic even when phrased generally, not performance — performance covers the
  review/rating process, not the resulting pay change).
- Greetings and small_talk are NEVER non_hr.
- Do NOT classify as HR just because an HR word appears — judge the full intent.
- "What is my leave balance" / "how many leaves left" → leave_balance (personal, self).
- "I want to apply for leave" / "book leave for tomorrow" → apply_leave (personal, self, action).
- "Is my leave approved" / "status of my leave request" → leave_status (checking an existing request).
- "Show my leave application history" / "show my previous leave applications" → leave_status,
- "Do I have any pending leave requests" / "show me my pending leaves" / "view pending leave
  request" / "give my pending leaves" → leave_status, NEVER leave_balance — "pending" describes
  the STATE of an already-submitted request, not a count of days remaining.
- "Cancel my leave" / "withdraw my pending request" / "cancel LR-2041" / "please cancel it" →
  cancel_leave — an instruction to perform the cancellation.
- "Show my cancelled leaves" / "show my cancel leave" / "what leaves have I cancelled" /
  "give me my cancelled leave requests" → leave_status, NEVER cancel_leave — this is asking to
  VIEW/LIST requests that are already in the "cancelled" state, not an instruction to cancel
  anything. The literal word "cancel"/"cancelled" appearing in a "show me"/"what are"/"give me"
  framing is a STATUS FILTER (like "pending" or "approved"), not an action request — only a
  direct imperative ("cancel my leave") is the action intent.
  NEVER conversation_meta — this is about their leave records, not this chat's history.
- "What is the sick leave policy" / "how does FMLA work" → leave_policy (general, informational).
- "Am I eligible for casual leave" / "do I qualify for earned leave" → leave_eligibility.
- "Can I take maternity leave" / "am I allowed sick leave" → leave_eligibility. A question
  about whether they QUALIFY is never apply_leave — apply_leave needs a clear intent to
  actually book or submit ("apply for", "book", "request X from <date>").
- leave_eligibility vs leave_policy is personal vs general: "am I eligible for X" is about
  THIS employee (leave_eligibility); "what is the X policy" / "who is eligible for X" asks
  about the rule in general (leave_policy).
- leave_eligibility vs leave_balance is qualification vs quantity: "am I eligible for casual
  leave" (leave_eligibility) vs "how many casual leaves do I have left" (leave_balance).
- "What is the work from home policy" / "what's considered an unauthorized absence" →
  attendance, NEVER leave_policy — WFH and absence rules are not a leave TYPE.
- "What time did I check in today" / "my shift timing" / "how many hours did I work" → punch_details
  (personal, a specific day's punch/shift/work-hours record — NOT the broader attendance intent).
- "Why was I marked late" / "explain my attendance for Monday" → attendance_explain
  (wants the reasoning behind a classification, not a general attendance question).
- A plain-language HR question with no obvious "HR" vocabulary is still HR, never non_hr:
  "how is professional tax deducted" → payroll; "how do I claim medical reimbursement" →
  benefits; "what records are needed for a statutory audit" → compliance; "what's a good
  format for a lunch-and-learn" / "what learning platforms work well for remote teams" →
  training; "how should a show-cause notice be worded" → employee_management.
- "What questions should I ask..." in a hiring/interview context → interview_questions, even
  when the questions are about a specific skill or technology (e.g. "what technical
  questions suit a React developer" → interview_questions, not skills).
- Writing/content questions about a hiring DOCUMENT (a JD, a job posting, an offer letter)
  → job_description, even though sourcing/screening/background-checks for the SAME hire
  is recruitment: "what should an offer letter include" / "how do we write an attractive
  job posting" → job_description. "how should we structure a technical interview panel" /
  "how many interview rounds should a senior role have" / "what questions reveal culture
  fit" → interview_questions, not recruitment.
- A "how should we structure/measure/run..." question naming a specific topic already listed
  above stays that intent, not general_hr: "what KPIs should a sales manager be rated on" →
  performance; "what's the best way to source passive candidates" → recruitment; "how do we
  identify skill gaps across the org" → training.

{awaited_directive}{followup_directive}{context_block}Current User Query: {query}"""


# ── The name points at the LIVE prompt builder, not the copy above ───────────
# Exactly the shadowing that killed _VALID_INTENT_LABELS (see the note just
# below) and leave_action_node: the import at the top of this section brings
# in classify_node's builder, and the `def` above then rebinds the name over
# it. The graph calls classify_node's directly, so the copy above is dead —
# but anything reading hr_graph._build_intent_prompt got the dead one, several
# sprints out of date and missing every complex-manager label.
#
# Re-pointing the name is the whole fix; deleting the ~290 dead lines above is
# the follow-up, kept separate so this change stays reviewable.
_build_intent_prompt = classify_node_mod._build_intent_prompt


# Every label the prompt above can legally return — must stay in sync with it.
# _VALID_INTENT_LABELS lives in classify_node.py and arrives via the line-17
# import. A second copy used to be defined HERE, shadowing that import with a
# stale list - it was missing every manager label added since (shift_query,
# manager_leave_approval, manager_leave_request_lookup,
# manager_attendance_explanation, the complex-manager set), so anything
# reading hr_graph._VALID_INTENT_LABELS saw a taxonomy several sprints out of
# date. Deleted rather than re-synced: one taxonomy, one definition, and no
# way for the two to drift apart again.


_DATABASE_WIRED_INTENTS = frozenset({"leave_balance", "apply_leave", "leave_status", "cancel_leave", "leave_eligibility","HRMS_TEAM_LEAVE_QUERY",
                                     "manager_leave_request_lookup", "manager_attendance_explanation",
                                     "manager_leave_approval",
                                     "HRMS_TEAM_ATTENDANCE_QUERY"})

_DATABASE_CAPABLE_INTENTS = frozenset({"attendance", "payroll", "salary", "performance"})


def _is_database_related(intent: str) -> bool:
    return intent in _DATABASE_WIRED_INTENTS or intent in _DATABASE_CAPABLE_INTENTS


#: The three categories FR-09 reports on, and FR-02 asks the system to tell
#: apart. Kept beside the frozensets they are derived from so the two cannot
#: drift.
CATEGORY_GENERAL = "general"
CATEGORY_HR_QUERY = "hr_query"
CATEGORY_HRMS_ACTION = "hrms_action"


def conversation_category(intent: str, is_hr: bool = True) -> str:
    """Which of FR-02's three kinds this turn was.

    "HRMS action/request" means the turn TOUCHES HRMS DATA and is therefore
    governed by the permission framework — it does not mean the turn mutates
    anything. So `leave_balance` sits with `apply_leave`: both need auth,
    both need tenant isolation. Splitting them by read-vs-write would be an
    engineering distinction the ticket never asks for, and would report
    "how many leaves do I have" as an HR *query* when it is an HRMS lookup.

    "HR information/query" is therefore the HR turns that are answered from
    documents or general HR knowledge, touching no employee record.

    Note `payroll`, `salary` and `performance` appear in both
    _DATABASE_CAPABLE_INTENTS and _DOCUMENT_BACKED_INTENTS, so they report as
    HRMS. That over-reports rather than under-reports, which is the safe
    direction for anything read as a permissions signal.
    """
    if not is_hr:
        return CATEGORY_GENERAL
    if _is_database_related(intent or ""):
        return CATEGORY_HRMS_ACTION
    return CATEGORY_HR_QUERY


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



def _describe_awaited_leave_slot(slots: dict) -> Optional[str]:
    if slots.get("step") == "awaiting_confirmation":
        return "whether to CONFIRM submitting their leave request"
    if not slots.get("leave_type"):
        return "the TYPE of leave they want (e.g. casual, sick, earned)"
    if not slots.get("from_date") or not slots.get("to_date"):
        return "the DATES for their leave"
    if (slots.get("leave_type") in _SESSION_TYPE_REQUIRED_LEAVE_TYPES
            and _is_single_day(slots) and not slots.get("session_type_slug")):
        return "whether it's a FULL DAY or HALF DAY"
    if _is_single_day(slots) and slots.get("session_type_slug") == "half_day":
        return "whether it's the FIRST HALF or SECOND HALF of the day"
    if not slots.get("reason"):
        return "the REASON for their leave request"
    return "a detail of their in-progress leave application"


# ── Node 3: Non-HR redirect ───────────────────────────────────────────────────

def _is_withdrawn_name_guess(state: HRState) -> bool:
    """A manager's / HR's / admin's short message that classify_node guessed
    was an employee's name, and erp-api found nobody by it ("tough", "wow").
    It is conversation, so it is answered by the model alone, never searched:
    the ticket of Oct 22 had these answered as dictionary entries built from
    dictionary pages."""
    return state.get("route_to") == individual_report.GUESSED_SUBJECT_NOT_AN_EMPLOYEE


# What the directory just established about a withdrawn guess, told to the
# model answering it. HA-932 re-test: under the team's pending list, "Kunal
# Employee" (not on that team) was handed back and the model invented two
# leave requests for him, copying the list above.
WITHDRAWN_NAME_GUESS_NOTE = (
    "\n\nThis message was checked against the user's team in Helixta's HR system and "
    "matched no one on it. If it reads as a person's name, say plainly that nobody by "
    "that name is on their team, and offer to show the team's list. Never give leave, "
    "attendance or any other HR details for that name - you have none. Otherwise "
    "treat it as ordinary conversation.")


# A question word, an ask, or a conversational word: not a bare topic.
_NOT_A_BARE_TOPIC_RE = re.compile(
    r"\b(?:what|who|whom|whose|how|why|when|where|which|is|are|was|were|can|could|do|does|did|"
    r"should|will|would|tell|explain|show|give|define|meaning|mean|list|find|search|compare|"
    r"kya|kaun|kaise|kab|kyun|kahan|batao|bata|samjhao|"
    r"ok|okay|thanks?|thank|wow|hmm+|nah|yes|yeah|no|nope|lol|cool|nice|great|sure|hi|hello|hey|"
    r"bye|please|pls)\b",
    re.IGNORECASE)

BARE_TOPIC_INSTRUCTION = (
    "The user typed only a topic, with no question. This overrides the Conversation section "
    "above: it is a new subject, not a reaction to anything earlier, and you NEVER reply with "
    "only a question. Answer from your own knowledge - do not search. START with 2 or 3 "
    "sentences saying what it is. Give NO current figure: no price, rate, "
    "score, result, ranking or recent event, because you have no live data. Then ask, in one "
    "short sentence, what they would like to know about it - for example how it works, its "
    "history, or the latest news or figures (which you can look up if they ask). If you do "
    "not know what it is - a person's name, say - do not guess: say so and ask what they mean.")


def is_bare_topic(query: str, context: Optional[list] = None) -> bool:
    """"bitcoin", "stock market", "election": 1-3 words, no question, no ask.
    UAT UV-16 (28 Oct): searched and answered at length; UAT asks what they
    want to know. A reply to a question the assistant just asked ("which
    coin?" -> "bitcoin") is an answer, not a new topic."""
    text = (query or "").strip().strip("?!.")
    words = text.split()
    if not 1 <= len(words) <= 3 or not all(re.fullmatch(r"[A-Za-z][A-Za-z'&-]*", w) for w in words):
        return False
    if _NOT_A_BARE_TOPIC_RE.search(text) or needs_live_search(text):
        return False
    last = next((m.get("content") or "" for m in reversed(context or [])
                 if m.get("role") == "assistant"), "")
    return not last.rstrip().endswith("?")


async def non_hr_node(state: HRState, writer: StreamWriter) -> dict:
    query = state["query"]
    # Non-HR questions are ANSWERED by the LLM with web search always on,
    # regardless of GENERAL_CHAT_WEB_SEARCH_ENABLED (that switch only governs
    # general_chat_node). The old HR-only redirect is kept as the fallback
    # when the LLM returns nothing.
    usage_events = list(state.get("usage_events", []))

    # The weather now and the time somewhere are answered from a live source
    # with the reading's own timestamp - never from a search snippet or the
    # model. P1 (Oct 14): "current weather in calgary" got a 19-hour-old
    # observation copied from a search-index snapshot, presented as current.
    # With a date ("1 Nov 2026 ko Calgary weather") and as a follow-up to the
    # last live answer ("Which city?" -> "noida", "what about delhi?").
    # services/live_requests: units, ranges, several cities, time-zone
    # questions and "how old is this data?" follow-ups too (QA TP-001..082).
    # NON_HR_LIVE_SOURCES can switch any kind off; it then goes to web search.
    live = live_requests.parse_request(query, state.get("context"))
    # "bitcoin" alone names a topic, not a price request (UV-16): it gets the
    # short overview and a question below. "bitcoin price" keeps the quote.
    if live and live["kind"] == "market" and is_bare_topic(query, state.get("context")):
        live = None
    if live and not live_requests.live_source_enabled(live["kind"]):
        logger.info("[Graph] non_hr live %s disabled - web search instead", live["kind"])
        live = None
    if live:
        kind, place = live["kind"], live.get("place")
        result = await live_requests.answer_request(live)
        logger.info("[Graph] non_hr live %s for %r - available=%s observed_at=%s",
                    kind, place, result.get("available"), result.get("observed_at"))
        writer({"type": "chunk", "content": result["answer"]})
        writer({
            "type": "done", "intent": state["intent"], "is_hr": False,
            "data": {"answer": result["answer"], "live_info": kind,
                     "source": result.get("source"), "observed_at": result.get("observed_at"),
                     "stale": result.get("stale", False),
                     "live_available": result.get("available", False)},
            "message": result["answer"], "usage_events": usage_events,
        })
        return {"response_text": result["answer"], "usage_events": usage_events}

    # A withdrawn name guess is answered without search, so without the
    # search prompt too: told "you can search the web" with no way to, the
    # model wrote fake searches ('Searching web for "Dileep Anumla". Search
    # results: 1. LinkedIn...') and raw tool-call JSON (QA, Oct 23).
    conversational = _is_withdrawn_name_guess(state)
    # A place name on its own ("canada calgary alberta"): the live facts lead -
    # local time, the weather now, today's high/low - straight from the live
    # sources, then the model's overview. The model is told not to give its
    # own figures for any of them.
    place = (await live_info.resolve_place(query)
             if live_requests.live_source_enabled("place") and live_info.looks_like_bare_place(query)
             else None)
    # Any other bare topic ("bitcoin", "stock market") is answered from the
    # model, briefly, with no search, and asks what they want to know (UV-16).
    bare_topic = (not conversational and not place
                  and is_bare_topic(query, state.get("context")))
    if bare_topic:
        logger.info("[Graph] non_hr bare topic %r - short overview and a question, no search", query)
        conversational = True
    system = ((GENERAL_CHAT_SYSTEM_PROMPT if conversational else GENERAL_CHAT_WEB_SEARCH_PROMPT)
              + _general_chat_clock_line())
    if bare_topic:
        system += "\n\n" + BARE_TOPIC_INSTRUCTION
    elif conversational:
        system += WITHDRAWN_NAME_GUESS_NOTE
    full_text = ""
    if place:
        snapshot = await live_info.place_snapshot(place)
        full_text = snapshot + "\n\n"
        writer({"type": "chunk", "content": full_text})
        system += ("\n\nThe user typed only a place name. This live snapshot has ALREADY been "
                   f"shown to them above your reply:\n{snapshot}\nDo not repeat it, and do not "
                   "give any time, temperature or weather figure of your own. Write a short, "
                   "useful overview: what and where the place is, what it is best known for, "
                   "and practical facts - language, currency, the main airport, the local time "
                   "zone's name. 4 to 6 sentences, or a short list.")
    # A bare topic is a new subject: with the earlier turns in view the model
    # treated "bitcoin" as a reply to them and only asked "What would you like
    # to know about Bitcoin?" (live, 28 Oct).
    messages = ([{"role": "system", "content": system}]
                + ([] if bare_topic else _general_chat_context(state))
                + [{"role": "user", "content": query}])
    captured_usage = None
    try:
        async for event in _call_llm_stream(messages, max_tokens=LLM_MAX_TOKENS,
                                            use_tools=not conversational):
            if event["type"] == "searching":
                logger.info("[Graph] non_hr web search")
                writer({"type": "searching", "message": "Searching the web..."})
            elif event["type"] == "chunk":
                # The race model writes OpenAI-style 【Source title】 markers
                # the chat window shows verbatim; plain brackets instead.
                content = event["content"].replace("【", "(").replace("】", ")")
                full_text += content
                writer({"type": "chunk", "content": content})
            elif event["type"] == "usage":
                captured_usage = event["usage"]
    except Exception as e:
        logger.warning(f"[Graph] non_hr LLM failed, using fallback: {e}")

    # The model failed or said nothing: say so, as hr_response_node does. The
    # HR-only redirect that used to stand in here ("I only cover HR and
    # workforce topics...") brought the removed guardrail back on every
    # model outage (P1, Oct 26). Whitespace counts as nothing: a reply of
    # only newlines rendered as an empty bubble (HAI-GEN-15, 27 Oct).
    if not full_text.strip():
        full_text = GENERAL_CHAT_UNAVAILABLE
        writer({"type": "chunk", "content": full_text})

    if captured_usage:
        usage_events.append({"source": "non_hr", "usage": captured_usage})

    writer({
        "type": "done",
        "intent": state["intent"],
        "is_hr": False,
        "data": {"answer": full_text},
        "message": full_text,
        "usage_events": usage_events,
    })
    return {"response_text": full_text, "usage_events": usage_events}


# ── Node: general-purpose (non-HR) chat ───────────────────────────────────────

GENERAL_CHAT_UNAVAILABLE = (
    "I couldn't get an answer together just then — please try again in a moment."
)

#: The general lane's intent on its done event, so analytics (and the next
#: turn) can tell a general answer from the HR redirect ("non_hr").
GENERAL_CHAT_INTENT = "general_chat"

#: How much of the conversation the general lane sees: enough for "make it
#: shorter" / "now add type hints" to mean something.
_GENERAL_CHAT_CONTEXT_MESSAGES = 6
_GENERAL_CHAT_CONTEXT_CHARS = 4000

#: Set on the done event (top level, never sent to the client) when the turn
#: did not produce a real answer, so main.py logs it as a failure with the
#: stage that failed instead of as a success (FR-09).
FAILURE_STAGE_LLM = "general_chat_llm"
LIMITED_STAGE = "general_chat_rate_limited"

GENERAL_CHAT_LIMIT_REACHED = (
    "You've reached the limit for general questions for now — please try again "
    "a little later. I can still help with your leave, attendance, "
    "regularization and other HR requests."
)


def _general_chat_clock_line() -> str:
    """The current date AND time, in the app's timezone (QUOTA_TIMEZONE - the
    same one every "today" here uses). Live: "what is today time" got "I don't
    have access to real-time data" - the model had the date only."""
    import os
    from zoneinfo import ZoneInfo
    tz_name = os.getenv("QUOTA_TIMEZONE", "UTC")
    try:
        now = _dt.now(ZoneInfo(tz_name))
    except Exception:
        tz_name, now = "UTC", _dt.utcnow()
    # UTC as well: the model compares it with the times search results state
    # (an "as of 5 PM MDT" snippet is only judged stale if the model can tell
    # what time it is now in absolute terms - P1, Oct 14).
    utc_now = _dt.now(ZoneInfo("UTC"))
    return (f"\n\nToday's date is {now.strftime('%A, %d %B %Y')}. The current time is "
            f"{now.strftime('%I:%M %p').lstrip('0')} ({tz_name}), which is "
            f"{utc_now.strftime('%H:%M')} UTC on {utc_now.strftime('%d %B %Y')}. This is the "
            f"app's time zone, not necessarily the user's. Use these when asked for the "
            f"date, the day or the time, and to judge how old a search result is.")


def _general_chat_context(state: HRState) -> list:
    """The last few turns of THIS conversation, as chat messages. Only ever
    the caller's own conversation (main.py loads it by conversation id for
    the authenticated user), so nothing crosses users or tenants."""
    out = []
    context = state.get("context") or []
    # A summary needs the whole chat main.py loaded, not the last three
    # exchanges (QA LF-01: "Summarize the trip plan" covered the last turn).
    if not mentions_summary(state.get("query") or ""):
        context = context[-_GENERAL_CHAT_CONTEXT_MESSAGES:]
    for msg in context:
        role = msg.get("role", "user")
        if role not in ("user", "assistant"):
            role = "user"
        content = str(msg.get("content") or "")[:_GENERAL_CHAT_CONTEXT_CHARS]
        if content:
            out.append({"role": role, "content": content})
    return out


async def general_chat_node(state: HRState, writer: StreamWriter) -> dict:
    """Answers a non-HR question with ACTIVE_LLM_PROVIDER, for any role.

    Reached from _route_after_classify when the classifier said non-HR and
    general chat is switched on. Adds no access of its own: no ERP client, no
    database session - the model gets its own system prompt, the last few
    messages of this conversation and the question. Streamed like every
    other answer. Web search only when GENERAL_CHAT_WEB_SEARCH_ENABLED is on
    (default OFF): browsing was out of scope (HA-884), and on the race
    provider a search sends the raw message to /v1/search/brave on EVERY turn.
    """
    query = state["query"]
    usage_events = list(state.get("usage_events", []))

    if state.get("general_chat_over_limit"):
        # FR-08. Counted in main.py before the graph runs; HR questions are
        # never limited by this.
        writer({"type": "chunk", "content": GENERAL_CHAT_LIMIT_REACHED})
        writer({"type": "done", "intent": GENERAL_CHAT_INTENT, "is_hr": False,
                "data": {"answer": GENERAL_CHAT_LIMIT_REACHED},
                "message": GENERAL_CHAT_LIMIT_REACHED, "usage_events": usage_events,
                "failure_stage": LIMITED_STAGE})
        return {"response_text": GENERAL_CHAT_LIMIT_REACHED, "usage_events": usage_events}

    web_search = _general_chat_web_search_enabled() and not _is_withdrawn_name_guess(state)
    system = ((GENERAL_CHAT_WEB_SEARCH_PROMPT if web_search else GENERAL_CHAT_SYSTEM_PROMPT)
              + _general_chat_clock_line())
    if _is_withdrawn_name_guess(state):
        system += WITHDRAWN_NAME_GUESS_NOTE
    messages = ([{"role": "system", "content": system}]
                + _general_chat_context(state)
                + [{"role": "user", "content": query}])

    full_text = ""
    captured_usage = None
    try:
        async for event in _call_llm_stream(messages, max_tokens=LLM_MAX_TOKENS,
                                            use_tools=web_search):
            if event["type"] == "searching":
                logger.info("[Graph] general chat web search")
                writer({"type": "searching", "message": "Searching the web..."})
            elif event["type"] == "chunk":
                full_text += event["content"]
                writer({"type": "chunk", "content": event["content"]})
            elif event["type"] == "usage":
                captured_usage = event["usage"]
    except Exception as e:
        logger.warning("[Graph] general chat LLM failed: %s", e)

    if captured_usage:
        usage_events.append({"source": "general_chat", "usage": captured_usage})

    failure_stage = None
    answer = full_text
    if not full_text.strip():
        answer, failure_stage = GENERAL_CHAT_UNAVAILABLE, FAILURE_STAGE_LLM
        writer({"type": "chunk", "content": answer})

    done = {
        "type": "done",
        "intent": GENERAL_CHAT_INTENT,
        "is_hr": False,
        "data": {"answer": answer},
        "message": answer,
        "usage_events": usage_events,
    }
    if failure_stage:
        done["failure_stage"] = failure_stage
    writer(done)
    return {"response_text": answer, "usage_events": usage_events}


async def clarify_node(state: HRState, writer: StreamWriter) -> dict:
    """Terminal node for a bare-verb clarify question (e.g. lone 'apply').
    The prompt text was already decided in classify_node and stashed in
    state['clarify_message']/state['clarify_options'] — this node's only
    job is to stream it out and persist it the same way every other
    terminal node does, so it lands correctly in chat history."""
    usage_events = list(state.get("usage_events", []))

    # `or`, not a .get default: every turn now starts with the key set to None
    # (main.py's per-turn reset), which a .get default would not replace.
    message = state.get("clarify_message") or "Could you clarify what you'd like to do?"
    options = state.get("clarify_options") or []

    # Fold the options into the visible text too, since not every client
    # surface is guaranteed to render a separate options/buttons payload —
    # this keeps the message self-contained either way. Blank lines
    # (not single "\n") between entries because the frontend renders this
    # as markdown, and CommonMark collapses a lone "\n" into a plain space
    # instead of a line break.
    full_text = message
    if options:
        full_text += "\n\n" + "\n\n".join(f"• {opt}" for opt in options)

    writer({"type": "chunk", "content": full_text})

    writer({
        "type": "done",
        "intent": "clarify_needed",
        "is_hr": True,
        "data": {"answer": full_text, "options": options},
        "message": full_text,
        "usage_events": usage_events,
    })
    return {"response_text": full_text, "usage_events": usage_events}

# ── Node 3: HR Response ───────────────────────────────────────────────────────
# Chunks are streamed to the client immediately as they arrive — no buffering.
# Input moderation (in classify_node) is sufficient; output guardrail removed
# to eliminate the ~entire-response-duration delay before first byte.

# ── Node: HR-policy retrieval (leave_policy intent) ───────────────────────────
# race-api is the only provider with an actual document collection behind
# it (POST /v1/rag/query), so this runs independently of ACTIVE_LLM_PROVIDER
# — it fails open (policy_context stays None) straight through to
# hr_response_node whenever RAG isn't configured (RACE_API_KEY /
# RACE_RAG_COLLECTION_ID unset) or the lookup itself fails, same contract as
# _check_moderation and _call_race_brave_search elsewhere in this app.

# "show my policy" / "show my company policy" — the company's policies IN
# GENERAL, with no topic named. Live: these came back with the no-information
# fallback even though retrieval returned excerpts from all eleven documents.
# The summarizer below is told to answer NO_RELEVANT_POLICY_FOUND unless an
# excerpt ANSWERS the question, and "show my policy" asks nothing any one
# excerpt answers — it asks what the policies ARE. Such a question gets an
# overview of the documents instead (_policy_overview).
#
# The detector lives in nlp_service (is_policy_overview_request) so the
# classifier's deterministic policy override and this node agree on it.
_is_policy_overview_query = is_policy_overview_request


# What an overview searches each document for: the rule-bearing parts, not
# the words "show my policy", which match nothing in particular.
_POLICY_OVERVIEW_SEARCH = ("policy rules entitlements eligibility days limits approval "
                           "procedure applicability exceptions")
_POLICY_OVERVIEW_CHUNKS_PER_DOC = 5

# Several uploaded "policies" are lorem ipsum. Dropped before the model reads
# them: they cost prompt tokens and carry nothing to show an employee.
_PLACEHOLDER_TEXT_RE = re.compile(r"\blorem\s+ipsum\b|\bdolor\s+sit\s+amet\b", re.IGNORECASE)


def _is_placeholder_text(text: str) -> bool:
    return bool(_PLACEHOLDER_TEXT_RE.search(text or ""))


_POLICY_SOURCE_HEADING_RE = re.compile(r"^### From: (.+)$", re.MULTILINE)


def _policy_titles_in(retrieved_text: str) -> list:
    """The policy names in format_retrieved_chunks' "### From: <name>"
    headings, in order — how hr_response_node recovers them from
    policy_context without another state key."""
    seen = []
    for name in _POLICY_SOURCE_HEADING_RE.findall(retrieved_text or ""):
        name = name.strip()
        if name and name not in seen:
            seen.append(name)
    return seen


def _policy_overview_prompt(retrieved_text: str) -> str:
    """What every policy actually says, from the excerpts only. Streamed by
    hr_response_node: generated in one piece it took ~31s (5.8k output
    tokens) with nothing on the employee's screen."""
    names_line = ", ".join(_policy_titles_in(retrieved_text))
    return (
        "Below are excerpts from this company's HR policy documents, grouped under "
        "'### From: <policy name>'. The employee asked to see their company's "
        "policies, so show them what each policy actually says.\n\n"
        "Write a section for EVERY policy in the list below that has real policy "
        "content — including the Leave Policy, the Attendance Policy and the General "
        "Policy when they are listed:\n"
        "  ## <Policy name>\n"
        "  one sentence on what it covers, then bullets with its actual rules — "
        "entitlements, numbers of days, limits, who it applies to, eligibility, how to "
        "apply and get approval, exceptions. Keep every figure and rule exactly as "
        "written. Include everything substantive in the excerpts; leave out only "
        "repetition.\n\n"
        "A policy marked as a draft, or with blanks still to be filled in, IS a real "
        "policy: include it. Leave out only a policy whose excerpts are filler text or "
        "a document that is not a policy at all (a job description, a payslip). "
        "Use only what the excerpts say — no general HR knowledge, no invented rules. "
        "Never mention excerpts, documents, files or that anything is missing; the "
        "employee is reading an answer, not a report on the files.\n\n"
        "End with one line inviting them to ask about any policy for more detail.\n\n"
        f"Policies: {names_line}\n\n"
        f"Excerpts:\n{retrieved_text}"
    )


def _policy_names_fallback(retrieved_text: str) -> str:
    """The bare list of policy names, for when the overview can't be written —
    the names are facts from the collection, so this list is never wrong."""
    titles = _policy_titles_in(retrieved_text)
    if not titles:
        return ""
    return ("Your company's HR policies are:\n" + "\n".join(f"- **{t}**" for t in titles)
            + "\n\nAsk me about any of them for the details.")


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

    # A leave-policy question is answered from the leave configuration
    # (hr_response_node), so that is tried FIRST: QA (Oct 23) "hmm, what is
    # the leave policy?" waited 10-12 s on a document search it then ignored.
    # The documents are still searched when the configuration can't be read.
    if state.get("intent") != "general_chat" and _LEAVE_POLICY_QUESTION_RE.search(query or ""):
        configured = await _configured_leave_policy_answer(state, query)
        if configured:
            return {"configured_policy_answer": configured, "policy_context": None,
                    "policy_lookup_failed": False, "usage_events": usage_events}

    # Every document gets its own query and its own budget, rather than one
    # global top-k. A flat top-k is won by whichever document has the most
    # lexically similar text, so on this collection the two large documents
    # crowded out the rest: "work from home policy" returned the earned-leave
    # carry-forward chunk while the 536-character remote-work policy -- the
    # whole answer -- was never retrieved at all.
    #
    # "show my policy" asks for the CONTENT of every policy, so it searches for
    # rule-bearing text rather than for its own words (which match nothing in
    # particular), takes more of each document, and drops placeholder text.
    overview_requested = _is_policy_overview_query(query)
    if overview_requested:
        chunks = await race_rag_service.query_all_documents(
            _POLICY_OVERVIEW_SEARCH, k_per_doc=_POLICY_OVERVIEW_CHUNKS_PER_DOC)
        chunks = [c for c in chunks if not _is_placeholder_text(race_rag_service._chunk_text(c))]
    else:
        chunks = await race_rag_service.query_all_documents(query)
    if not chunks:
        return {"policy_context": None, "policy_lookup_failed": True,
                "usage_events": usage_events}

    retrieved_text = race_rag_service.format_retrieved_chunks(chunks)
    if not retrieved_text:
        return {"policy_context": None, "policy_lookup_failed": True,
                "usage_events": usage_events}

    writer({"type": "searching", "message": "Checking policy documents..."})

    # "show my policy" — the policies in general, no topic named. An overview
    # of the documents, not the relevance-judged answer below, which rejects
    # every excerpt for a question none of them individually answers.
    # The overview itself is written by hr_response_node, STREAMED — see
    # _policy_overview_prompt. Here it only needs the excerpts.
    if overview_requested:
        return {"policy_context": retrieved_text, "policy_lookup_failed": False,
                "policy_overview": True, "usage_events": usage_events}

    # race-api's /v1/rag/query is a plain top-k vector search with no
    # relevance floor — it always returns k chunks, and its "similarity"
    # score is not a reliable relevance signal (live-tested: a deliberately
    # off-topic query scored numerically HIGHER than a genuinely on-topic
    # one, because the score tracks lexical/keyword overlap, not semantic
    # match). A numeric similarity cutoff would therefore be guessing blind.
    # Instead the summarizer itself judges relevance and is told to emit
    # this exact sentinel when nothing retrieved actually answers the
    # question — checked verbatim below to fall back to web search/general
    # HR knowledge in hr_response_node, same as if RAG had returned nothing.
    _NO_MATCH_SENTINEL = "NO_RELEVANT_POLICY_FOUND"
    summary_prompt = (
        "Summarise the following internal policy document excerpts into a short, "
        "factual briefing that answers the employee's question below. Keep only "
        "details relevant to the question, preserve any concrete numbers/rules "
        "exactly as written, and say nothing not present in the excerpts. "
        f"If NONE of the excerpts actually answer the question, respond with "
        f"exactly this and nothing else: {_NO_MATCH_SENTINEL}\n\n"
        f"Employee's question: {query}\n\n"
        f"Policy excerpts:\n{retrieved_text}"
    )
    try:
        # race's gpt-oss-120b is reasoning-tier — same overhead documented on
        # _call_classification_race/_call_structured_date_race: it burns
        # completion tokens on a hidden "reasoning" field before writing
        # visible "content", and stops with content=None on finish_reason=
        # "length" if the budget runs out first. Live-tested against this
        # node's own prompt (~3.3k prompt tokens of retrieved policy text):
        # 400 -> content=None every time; 1200 -> still truncated mid-answer;
        # 1800 -> finishes naturally (finish_reason="stop") around ~1050
        # completion tokens. 2000 keeps headroom above that observed ceiling.
        # temperature=0 — this call judges relevance (the NO_MATCH_SENTINEL
        # branch above), not just phrasing; live-tested at the default 0.7,
        # the SAME query/retrieved-chunks pair flipped between a real
        # summary and NO_RELEVANT_POLICY_FOUND across two runs. 0 doesn't
        # guarantee determinism but removes the biggest source of it.
        raw = await _call_llm(summary_prompt, max_tokens=LLM_TASK_MAX_TOKENS, model=INTENT_MODEL, temperature=0)
        summary = _extract_text(raw).strip()
        usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
        if usage:
            usage_events.append({"source": "policy_rag_summary", "usage": usage})
    except Exception as e:
        logger.warning(f"[Graph] policy RAG summarisation failed: {e}")
        summary = retrieved_text[:2000]

    no_match = summary.strip().upper().startswith(_NO_MATCH_SENTINEL)
    if no_match:
        summary = ""

    # policy_lookup_failed says "we searched our documents and they do not
    # answer this". It is what stops the generic-HR fallback from taking over:
    # an employee asking "what is my company policy" used to get a polished
    # essay assembled from OTHER companies' HR blogs via web search, complete
    # with citations, presented as an answer about their own workplace. Silence
    # about what we don't have beats a confident answer from somewhere else.
    return {"policy_context": summary or None,
            "policy_lookup_failed": no_match or not summary,
            "usage_events": usage_events}


# The approved wording for anything the company's system and documents do not
# cover (QA sheet, TC-KG02/KG04). One sentence everywhere, never ad-hoc.
NO_INFO_FALLBACK = ("Based on the information available in your company policy/playbook, "
                    "I do not have this information. Would you like to check with HR?")

# Someone ELSE's employment record: whether they work here, when they joined or
# left, their exit / last working day, a resignation or termination. Two
# kinds: phrasings that can only be about a person, and record words that are
# also general process vocabulary ("what is the resignation process") and so
# count only when a person is named.
_PERSON_EMPLOYMENT_RE = re.compile(
    r"\b(?:(?:currently\s+|still\s+)?(?:an?\s+)?employee\s+here|(?:still\s+)?(?:work|works|working)\s+(?:here|with\s+us)|"
    r"still\s+(?:here|with\s+us|employed)|when\s+did\s+(?!i\b|we\b|you\b)\w+(?:\s+\w+)?\s+(?:join|leave|resign|quit)|"
    r"(?:did|does|has|is|was)\s+(?!i\b|we\b|you\b|an?\b|the\b|an?\s+employee\b)\w+(?:\s+\w+)?\s+"
    r"(?:resign\w*|leave|left|quit|join\w*|get\s+(?:fired|terminated)))\b",
    re.IGNORECASE)
_RECORD_WORD_RE = re.compile(
    r"\b(?:(?:leave|left|quit)\s+(?:the\s+)?(?:company|organi[sz]ation|firm)|exit\s+date|"
    r"date\s+of\s+(?:exit|leaving|joining|relieving)|last\s+working\s+day|relieving\s+date|"
    r"joining\s+date|resign(?:ed)?|terminated|fired|laid\s+off)\b", re.IGNORECASE)
_FIRST_PERSON_ONLY_RE = re.compile(r"\b(?:i|me|my|mine|myself)\b", re.IGNORECASE)
_THIRD_PARTY_RE = re.compile(
    r"\b(?:he|she|they|their|his|her|him|them)\b|'s\b|\b[A-Z][a-z]+\s+[A-Z][a-z]+\b")
_GUESS_PRESSURE_RE = re.compile(
    r"\b(?:best\s+guess|just\s+guess|take\s+a\s+guess|make\s+a\s+guess|guess\s+anyway|estimate|"
    r"roughly|approximately|ball\s*park)\b", re.IGNORECASE)


_LEAVE_POLICY_QUESTION_RE = re.compile(
    r"\bleave\s+(?:policy|policies|rules?|entitlements?|structure)\b"
    r"|\b(?:types?|kinds?)\s+of\s+leaves?\b|\bleave\s+types\b"
    r"|\bhow\s+many\s+(?:days\s+of\s+)?leaves?\s+(?:am\s+i|are\s+we|do\s+(?:i|we))\s+(?:entitled|allowed|eligible)",
    re.IGNORECASE)


def _yes_no(value) -> bool:
    return str(value).strip().lower() in ("1", "true", "yes")


async def _configured_leave_policy_answer(state: dict, query: str) -> Optional[str]:
    """The tenant's leave policy as configured in erp-api, or None when the
    configuration cannot be loaded (the caller falls back to the documents)."""
    try:
        result = await erp_client.get_leave_balance(
            state.get("bearer_token"), company_id=state.get("company_id"),
            conversation_id=state.get("conversation_id"))
    except Exception as exc:
        logger.info("[Graph] leave configuration unavailable for the policy answer: %s", exc)
        return None
    body = (result or {}).get("body") or {}
    settings = (body.get("data") or {}).get("leave_settings") or {}
    types = [t for t in (settings.get("leave_type") or [])
             if isinstance(t, dict) and t.get("slug") != "regularization" and t.get("name")]
    if not types:
        return None

    ql = (query or "").lower()
    asked = [t for t in types if str(t["name"]).lower() in ql
             or str(t.get("slug") or "").replace("_", " ") in ql]
    shown = asked or types

    def _type_lines(t):
        parts = []
        if t.get("quota") not in (None, ""):
            parts.append(f"{t['quota']} days a year")
        if t.get("max_apply_in_month") not in (None, ""):
            n = t["max_apply_in_month"]
            parts.append(f"up to {n} application{'s' if str(n) != '1' else ''} a month")
        start = str(t.get("benefit_start") or "").strip().lower()
        if start == "confirmation":
            parts.append("available after confirmation")
        elif start == "joining":
            parts.append("available from joining")
        parts.append("carries forward" if _yes_no(t.get("is_carry_forward"))
                     else "does not carry forward")
        if _yes_no(t.get("salary_settlement")):
            parts.append("unused days are encashed")
        if _yes_no(t.get("notice_period_applicable")):
            parts.append("can be used during the notice period")
        return f"- **{t['name']}**: " + "; ".join(parts) + "."

    title = (f"Your company's {shown[0]['name']} policy:" if asked and len(shown) == 1
             else "Your company's leave policy, as configured in Helixta:")
    lines = [title] + [_type_lines(t) for t in shown]
    if not asked:
        general = []
        if _yes_no(settings.get("is_leave_monthy_credit")):
            general.append("Leave is credited monthly.")
        if _yes_no(settings.get("back_date_leave_allow")):
            general.append("Back-dated leave can be applied.")
        if settings.get("comp_off_expire_days"):
            general.append(f"Comp-off expires after {settings['comp_off_expire_days']} days.")
        sessions = [s.get("name") for s in (settings.get("session_type") or []) if s.get("name")]
        if sessions:
            general.append("Leave can be taken as: " + ", ".join(sessions) + ".")
        if general:
            lines += ["", *general]
    lines += ["", "Ask \"how many leaves do I have remaining\" to see your current balance."]
    return "\n".join(lines)


def _hr_web_search_enabled() -> bool:
    """HR_WEB_SEARCH_ENABLED: whether HR answers may search the web when the
    company documents have nothing. Default OFF - browsing is out of scope
    (HA-884). Read per call, like the other switches."""
    return os.getenv("HR_WEB_SEARCH_ENABLED", "false").strip().lower() in ("1", "true", "yes", "on")


def _general_chat_web_search_enabled() -> bool:
    """GENERAL_CHAT_WEB_SEARCH_ENABLED: whether general (non-HR) answers may
    search the web. Default OFF, separate from HR_WEB_SEARCH_ENABLED so each
    lane is switched on its own. Read per call, like the other switches."""
    return os.getenv("GENERAL_CHAT_WEB_SEARCH_ENABLED", "false").strip().lower() in ("1", "true", "yes", "on")


_HOLIDAY_QUESTION_RE = re.compile(
    r"\b(?:next|upcoming|coming|future|remaining)\s+(?:public\s+|company\s+|national\s+)?holidays?\b"
    r"|\bholidays?\s+(?:list|calendar|schedule)\b"
    r"|\blist\s+(?:of\s+)?(?:all\s+)?(?:the\s+)?holidays\b"
    r"|\bwhen\s+is\s+(?:the\s+|our\s+)?(?:next\s+)?holiday\b"
    r"|\b(?:show|give|tell)\s+(?:me\s+)?(?:the\s+|my\s+|our\s+)?(?:company\s+)?holidays\b"
    r"|\bholidays?\s+(?:this|in\s+this|for\s+this)\s+(?:year|month)\b"
    # "How many holidays are there in my company this year?" (27 Oct) matched
    # none of the above, went to the policy documents and got "I do not have
    # this information" - the calendar has the answer.
    r"|\b(?:how\s+many|number\s+of|total(?:\s+no\.?\s+of)?|count\s+of)\s+(?:\w+\s+){0,2}holidays\b"
    r"|\bholidays\b[\w\s']{0,40}?\b(?:this|current|in\s+the)\s+(?:calendar\s+)?year\b"
    # "Is it a holiday in our company?" (QA LT-06, about Diwali), "is 25 Dec a
    # holiday", "holiday at our office". Answered from the calendar: the policy
    # documents said "Yes, Diwali is a company holiday" in one run and "not a
    # company holiday" in another.
    r"|" + r"\bis\s+(?:it|this|that|[\w.-]+(?:\s+[\w.-]+){0,2})\s+a\s+(?:company\s+|public\s+|national\s+|bank\s+)?holiday\b"
    r"|\bholiday\s+(?:in|at|for)\s+(?:our|my|the)\s+(?:company|office|organi[sz]ation|firm)\b",
    re.IGNORECASE)

_HOW_MANY_RE = re.compile(r"\b(?:how\s+many|count|number\s+of)\b", re.IGNORECASE)
_LEFT_RE = re.compile(r"\b(?:left|remaining|remain|more|still|upcoming|to\s+come|rest|baaki|bache)\b",
                      re.IGNORECASE)

_HOW_MANY_HOLIDAYS_RE = re.compile(
    r"\b(?:how\s+many|number\s+of|total(?:\s+no\.?\s+of)?|count\s+of)\s+(?:\w+\s+){0,2}holidays\b",
    re.IGNORECASE)

# Whether a particular day is a holiday, rather than "which are the holidays".
_IS_IT_A_HOLIDAY_RE = re.compile(
    r"\bis\s+(?:it|this|that|[\w.-]+(?:\s+[\w.-]+){0,2})\s+a\s+(?:company\s+|public\s+|national\s+|bank\s+)?holiday\b"
    r"|\bholiday\s+(?:in|at|for)\s+(?:our|my|the)\s+(?:company|office|organi[sz]ation|firm)\b",
    re.IGNORECASE)


def _holiday_named_in(holidays: list, query: str, context: list) -> Optional[dict]:
    """The calendar holiday the question is about: one whose name appears in
    the question, else in the earlier user messages, else in the last answer.
    Most recent mention wins. UAT LT-06 T7: "Diwali kya hai?" was six turns
    back - the four user messages before "Is it a holiday in our company?"
    said only "it"/"iska" - so a last-4 window found nothing; the answer to
    "When is it in 2026?" named Diwali."""
    msgs = list(reversed(context or []))
    def _in(text):
        low = (text or "").lower()
        return [h for h in holidays
                if (name := str(h.get("holiday_name") or "").strip().lower())
                and re.search(rf"\b{re.escape(name)}\b", low)]

    for text in [query] + [m.get("content") or "" for m in msgs if m.get("role") == "user"]:
        found = _in(text)
        if found:
            return found[0]
    # The last answer only when it names one holiday - a holiday list names them all.
    last_answer = next((m.get("content") or "" for m in msgs if m.get("role") == "assistant"), "")
    found = _in(last_answer)
    return found[0] if len(found) == 1 else None


async def _holiday_answer(state: dict, query: str) -> str:
    """The next holiday (or the upcoming list) from erp-api's holiday
    calendar for the caller's department. erp-api's own words when it has no
    calendar for them."""
    # "iss 25 dec a holiday", "holidayy list": read as meant (pilot run, 28 Oct).
    query = fold_holiday_typos(query or "")
    try:
        result = await erp_client.get_leave_holidays(
            state.get("bearer_token"), company_id=state.get("company_id"),
            conversation_id=state.get("conversation_id"))
    except erp_client.ErpApiUnavailable as exc:
        return (getattr(exc, "erp_message", None)
                or "I couldn't load the holiday calendar right now - please try again shortly.")
    except Exception:
        return "I couldn't load the holiday calendar right now - please try again shortly."
    body = (result or {}).get("body") or {}
    if not body.get("success", True):
        return body.get("message") or "The holiday calendar isn't available for you right now."
    holidays = (body.get("data") or {}).get("holidays") or []
    today_iso = _today_in_app_timezone().isoformat()
    upcoming = sorted((h for h in holidays if str(h.get("holiday_date") or "") >= today_iso),
                      key=lambda h: str(h.get("holiday_date")))

    def _line(h):
        try:
            d = _dt.strptime(str(h.get("holiday_date"))[:10], "%Y-%m-%d").strftime("%a, %d %b %Y")
        except ValueError:
            d = h.get("holiday_date")
        return f"{h.get('holiday_name') or 'Holiday'} - {d}"

    if _IS_IT_A_HOLIDAY_RE.search(query or ""):
        named = None
        # "is 25 Dec a holiday" names a date, not a holiday.
        try:
            asked = date_query_resolver.resolve(query, _today_in_app_timezone())
        except Exception:
            asked = None
        if isinstance(asked, dict) and asked.get("type") == "single":
            asked_iso = asked["date"].isoformat()
            named = next((h for h in holidays if str(h.get("holiday_date") or "")[:10] == asked_iso), None)
            if named is None:
                return f"{asked['date'].strftime('%a, %d %b %Y')} isn't on your holiday calendar."
        named = named or _holiday_named_in(holidays, query, state.get("context") or [])
        if named:
            return f"Yes - {_line(named)} is on your holiday calendar."
        # "Is Diwali a holiday?" names its subject: with Diwali missing from
        # the calendar - or no calendar at all - it got "Which holiday do you
        # mean?" (HAI-GEN-27 re-test, 29 Oct).
        subject = re.search(r"\bis\s+(?P<s>[\w.-]+(?:\s+[\w.-]+){0,2})\s+a\s+", query or "", re.IGNORECASE)
        subject = subject.group("s") if subject else ""
        if subject and subject.lower() not in ("it", "this", "that", "there", "today", "tomorrow"):
            if not holidays:
                return (f"There are no holidays on your holiday calendar yet, so {subject} isn't "
                        f"listed as one. HR can confirm whether it will be added.")
            msg = f"{subject} isn't on your holiday calendar."
            if upcoming:
                msg += " Your upcoming holidays:\n" + "\n".join(f"- {_line(h)}" for h in upcoming)
            return msg
        # The whole chat was searched, so a subject that was discussed is not
        # on the calendar. With nothing before the question, "it" names
        # nothing - ask (UAT UV-01).
        msg = ("I can't see that on your holiday calendar." if state.get("context")
               else "Which holiday do you mean?")
        if upcoming:
            msg += " Your upcoming holidays:\n" + "\n".join(f"- {_line(h)}" for h in upcoming)
        return msg

    # "List holidays in December" listed November's too (HAI-GEN-27 re-test,
    # 29 Oct): a named month is that month of this year's calendar.
    month = re.search(r"\b(?:in|for|during|of)\s+(?P<m>jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\b",
                      query or "", re.IGNORECASE)
    if month:
        month_no = _dt.strptime(month.group("m")[:3].title(), "%b").month
        year = _today_in_app_timezone().year
        in_month = sorted((h for h in holidays
                           if str(h.get("holiday_date") or "")[:7] == f"{year}-{month_no:02d}"),
                          key=lambda h: str(h.get("holiday_date")))
        name = _dt(year, month_no, 1).strftime("%B %Y")
        if not in_month:
            return f"There are no holidays on your calendar in {name}."
        n = len(in_month)
        return (f"{n} {'holiday' if n == 1 else 'holidays'} in {name}:\n"
                + "\n".join(f"- {_line(h)}" for h in in_month))

    # "How many holidays this year": the count of the WHOLE year's calendar,
    # then what is still to come - not only the remaining ones.
    # A count asked after the list too: "how many are left?" (pilot run, 28
    # Oct: answered with the list alone, the number never said).
    asks_count = _HOW_MANY_HOLIDAYS_RE.search(query or "") or _HOW_MANY_RE.search(query or "")
    if asks_count and _LEFT_RE.search(query or "") and not re.search(r"\btotal\b", query or "", re.I):
        if not upcoming:
            return "There are no more holidays on your calendar this year."
        n = len(upcoming)
        return (f"{n} {'holiday is' if n == 1 else 'holidays are'} still to come this year:\n"
                + "\n".join(f"- {_line(h)}" for h in upcoming))
    if asks_count:
        data = body.get("data") or {}
        year = str(data.get("year") or _today_in_app_timezone().year)
        in_year = [h for h in holidays if str(h.get("holiday_date") or "")[:4] == year]
        total = len(in_year) or data.get("total_holidays") or 0
        if not total:
            return f"There are no holidays on your holiday calendar for {year}."
        msg = f"There {'is 1 holiday' if total == 1 else f'are {total} holidays'} on your holiday calendar for {year}."
        if upcoming:
            msg += (f" {len(upcoming)} {'is' if len(upcoming) == 1 else 'are'} still to come:\n"
                    + "\n".join(f"- {_line(h)}" for h in upcoming))
        else:
            msg += " All of them have already passed."
        return msg

    if not upcoming:
        return "There are no more holidays on your calendar this year."
    wants_list = re.search(r"\b(?:list|calendar|schedule|holidays|all|how\s+many|remaining|rest|left)\b",
                           query or "", re.IGNORECASE)
    if wants_list:
        return "Your upcoming holidays:\n" + "\n".join(f"- {_line(h)}" for h in upcoming)
    nxt = upcoming[0]
    rest = upcoming[1:3]
    msg = f"Your next holiday is {_line(nxt)}."
    if rest:
        msg += " After that: " + "; ".join(_line(h) for h in rest) + "."
    return msg


#: Wording that ties a question to THIS company's rules or the caller's own
#: record - never answered from general knowledge.
_COMPANY_SPECIFIC_RE = re.compile(
    r"\b(?:our|my|mine|i|we|us|company|company's|organi[sz]ation|firm|employer|office|"
    r"policy|policies|rule|rules|entitle\w*|eligib\w*|allowed|allowance|leave|leaves|"
    r"holiday|holidays|notice\s+period|probation|payroll|salary|attendance|shift|"
    r"helixta|hr)\b",
    re.IGNORECASE)


OWN_PAY_MESSAGE = ("I can't see your salary or payslip details here. Please check your "
                   "payslip in the Payroll section, or contact HR.")

_OWN_PAY_RE = re.compile(
    r"\b(?:my|mine|i|me)\b[^.?!]{0,40}\b(?:salary|salaries|pay|payslip|pay\s*slip|ctc|"
    r"net\s+pay|gross\s+pay|take[\s-]*home|wages?|earnings|in[\s-]*hand|deductions?|bonus)\b"
    r"|\b(?:salary|payslip|pay\s*slip|ctc|take[\s-]*home|wages?)\b[^.?!]{0,30}\b(?:my|mine|me|i)\b",
    re.IGNORECASE)


def _asks_for_own_pay(query: str) -> bool:
    """True for a question about the caller's OWN pay ("what is my salary
    this month", "show my payslip", "how much do I take home")."""
    return bool(_OWN_PAY_RE.search(query or ""))


def _asks_about_someones_employment_record(query: str) -> bool:
    """"When did Priya Sharma leave the company?", "Is Rohan Mehta an employee
    here?", "What was their exit date?" - a person other than the caller.
    The caller's own ("when did I join") is not this."""
    q = query or ""
    if _PERSON_EMPLOYMENT_RE.search(q):
        return bool(_THIRD_PARTY_RE.search(q)) or not _FIRST_PERSON_ONLY_RE.search(q)
    return bool(_RECORD_WORD_RE.search(q) and _THIRD_PARTY_RE.search(q))


_ABOUT_THE_CARD_RE = re.compile(
    r"\b(?:why|how\s+come|explain|what\s+does\s+(?:it|this|that)\s+mean|fix|correct|"
    r"which\s+(?:one|request|day|leave)|oldest|newest|latest|earliest|it|this|that|these|those|them)\b",
    re.IGNORECASE)


def _asks_about_the_card_shown(query: str, context: list) -> bool:
    """A short question about the card the last answer showed ("Why is it
    showing Not Recorded?", "How do I fix it?", "Interesting, why is that?",
    "Which one is the oldest?"). UAT UV-02: these were classified policy, the
    documents had nothing, and the "I do not have this information" template
    went out - the answer was on the card. Answered from that card's data,
    which history_text puts in the context."""
    if len((query or "").split()) > 12 or not _ABOUT_THE_CARD_RE.search(query or ""):
        return False
    last = next((m.get("content") or "" for m in reversed(context or [])
                 if m.get("role") == "assistant"), "")
    return "(Card data shown with this answer:" in last


def _presses_for_a_guess_after_fallback(query: str, context: list) -> bool:
    """"Just give me your best guess" straight after the fallback was given."""
    if not _GUESS_PRESSURE_RE.search(query or ""):
        return False
    last = next((m.get("content") or "" for m in reversed(context or [])
                 if m.get("role") == "assistant"), "")
    return last.strip() == NO_INFO_FALLBACK


CHAT_SUMMARY_INSTRUCTION = (
    "The user is asking for a summary of THIS conversation. Summarise it from its FIRST "
    "message, not just your last answer: cover every topic in the order it came up. A bare "
    "request (\"summary\", \"summarize\", \"Summary de do\", \"recap\") means the whole "
    "conversation. If they name one topic (\"what we discussed about yoga\"), cover every "
    "turn on that topic, however far back, and leave the others out. Use only what was "
    "actually said here; add nothing new. Write it as plain text: a numbered list, one point "
    "per line, with no bold (**), no headings and no title line (UAT UV-06: the summary "
    "showed literal asterisks). Never include \"(Card data ...)\" text or raw JSON.")

NO_EARLIER_MESSAGES_NOTE = (
    " This is the FIRST message of the conversation: nothing was said before it, so do not "
    "refer to anything earlier - react to this message alone.")


def _is_conversational_turn(intent: Optional[str], query: str) -> bool:
    """Greetings and small talk, and any message with no words at all ("...",
    an emoji) whatever the classifier called it - QA: "..." came back
    conversation_meta and was answered "How can I assist you with HR?"."""
    return intent in ("greeting", "small_talk") or not re.search(r"\w", query or "")


_DEVANAGARI_RE = re.compile(r"[ऀ-ॿ]")


async def _answer_under_turn_instruction(state: HRState, writer: StreamWriter) -> dict:
    """classify_node's turn_instruction, answered by the model - in its own
    words each time, not one fixed text (UAT UV-12: "..." and another
    employee's payslip got the same "could cause real harm" refusal,
    repeatedly). No earlier messages: live, "..." was answered with a reply to
    the two messages before it. turn_fallback if the model gives nothing."""
    query = state["query"]
    # A message in English gets English. Phrased only as "Hinglish gets
    # Hinglish", the model answered plain English questions in Hinglish.
    language_rule = (" Reply in the language of the user's message: a message written in English "
                     "gets an English reply. Only a message that is itself mostly Hindi typed in "
                     "English letters (Hinglish, e.g. \"mujhe chutti chahiye\") gets a Hinglish reply.")
    usage_events = list(state.get("usage_events", []))

    async def _reply(extra: str = "") -> str:
        messages = [{"role": "system", "content": HR_SYSTEM_PROMPT},
                    {"role": "system", "content": state["turn_instruction"] + language_rule + extra},
                    {"role": "user", "content": query}]
        out = ""
        try:
            async for event in _call_llm_stream(messages, max_tokens=LLM_MAX_TOKENS, use_tools=False):
                if event["type"] == "chunk":
                    out += event["content"]
                elif event["type"] == "usage":
                    usage_events.append({"source": "chat", "usage": event["usage"]})
        except Exception as e:
            logger.warning(f"[Graph] turn-instruction reply failed: {e}")
        return out.strip()

    # Collected, then sent: these are one to three sentences, and a reply in
    # Devanagari to a message typed in English letters is asked again
    # ("mere dost ko leave chahiye" got Hindi script on one live run of three).
    text = await _reply()
    if text and _DEVANAGARI_RE.search(text) and not _DEVANAGARI_RE.search(query):
        text = await _reply(" The user wrote in English letters, so write your reply in English.")
        if _DEVANAGARI_RE.search(text):
            text = ""
    if not text:
        text = state.get("turn_fallback") or "Could you please clarify what you mean?"
    writer({"type": "chunk", "content": text})
    writer({"type": "done", "intent": state.get("intent"), "is_hr": True,
            "data": {"answer": text}, "message": text, "usage_events": usage_events})
    return {"response_text": text, "output_guardrail": {"status": "skipped"},
            "usage_events": usage_events}


async def hr_response_node(state: HRState, writer: StreamWriter) -> dict:
    context = state.get("context", [])
    query = state["query"]
    # The LLM classifier chose apply_for_someone_else (wording the rules did
    # not catch): the same model-written "only you can apply" reply.
    if (state.get("intent") == classify_node_mod.APPLY_FOR_SOMEONE_ELSE_INTENT
            and not state.get("turn_instruction")):
        state = {**state, "turn_instruction": classify_node_mod.APPLY_FOR_SOMEONE_ELSE_INSTRUCTION,
                 "turn_fallback": classify_node_mod.APPLY_FOR_SOMEONE_ELSE_MESSAGE}
    if state.get("turn_instruction"):
        return await _answer_under_turn_instruction(state, writer)

    # A policy question whose answer is genuinely not in the company's own
    # documents is answered by saying so, not by falling through to general HR
    # knowledge and a web search. Those produced a confident, well-formatted
    # answer sourced from other companies' HR blogs — the worst possible
    # outcome for a question phrased "what is MY company policy".
    # Only a question CLASSIFIED as policy gets the "not in our documents"
    # answer. The other document-backed intents (employee_management,
    # compliance, benefits...) consult the documents opportunistically -- they
    # might be answerable from them -- so a miss there must fall through to
    # the ordinary answer, exactly as before RAG was consulted at all.
    # Declining on those would turn a lookup that was meant to add something
    # into one that takes an answer away.
    # A named person's employment record ("when did Priya Sharma leave the
    # company?", "what was Ayush Chandra's exit date?") is answered from the
    # company's own system or not at all. QA: these reached the web-search
    # answer below and came back with a LinkedIn snippet about the real
    # employee, and a stranger of the same name's career ("moved to India in
    # 2011 for a role at Wonga") - then, pushed to "just guess", an invented
    # exit year. Nothing in this node has the company's HR records, so the
    # approved fallback is the only honest answer, and a push to guess after
    # it gets the same answer again.
    if _asks_about_someones_employment_record(query) or _presses_for_a_guess_after_fallback(
            query, context):
        logger.info("[Graph] employment-record question with no system data — fallback, no web search")
        writer({"type": "chunk", "content": NO_INFO_FALLBACK})
        writer({"type": "done", "intent": state.get("intent", "general"), "is_hr": True,
                "data": {"answer": NO_INFO_FALLBACK}, "message": NO_INFO_FALLBACK,
                "usage_events": state.get("usage_events", [])})
        return {"response_text": NO_INFO_FALLBACK, "output_guardrail": {"status": "skipped"},
                "usage_events": state.get("usage_events", [])}

    # The company's leave policy comes from its LEAVE CONFIGURATION in erp-api
    # (the same data the balance is computed from), not from a generic
    # document or the model. QA HA884-TC-016: "What is the company leave
    # policy?" answered from a template ("suggested: Casual Leave 8 days", or
    # "[X]" placeholders) while the user's allocation was 100. Falls back to
    # the document path below when the configuration cannot be loaded.
    if state.get("intent") != "general_chat" and _LEAVE_POLICY_QUESTION_RE.search(query or ""):
        msg = (state.get("configured_policy_answer")
               or await _configured_leave_policy_answer(state, query))
        if msg:
            writer({"type": "chunk", "content": msg})
            writer({"type": "done", "intent": "leave_policy", "is_hr": True,
                    "data": {"answer": msg, "source": "leave_configuration"}, "message": msg,
                    "usage_events": state.get("usage_events", [])})
            return {"response_text": msg, "output_guardrail": {"status": "skipped"},
                    "usage_events": state.get("usage_events", [])}

    # Holidays come from the company's holiday calendar, never from the model.
    # QA HA884-TC-018: "When is the next holiday?" went to the policy search
    # and came back "I do not have this information"; on a retry the model
    # invented one ("The next holiday is the upcoming Wednesday, 13 Oct 2026").
    # The intent alone is enough too: "When is the next one?" after the
    # holiday answer has no holiday word (QF-01) - classify_node labelled it.
    if state.get("intent") == "leave_holidays" or (
            state.get("intent") != "general_chat" and _HOLIDAY_QUESTION_RE.search(query or "")):
        msg = await _holiday_answer(state, query)
        writer({"type": "chunk", "content": msg})
        writer({"type": "done", "intent": "leave_holidays", "is_hr": True,
                "data": {"answer": msg}, "message": msg,
                "usage_events": state.get("usage_events", [])})
        return {"response_text": msg, "output_guardrail": {"status": "skipped"},
                "usage_events": state.get("usage_events", [])}

    # The caller's OWN pay. This node has no payroll access: answered from the
    # model, "what is my salary this month" read a payslip figure out of the
    # company documents the policy search returned and streamed it as the
    # employee's own net pay (QA sheet: "₹ 83,501.40" for an April-May
    # period). A market question ("what does a data analyst earn") is not
    # first-person and still goes to the model.
    if state.get("intent") in ("salary", "payroll") and _asks_for_own_pay(query):
        msg = OWN_PAY_MESSAGE
        logger.info("[Graph] own-pay question - no payroll access, answering without the model")
        writer({"type": "chunk", "content": msg})
        writer({"type": "done", "intent": state.get("intent"), "is_hr": True,
                "data": {"answer": msg}, "message": msg,
                "usage_events": state.get("usage_events", [])})
        return {"response_text": msg, "output_guardrail": {"status": "skipped"},
                "usage_events": state.get("usage_events", [])}

    # A general HR-THEMED question the company documents don't cover ("Summarise
    # the benefits of remote work") is general knowledge, not this company's
    # policy: with general chat on it gets a general answer instead of "I do
    # not have this information" (QA HA884-TC-031). A question about THIS
    # company's rules keeps the honest fallback below - the general lane must
    # not invent company policy.
    # With the general lane off (main.py: non-HR questions always go to
    # non_hr_node) this used to skip straight to the fallback - UAT, 27 Oct:
    # "Summarise the benefits of remote work" got "I do not have this
    # information". The same non_hr_node every other general question gets.
    if (state.get("intent") == "policy"
            and state.get("policy_lookup_failed") and not state.get("policy_context")
            and not _COMPANY_SPECIFIC_RE.search(query)):
        if state.get("general_chat_enabled") is True:
            logger.info("[Graph] policy documents have no answer for a general question - "
                        "answering it in the general lane")
            return await general_chat_node(state, writer)
        logger.info("[Graph] policy documents have no answer for a general question - non_hr_node")
        return await non_hr_node(state, writer)

    if (state.get("intent") == "policy"
            and state.get("policy_lookup_failed") and not state.get("policy_context")
            and not _asks_about_the_card_shown(query, context)):
        # The approved fallback template (QA TC-KG03/KG04): every unanswerable
        # question gets the same words, not ad-hoc phrasing.
        msg = NO_INFO_FALLBACK
        logger.info("[Graph] policy question not covered by the documents — declining")
        writer({"type": "chunk", "content": msg})
        writer({"type": "done", "intent": state.get("intent", "policy"), "is_hr": True,
                "data": {"answer": msg}, "message": msg,
                "usage_events": state.get("usage_events", [])})
        return {"response_text": msg, "output_guardrail": {"status": "skipped"},
                "usage_events": state.get("usage_events", [])}

    # "show my policy": what every policy says, written from the excerpts
    # policy_rag_node retrieved — with ITS OWN prompt, not the chat prompt
    # below, which answered "Which specific policy would you like to see?"
    # instead of showing them. Streamed: in one piece it took ~31s with
    # nothing on screen.
    if state.get("policy_overview") and state.get("policy_context"):
        retrieved_text = state["policy_context"]
        usage_events = list(state.get("usage_events", []))
        overview = ""
        captured_usage = None
        try:
            async for event in _call_llm_stream(_policy_overview_prompt(retrieved_text),
                                                max_tokens=LLM_MAX_TOKENS, use_tools=False):
                if event["type"] == "chunk":
                    overview += event["content"]
                    writer({"type": "chunk", "content": event["content"]})
                elif event["type"] == "usage":
                    captured_usage = event["usage"]
        except Exception as e:
            logger.warning(f"[Graph] policy overview stream failed: {e}")
        if captured_usage:
            usage_events.append({"source": "policy_overview", "usage": captured_usage})
        if not overview.strip():
            # Nothing streamed: the policy names alone, which are never wrong.
            overview = _policy_names_fallback(retrieved_text) or NO_INFO_FALLBACK
            writer({"type": "chunk", "content": overview})
        writer({"type": "done", "intent": state.get("intent", "policy"), "is_hr": True,
                "data": {"answer": overview}, "message": overview,
                "usage_events": usage_events})
        return {"response_text": overview, "output_guardrail": {"status": "skipped"},
                "usage_events": usage_events}

    messages = [{"role": "system", "content": HR_SYSTEM_PROMPT}]
    policy_context = state.get("policy_context")
    if policy_context:
        messages.append({
            "role": "system",
            "content": (
                "Relevant company policy information retrieved for this question — "
                "prefer this over general HR best practice where it applies, and do "
                "not contradict it.\n\n"
                # This is the company's OWN document, so HR_SYSTEM_PROMPT's
                # hedging rules ("typically", "verify with HR", never say "the
                # policy is") are wrong here and make a definite answer read as
                # a guess. They stay in force for everything NOT in the excerpts.
                "Everything in these excerpts is this company's actual policy: state it "
                "directly, without hedging. Hedge only where you step outside them.\n\n"
                + POLICY_ANSWER_FORMAT + "\n\n"
                "Policy excerpts:\n" + policy_context
            ),
        })
    if _is_conversational_turn(state.get("intent"), query):
        instruction = SMALL_TALK_TURN_INSTRUCTION
        if not context:
            # QA: "wow" in a new chat got "I know - those attendance details
            # can be eye-opening": told reactions answer the previous message,
            # the model invented one.
            instruction += NO_EARLIER_MESSAGES_NOTE
        messages.append({"role": "system", "content": instruction})
    # QA LF-01 (LT-06): "Summary de do" reached this node with the whole chat
    # and was still answered with a summary of the LAST answer only.
    if state.get("intent") == "conversation_meta" and is_chat_summary_request(query):
        messages.append({"role": "system", "content": CHAT_SUMMARY_INSTRUCTION})
    for msg in context:
        role = msg.get("role", "user")
        if role not in ("user", "assistant"):
            role = "user"
        content = msg.get("content", "")
        if content:
            messages.append({"role": role, "content": content})
    messages.append({"role": "user", "content": query})

    usage_events = list(state.get("usage_events", []))
    full_text = ""
    captured_usage = None
    try:
        # policy_context already carries an authoritative retrieved-document
        # summary — a web search on top would be a redundant round trip
        # (race always searches when use_tools=True) whose public results
        # could dilute or contradict it, so tools are suppressed whenever
        # it's present.
        #
        # And never unless HR_WEB_SEARCH_ENABLED says so (default OFF). Internet
        # browsing is out of scope for Helix AI (HA-884): with it on, "What is a
        # salary slip?" was answered "per Zoho Payroll, Salesforce India and
        # RazorpayX" with the article titles (QA HA884-TC-029).
        async for event in _call_llm_stream(messages, max_tokens=LLM_MAX_TOKENS,
                                            use_tools=_hr_web_search_enabled() and not policy_context):
            if event["type"] == "searching":
                logger.info("[Graph] Web search triggered by LLM")
                writer({"type": "searching", "message": "Searching the web..."})
            elif event["type"] == "chunk":
                full_text += event["content"]
                writer({"type": "chunk", "content": event["content"]})
            elif event["type"] == "usage":
                captured_usage = event["usage"]
    except Exception as e:
        logger.exception(f"[Graph] LLM stream failed: {e}")
        writer({"type": "error", "message": "Sorry, something went wrong while I was putting that answer together — please try again."})
        return {"response_text": "", "output_guardrail": {"status": "skipped"}, "usage_events": usage_events}

    if not full_text:
        writer({"type": "error", "message": "Sorry, I didn't quite get an answer together there — could you try asking again?"})
        return {"response_text": "", "output_guardrail": {"status": "skipped"}, "usage_events": usage_events}

    if captured_usage:
        usage_events.append({"source": "chat", "usage": captured_usage})
    else:
        prompt_text = "\n".join(m.get("content", "") for m in messages)
        usage_events.append({"source": "chat", "usage": {
            "prompt_tokens": estimate_tokens(prompt_text),
            "completion_tokens": estimate_tokens(full_text),
            "total_tokens": estimate_tokens(prompt_text) + estimate_tokens(full_text),
        }, "is_estimated": True})

    parsed = {"answer": full_text}
    if full_text.strip().startswith("{"):
        try:
            parsed = _safe_json_parse(full_text)
        except Exception:
            pass

    message = _build_user_message(state["intent"], parsed)
    logger.info(f"[Graph] Response complete | intent={state['intent']}")

    writer({
        "type": "done",
        "intent": state["intent"],
        "is_hr": True,
        "data": parsed,
        "message": message,
        "usage_events": usage_events,
    })
    return {"response_text": full_text, "output_guardrail": {"status": "skipped"}, "usage_events": usage_events}


# ── Node 4: Apply-leave / leave-balance (AC#2-#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.

# Informational intents whose answer plausibly lives in the company's own
# policy documents, so they consult RAG before falling back to general HR
# knowledge. "policy" itself is routed explicitly above; these are the ones
# a question can land on when the classifier reads it as a topic rather than
# as a policy lookup -- "what happens if I resign" (employee_management),
# "what is the notice period" (compliance), "how many WFH days" (attendance
# wording). Greetings, small talk and conversation_meta are excluded: there
# is nothing to look up and a retrieval on "hi" is pure latency.
# Grammatical markers of a CONDITION or process qualifier. Their presence
# turns "can I take leave" from a question about this employee into a question
# about a rule: "can I apply leave IF my balance is zero", "can I take leave
# WITHOUT approval", "WHAT HAPPENS IF I don't inform".
#
# Deliberately grammar, not vocabulary. Listing the domain phrasings ("without
# approval", "balance is zero", "after the date") is the enumerate-the-world
# trap -- there is always one more. A subordinate clause means they are asking
# what the rule is under some circumstance, whatever circumstance they name,
# and the rule lives in a document rather than in their record.
_CONDITIONAL_MARKER_RE = re.compile(
    r"\b(if|unless|in\s+case|what\s+happens|suppose|whenever|"
    r"without|beyond|exceed(s|ed)?|more\s+than|less\s+than|"
    r"even\s+though|despite|regardless)\b",
    re.IGNORECASE,
)

# WHEN the leave would fall is a condition too, and the eligibility node has
# nothing to evaluate for it: it reads the caller's confirmation status, which
# says nothing about whether the company allows leave on a Wednesday, a
# weekend or a public holiday. Those answers live in the policy documents.
#
# Reported live: "can I take a leave on wednesday" reached the eligibility
# node and came back with the menu of leave types -- an answer to a question
# nobody asked -- because a day name was not recognised as a condition. The
# taxonomy already called "on a holiday" a policy qualifier; this makes the
# routing agree with it.
#
# A DATE is deliberately absent. "Can I take leave on 28 January" is close to
# an application, and _WHEN_CONDITION_RE only ever runs on a question the
# classifier already called leave_eligibility, so it must not reach for
# anything that specific.
_WHEN_CONDITION_RE = re.compile(
    r"\b(monday|tuesday|wednesday|thursday|friday|saturday|sunday|"
    r"weekend|weekends|week\s*end|public\s+holiday|holidays?|"
    r"festival|off\s+day|non[\s-]?working\s+day)s?\b",
    re.IGNORECASE,
)

# Personal-status words the eligibility NODE answers better than any document,
# because it reads the caller's own confirmation status from erp-api. "Can I
# take leave if I am still on probation" is about THEM even though it has a
# condition in it, so it must stay with the node.
_PERSONAL_STATUS_RE = re.compile(
    r"\b(probation|probationary|confirmed|confirmation|notice\s+period|"
    r"my\s+joining|date\s+of\s+joining|doj|new\s+joinee)\b",
    re.IGNORECASE,
)


def _eligibility_question_is_really_a_rule(query: str) -> bool:
    """True when a "can I ...?" is asking about a RULE, not about this person.

    leave_eligibility is record-backed: it looks up the caller's confirmation
    status and reports which leave types they qualify for. A question with a
    CONDITION attached is not that -- it asks what the policy says under some
    circumstance, and the node has nothing to evaluate. Left alone it reaches
    LEAVE_TYPE_NOT_SPECIFIED and replies with a menu of leave types, which
    answers a question nobody asked. Observed twice: "can I take leave without
    approval" and "can I apply leave if my balance is zero".
    """
    q = query or ""
    if _PERSONAL_STATUS_RE.search(q):
        return False
    return bool(_CONDITIONAL_MARKER_RE.search(q) or _WHEN_CONDITION_RE.search(q))


_DOCUMENT_BACKED_INTENTS = frozenset({
    "general_hr", "employee_management", "compliance", "benefits",
    "payroll", "salary", "onboarding", "training", "performance",
    "recruitment", "experience", "skills",
})

_LEAVE_ACTION_INTENTS = {"leave_balance", "apply_leave", "leave_status", "cancel_leave"}
_PUNCH_DETAILS_INTENTS = {"punch_details"}
# NOTE: named distinctly from _ATTENDANCE_INTENTS below — that one is the
# plain "attendance" intent (live record lookup, attendance_node), this one
# is "attendance_explain" (WHY a specific day was classified a certain way,
# attendance_explain_node). Easy to conflate since both are attendance-
# adjacent; keep the names apart.
_ATTENDANCE_EXPLAIN_INTENTS = {"attendance_explain"}
_ATTENDANCE_INTENTS = {"attendance"}
_HRMS_REGULARIZATION = {"regularisation"}
# Intents a bare date fragment can legitimately RE-TARGET on the next turn
# ("4th Wednesday of August 2026" after a punch-details answer means "the
# same question, for that day instead"). All four are single-topic,
# date-driven lookups whose only real variable IS the date.
#
# Deliberately excludes the leave intents: a date arriving mid-apply-leave
# is a slot reply, owned by leave_slot_service's own mid-flow handling
# (classify_node's Fast-path 0.5), and re-classifying it here would
# pre-empt that flow.
_DATE_REFINABLE_INTENTS = frozenset(
    _PUNCH_DETAILS_INTENTS | _ATTENDANCE_INTENTS | _ATTENDANCE_EXPLAIN_INTENTS | _HRMS_REGULARIZATION
)
_HALF_DAY_SLUGS = {"first_half_day", "second_half_day", "half_day"}
_SESSION_TYPE_REQUIRED_LEAVE_TYPES = {"casual_leave", "sick_leave", "earned_leave"}


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


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


def _today_in_app_timezone():
    """The reference 'today' for deterministic date resolution — NOT a
    naive datetime.date.today() (server-local; could silently disagree with
    the company's actual day near midnight). Reuses the same QUOTA_TIMEZONE
    env var and re-read-per-call pattern already established in
    quota_service._get_timezone(), so the whole app shares one configured
    notion of 'today' rather than each feature picking its own."""
    import os
    from datetime import datetime
    from zoneinfo import ZoneInfo
    return datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))).date()


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 leave_action_node's _llm_date_needs_confirmation call, 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. Live bug: "apply leave from november
    first week to end of the first week" left both dates unresolved
    entirely (neither the weekday-anchored range above nor the LLM
    recognized this phrasing), so the bot re-asked for dates it had
    effectively already been given.

    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). Live bug: "apply casual leave for november first week coming
    wednesday for 1 day" was treated as a 7-day request for the entire
    first week ("...but this request needs 7.0"), silently ignoring both
    the weekday narrowing and the explicit "for 1 day" — because the old
    code returned immediately with the full span before either could be
    considered.

    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. Live bug: 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 — "next Sunday" (checked
    earlier in date_resolver._PATTERNS) silently won over "upcoming
    Wednesday" (which actually appears first), hallucinating a wrong,
    non-contiguous range instead of a clean forward span."""
    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).
    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

    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, found by mining real production queries: "next month first
    # week wednesday" / "monday in next month first week" / "wednesday in
    # the second week of next month" (retried at least 7 times across
    # different word orders) matched no deterministic pattern at all —
    # only bare "next_month" matched, which is deliberately discarded
    # below as ambiguous, so every one of these attempts fell through to
    # "ask, don't guess" even though "next month's Nth week, narrowed to a
    # weekday" is exactly as well-defined as the already-supported "first
    # week of November". Same top precedence tier as week-of-month, for
    # the same reason: a resolved week span already implies both endpoints
    # unless further narrowed to a single weekday.
    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:
        nm_start, nm_end = next_month_week_result
        if nm_start >= today:
            next_month_week_narrowed_to_weekday = date_resolver.weekday_within_span(query, nm_start, nm_end)
            if next_month_week_narrowed_to_weekday is None:
                slots["from_date"] = nm_start.isoformat()
                slots["to_date"] = nm_end.isoformat()
                logger.info(
                    "[Graph] Deterministic week-of-next-month range override: %s..%s", nm_start, nm_end,
                )
                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"],
            )

    # 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 starting a week
    # from today 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, not yet reported): "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" each
    # used to silently collapse to just the first endpoint — the same bug
    # shape range_result/weekday_range_result above were already built to
    # fix for their own phrase families, just never extended to these
    # three. Checked at this same top precedence tier for the same reason:
    # a resolved 2-endpoint range implies both dates on its own.
    next_month_range_result = date_resolver.resolve_next_month_weekday_range_phrase(query, today)
    if next_month_range_result and next_month_range_result[1] is not None:
        first, second = next_month_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_range_result = date_resolver.resolve_this_month_weekday_range_phrase(query, today)
    if this_month_range_result and this_month_range_result[1] is not None:
        first, second = this_month_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

    this_week_range_result = date_resolver.resolve_this_week_weekday_range_phrase(query, today)
    if this_week_range_result and this_week_range_result[1] is not None:
        first, second = this_week_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

    # Ordered single-anchor candidates, most specific first — a plain list
    # lookup rather than a deeply nested if/else ternary, since this chain
    # already had 4+ branches before these 3 additions and a hand-written
    # ternary that size is a real correctness risk to get right on a single
    # edit (each candidate here reuses the range results computed above,
    # rather than re-running their regex search a second time).
    _single_anchor_candidates = [
        numeric_range_result[0] if numeric_range_result else None,
        range_result[0] if range_result else None,
        weekday_range_result[0] if weekday_range_result else None,
        week_narrowed_to_weekday,
        next_month_week_narrowed_to_weekday,
        next_month_range_result[0] if next_month_range_result else None,
        this_month_range_result[0] if this_month_range_result else None,
        this_week_range_result[0] if this_week_range_result else None,
        date_resolver.resolve_relative_duration_offset_phrase(query, today),
        date_resolver.resolve_relative_date_phrase(query, today),
    ]
    resolved = next((c for c in _single_anchor_candidates if c), None)
    # 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 (an
    # assumption the user meant "starting the 1st"), which the apply-leave
    # flow must never do. Always discard this match here — regardless of
    # whether the query also names a weekday/week (that was the original,
    # narrower guard: a weekday/week mention was treated as a signal of a
    # more-specific-but-unparsed phrase; a bare mention with NEITHER signal
    # is just as ambiguous and needs the same treatment) — and let it fall
    # through to _llm_date_needs_confirmation's ambiguous-phrase safety net
    # (see its own text_recognized exclusion for "next_month", which keeps
    # this case from being treated as "already vetted") instead of
    # confidently returning an unannounced guess.
    if resolved and resolved.get("matched_kind") == "next_month":
        logger.info(
            "[Graph] Discarding bare 'next month' match — no day/weekday named, "
            "genuinely ambiguous which date within the month. query=%r", query,
        )
        resolved = None
    if resolved:
        slots["from_date"] = resolved["from_date"]
        if not llm_gave_distinct_range:
            slots["to_date"] = resolved["from_date"]
        logger.info(
            "[Graph] Deterministic date override: %r -> %s",
            resolved["matched_phrase"], resolved["from_date"],
        )

    duration_days = date_resolver.extract_duration_days(
        query, exclude=resolved["matched_phrase"] if resolved else None,
    )
    if duration_days and slots.get("from_date"):
        if llm_gave_distinct_range:
            try:
                actual_days = (date.fromisoformat(slots["to_date"]) - date.fromisoformat(slots["from_date"])).days + 1
                if actual_days != duration_days:
                    logger.warning(
                        "[Graph] Duration count (%s day(s)) conflicts with explicit date range "
                        "(%s day(s), %s to %s) — explicit range takes precedence. query=%r",
                        duration_days, actual_days, slots["from_date"], slots["to_date"], query,
                    )
            except (TypeError, ValueError):
                pass
        else:
            try:
                computed_to = date.fromisoformat(slots["from_date"]) + timedelta(days=duration_days - 1)
                slots["to_date"] = computed_to.isoformat()
                logger.info(
                    "[Graph] Deterministic duration override: %s day(s) -> to_date=%s",
                    duration_days, slots["to_date"],
                )
            except (TypeError, ValueError):
                pass

    return bool(resolved)


# ── Confirming an LLM-only date that the deterministic layer never saw ─────
# _apply_deterministic_date_overrides above only ever OVERRIDES a date it
# recognizes — for query text it doesn't recognize at all, it silently
# no-ops, so whatever the LLM guessed stands with zero cross-check. That's
# fine for the common case (an explicit absolute date like "12th November"
# or "2026-09-15" — date_resolver deliberately never touches these, see its
# module docstring, and the LLM is reliable at literal parsing with no
# arithmetic involved). It's NOT fine for genuinely relative phrasing
# date_resolver just doesn't have a pattern for yet ("the Monday after
# next", "wednesday off next week" — word order date_resolver's regex
# doesn't match), where the LLM is doing the same kind of multi-step
# weekday arithmetic it's been repeatedly shown to get wrong (see this
# module's own diagnostic sweep, 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 (see _apply_deterministic_date_overrides's docstring) — 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


# Systemic gap found via audit: tier 2's LLM gate and tier 3's "don't trust
# it, ask instead" cross-check used to each hand-duplicate the identical
# _find_named_weekday(...) or _RELATIVE_DATE_QUALIFIER_PATTERN.search(...)
# expression — which is exactly how a third signal (duration-offset
# phrases like "in two weeks") went missing from both places at once: it
# was only ever going to be added to one copy. One shared predicate now
# backs both call sites, so any future signal only needs adding here.
#
# `today` is required (not just `query`) because the fourth signal below —
# an already-passed bare day-of-month — is only ambiguous relative to what
# day it is right now; see date_resolver.mentions_ambiguous_bare_day_of_month.
def _query_needs_relative_date_scrutiny(query: str, today) -> bool:
    return bool(
        _find_named_weekday(query)
        or _RELATIVE_DATE_QUALIFIER_PATTERN.search(query)
        or date_resolver.mentions_relative_duration_qualifier(query)
        or date_resolver.mentions_ambiguous_bare_day_of_month(query, today)
    )


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 — leave_action_node decides
    what to do with the result.

    Three distinct reasons, because they need different responses from the
    bot (see leave_action_node):
      - "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 (an
        implied year, "the day after my deadline on the 15th") 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, a
        relative-time qualifier (next/this/coming/last/weekend/quarter/...),
        a bare duration-offset phrase, or a bare ordinal day-of-month that's
        already passed this month (see
        date_resolver.mentions_ambiguous_bare_day_of_month — live bug:
        "apply leave on 15th" on 2026-08-27 silently resolved to
        2026-09-15 with the month-rollover never disclosed) that
        date_resolver's own deterministic 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 when it's still unambiguous — still
    upcoming this month ("the 5th" on Aug 1), or an explicitly-named/
    qualified month ("the 5th of November", "next month's 5th") —
    date_resolver not having a pattern for literal date parsing is by
    design (see date_resolver.py's module docstring), not a gap. It's only
    flagged (via the "ambiguous_relative_phrase" branch above) once a
    same-month reading is impossible and the choice of month becomes a
    silent, undisclosed inference."""
    from datetime import date

    if det_matched or not llm_from_date:
        return None

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

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

    # "Recognized by text, regardless of the past-date guard" — a query
    # matching one of these was already deliberately considered and either
    # resolved (in which case det_matched above would have already been
    # True and returned None) or explicitly declined ONLY because it
    # resolved to a past date (e.g. "yesterday", or "last Monday this
    # month" when that Monday has already gone by) — 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, which already has a well-tested, specific response
    # for a deliberate past request.
    # A bare "next_month" match (see _apply_deterministic_date_overrides —
    # "next month" alone never names a specific day) is deliberately
    # excluded here too: it was never actually "resolved" or "declined only
    # for being past" the way this comment describes — 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
    )
    if text_recognized:
        return None

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

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

    return None


def _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.

    Unfiltered, get_pending_leaves is capped to erp-api's most-recently-CREATED
    20 rows — completely unrelated to the leave's actual DATE, so an older
    application for today (or any date) can silently fall off that window on
    an account with enough history. Live bug repro: a same-day duplicate
    sailed straight to the confirmation card and only got caught by erp-api's
    own apply() call after the user had already said yes, because that
    existing sick-leave row wasn't among the 20 most recently created. Query
    scoped to the requested date(s) via applied_leave_date instead, so the
    20-row cap only ever has to hold matches for THIS date — the residual
    gap (an existing multi-day leave that spans the requested date without
    either of ITS OWN endpoints landing exactly on it) is erp-api's own
    filter's limitation, not fixable from here; erp-api's apply() call still
    catches that case, just after confirmation instead of before."""
    if not from_date or not to_date:
        return None
    try:
        # get_pending_leaves, not get_leave_status — the two were one name
        # until erp_client split them, and the /leave/status one shadowed the
        # /leave/pending one. Updated here too even though this whole copy is
        # dead (see the "The name points at the LIVE implementation" note
        # below leave_action_node), so reviving it cannot resurrect the bug.
        results = await asyncio.gather(
            erp_client_mod.get_pending_leaves(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
                applied_leave_date=from_date,
            ),
            erp_client_mod.get_pending_leaves(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
                applied_leave_date=to_date,
            ) if to_date != from_date else _no_op(),
        )
    except (erp_client_mod.ErpApiTimeout, erp_client_mod.ErpApiUnavailable):
        return None

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


async def _no_op():
    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.

    Live bug: this used to compare against naive, server-local
    datetime.date.today() instead of _today_in_app_timezone() — caught by
    a test failing only once real wall-clock time crossed a boundary where
    the two actually disagreed (the app's configured QUOTA_TIMEZONE ran a
    day ahead of the server's local clock), silently letting a genuinely
    past date through as "not in the past" and skipping this check
    entirely. Same anti-pattern already fixed once this session in
    ai_service._build_leave_slot_extraction_prompt — this was a second,
    independent occurrence of it."""
    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"))


# erp-api's leave_status labels (config/site-vars.php "leave_status" map).
_LEAVE_STATUS_FILTER_WORDS = ("pending", "approved", "rejected", "cancelled")


def _extract_status_filter(query: str) -> Optional[str]:
    """'I want to know only pending leave status' -> 'pending'. Deterministic
    keyword match — no LLM call needed for a single, unambiguous word."""
    text = query.lower()
    for word in _LEAVE_STATUS_FILTER_WORDS:
        if re.search(r"\b" + word + r"\b", text):
            return word
    return None


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 today; a future
    attendance/payroll date query) 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.
    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 — reusable by
    any node that has already confirmed has_date_expression is True.
    '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" — live bugs shipped in the
    apply-leave flow when relative-date math was left to LLM guessing alone
    (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 —
    the same "don't guess blind" fix applied to the mid-flow intent
    classifier (see _describe_awaited_leave_slot). 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


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


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

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


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


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):
        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 _fetch_known_leave_types(
    erp_client_mod, bearer_token: str, company_id, conversation_id: str,
) -> Optional[list[dict]]:
    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 None
    data = result["body"].get("data", {})
    leave_quota_slugs = list(data.get("leave_quota", {}).keys())
    if not leave_quota_slugs:
        return None
    names_by_slug = {
        t["slug"]: t.get("name")
        for t in data.get("leave_settings", {}).get("leave_type", [])
        if t.get("slug")
    }
    return [
        {"slug": slug, "name": names_by_slug.get(slug) or slug.replace("_", " ").title()}
        for slug in leave_quota_slugs
    ]


def _normalize_leave_type_text(text: str) -> str:
    """Lowercase and collapse separators, so "Short Leave", "short_leave",
    "SHORT-LEAVE" and "short  leave" all compare equal."""
    return re.sub(r"[\s_-]+", " ", text.strip().lower())


def _match_known_leave_type(text: Optional[str], known_leave_types: Optional[list[dict]]) -> Optional[str]:
    """Returns the company's REAL slug if `text` names one of ITS OWN
    configured leave types under any capitalization or separator style,
    else None.

    Live bug: a user replying "Short Leave" (capitalized, as the bot itself
    had just printed it) came back from extraction as leave_type=null,
    unrecognized_leave_type="short leave" — even though short_leave IS in
    that company's list — producing the self-contradicting reply 'We don't
    have a "short leave" leave type — the leave types you can apply for
    are: Casual Leave, Sick Leave, Earned Leave, or Short Leave.' Same
    posture as the date engine's tier 3: never reject on the LLM's
    classification alone when the authoritative list can settle it
    deterministically.

    Matching is exact-after-normalization against each type's own slug AND
    display name, so it can only ever return a type this company actually
    has — it never invents or approximates one. A bare root word ("short",
    "casual") is also tried as "<word> leave", since that's how the type is
    named in the list."""
    if not text or not known_leave_types:
        return None
    candidate = _normalize_leave_type_text(text)
    if not candidate:
        return None
    variants = {candidate}
    if not candidate.endswith("leave"):
        variants.add(f"{candidate} leave")
    for t in known_leave_types:
        known = {
            _normalize_leave_type_text(t["slug"]),
            _normalize_leave_type_text(t.get("name") or ""),
        }
        known.discard("")
        if variants & known:
            return t["slug"]
    return None


# NOTE: a stale local copy of _CANCEL_REQUEST_PATTERNS / _is_declining_or_
# cancelling used to sit here. Defined AFTER the import at the top of this
# file, it silently shadowed the canonical version in leave_action_service for
# every caller in this module — including classify_node, which resolves the
# global at call time. It had drifted: it was missing the "keep it/this/the
# request" decline pattern, so the cancel card's own "Keep Request" button
# read as NOT a decline here while reading as one in leave_action_service.
# Deleted rather than re-synced; the import at the top is now authoritative,
# which is the whole point of having one predicate (see
# leave_action_service.cancel_phrase_targets_submitted_request).


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

    # ── Access pre-check — fetched lazily, only for actual leave interactions,
    # so erp-api's availability never affects ordinary (non-leave) HR chat.
    # Role does NOT gate this feature: managers and employees follow exactly
    # the same path from here on. erp-api's balance/apply/status routes are
    # self-scoped for every caller, so whoever is asking gets their own leave
    # data. This call stays only as a cheap token/reachability check, so an
    # expired token or a down erp-api produces one clean message up front
    # instead of failing deeper into the flow.
    try:
        context_result = await erp_client.get_leave_context(bearer_token, company_id=company_id, conversation_id=conversation_id)
    except erp_client.ErpApiTimeout:
        return _finish("I couldn't verify your access in time — please try again in a moment.")
    except erp_client.ErpApiUnavailable:
        return _finish("I'm unable to reach the HR system right now — please try again shortly.")

    # Logged for observability only — nothing branches on it.
    logger.info("[Graph] Leave context fetched | is_manager=%s",
                context_result["body"].get("data", {}).get("is_manager", False))

    existing_slots = leave_slot_service.get_slots(company_id, conversation_id)

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

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

        body = result["body"].get("data", {})
        leave_quota = body.get("leave_quota", {})
        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 {info.get('remaining')} {label} day(s) 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}
            writer({"type": "leave_balance", "data": filtered_body})
            return _finish(f"{msg}{resume_reminder}", intent="leave_balance", extra_data=filtered_body)

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

    # ── Status branch — check existing leave application(s) ──────────────────
    if state["intent"] == "leave_status":
        writer({"type": "fetching_status", "message": "Checking your leave requests..."})
        try:
            result = await erp_client.get_pending_leaves(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_status")
        except erp_client.ErpApiUnavailable:
            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", [])
        status_filter = _extract_status_filter(query)
        # Live bug: "show my leave details for 21th august" returned every
        # leave on record — this branch only ever filtered by status word,
        # never by date. Gated behind has_date_expression (computed once in
        # classify_node) so the common no-date query never pays for the
        # extra deterministic/LLM resolution work.
        date_filter = (
            await _resolve_date_range(
                query, _today_in_app_timezone(),
                purpose_hint="the employee's own leave request history",
            )
            if state.get("has_date_expression") else None
        )

        leaves = all_leaves
        if status_filter:
            leaves = [lv for lv in leaves if lv.get("status_name") == status_filter]
        if date_filter:
            d_from, d_to = date_filter
            leaves = [lv for lv in leaves if _dates_overlap(lv.get("from_date"), lv.get("to_date"), d_from, d_to)]

        status_label = f"{status_filter} " if status_filter else ""
        date_label = ""
        if date_filter:
            d_from, d_to = date_filter
            date_label = f" on {d_from}" if d_from == d_to else f" from {d_from} to {d_to}"

        writer({"type": "leave_status", "data": {
            "leaves": leaves, "filter": status_filter,
            "date_filter": {"from_date": date_filter[0], "to_date": date_filter[1]} if date_filter else None,
        }})
        if not leaves:
            msg = f"You don't have any {status_label}leave requests{date_label} on record."
        elif len(leaves) == 1:
            lv = leaves[0]
            msg = (f"Your {lv['leave_type']} request ({lv['from_date']} to {lv['to_date']}) "
                   f"is {lv['status_name']}.")
        else:
            summary = "; ".join(
                f"{lv['leave_type']} ({lv['from_date']} to {lv['to_date']}): {lv['status_name']}"
                for lv in leaves[:5]
            )
            msg = f"Your {status_label}leave requests{date_label} — {summary}."
        return _finish(f"{msg}{resume_reminder}", intent="leave_status", extra_data={"leaves": leaves})

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

    # This company's real configured leave types — only needed while
    # leave_type isn't yet fixed on this draft; once set, later turns
    # (session, reason, confirmation) don't need the full list again, so
    # skipping the fetch then avoids an unnecessary erp-api round trip.
    known_leave_types = None
    if not slots.get("leave_type"):
        known_leave_types = await _fetch_known_leave_types(
            erp_client, bearer_token, company_id, conversation_id,
        )

    # One extraction call serves both purposes: fills slots on a collecting
    # turn, and carries is_affirmative on a confirmation turn.
    today = _today_in_app_timezone()
    extracted: dict = {}
    try:
        prompt = _build_leave_slot_extraction_prompt(
            query, slots,
            known_leave_type_slugs=[t["slug"] for t in known_leave_types] if known_leave_types else None,
            today=today,
        )
        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}")

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

            body = result["body"]
            if not body.get("success", False):
                error_msg = body.get("message") or "Something went wrong submitting your request."
                # Resubmitting the exact same slots would just fail identically
                # again (duplicate application, locked attendance date, etc.) —
                # a bare "yes"/"try again" reply re-enters this same branch and
                # loops forever hitting the same erp-api rejection, since step
                # was never reset. Drop back to collecting so the next reply
                # is treated as new input, not another confirmation attempt.
                slots["step"] = "collecting"
                if "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
                    leave_slot_service.set_slots(company_id, conversation_id, slots)
                    return _finish(f"{error_msg} Could you share a brief reason for this leave?")
                if "session type" in error_msg.lower() or "session_type" in error_msg.lower():
                    # erp-api rejected specifically over the session type
                    # field (e.g. "The session type slug field is required
                    # when leave type slug is sick_leave" — some leave types
                    # require an explicit full/half day even on a single-day
                    # request). Clearing dates here would misdirect the user
                    # into re-picking dates that were never the problem —
                    # re-collect the session type instead.
                    slots["session_type_slug"] = None
                    leave_slot_service.set_slots(company_id, conversation_id, slots)
                    return _finish(f"{error_msg} Would that be a full day or half day?")
                # 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
                leave_slot_service.set_slots(company_id, conversation_id, slots)
                return _finish(
                    f"{error_msg} What dates would you like to try instead?",
                    extra_data={"requires_date_input": True},
                )

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

            writer({"type": "leave_success", "data": {"application_id": app_id}})
            confirm_msg = (f"Your leave request has been submitted — Request #{app_id}."
                           if app_id else "Your leave request has been submitted.")
            return _finish(confirm_msg, intent="leave_success", extra_data={"application_id": app_id})

        if _is_declining_or_cancelling(query):
            leave_slot_service.clear_slots(company_id, conversation_id)
            return _finish(
                "No problem — I've cancelled that leave request. "
                "Let me know if you'd like to start a new one."
            )

        # Not a clear "yes"/"cancel" — treat as a revision, fall through and re-collect.
        slots["step"] = "collecting"

    # Merge this turn's extracted fields into the slots.
    for field in ("leave_type", "from_date", "to_date", "session_type_slug", "reason"):
        if extracted.get(field):
            slots[field] = extracted[field]

    # Canonicalize a leave_type the model returned as a DISPLAY NAME rather
    # than a slug ("Short Leave" instead of "short_leave"). Stored verbatim
    # it would sail through every check here and only fail at erp-api's own
    # apply() call, after the user had already confirmed. Only ever rewrites
    # to a slug this company actually has; anything unmatched is left
    # exactly as-is for the existing checks to handle.
    if slots.get("leave_type") and known_leave_types:
        canonical = _match_known_leave_type(slots["leave_type"], known_leave_types)
        if canonical and canonical != slots["leave_type"]:
            logger.info(
                "[Graph] Canonicalized leave type: %r -> %s", slots["leave_type"], canonical,
            )
            slots["leave_type"] = canonical

    # Deterministic date/duration override — must run AFTER the LLM merge
    # (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 (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.
    det_matched = _apply_deterministic_date_overrides(query, slots, extracted, today)

    # ── Tier 2: structured tool-calling extraction ──────────────────────────
    # Only spent when tier 1 (regex, above) found nothing AND the query
    # plausibly names a date at all — most turns never reach this, so the
    # extra LLM call only fires on the phrasings tier 1's regexes can't
    # anticipate. This is the systemic fix for the recurring live-bug shape
    # this session kept hitting (a new English phrasing of an
    # already-computable date concept, each needing its own hand-written
    # regex): the LLM extracts structured fields ONLY — never a final date
    # — and date_resolver.resolve_structured_date (pure, reuses the exact
    # same tested primitives as every regex-matched path) does 100% of the
    # actual arithmetic. See services.ai_service.extract_structured_date_
    # fields for the field schema and prompt.
    #
    # Gate: deliberately does NOT use date_resolver.mentions_date_expression
    # here — that pattern was built for a different purpose (leave-status
    # date filtering) and matches month names / today-tomorrow-yesterday /
    # digit dates (including full ISO dates like "2026-11-18"). Tier 2's
    # structured schema (day_offset/target_weekday/weekday_relation/ordinal/
    # month_offset) is 100% relative — it has no field that can represent an
    # absolute calendar date at all, so firing it for a query that's already
    # a fully-specified absolute date can only waste a call or, worse,
    # return a nonsensical guess that risks overwriting an already-correct
    # date (live bug: "From 2026-11-18 to 2026-11-19" made the ISO-date
    # branch of mentions_date_expression fire tier 2, which guessed
    # day_offset=-6 — a value with nothing to do with the query — and was
    # only saved from corrupting the result by the past-date guard rejecting
    # it as a coincidence, not by design). Absolute dates are literal
    # parsing, already handled reliably by the plain extraction call itself;
    # today/tomorrow/yesterday/day-after-tomorrow are already handled by
    # tier 1 (date_resolver._match_relative_phrase). Use the same
    # weekday/relative-qualifier signal _llm_date_needs_confirmation already
    # uses below (see its own text_recognized check) — tier 2 exists only
    # for relative phrasing tier 1's regexes don't cover.
    _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
        structured_fields, structured_usage = await 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"],
            )

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

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

    # If the user named a leave type this company doesn't offer (e.g.
    # "maternity", "PL", "bereavement"), say so explicitly instead of
    # silently re-asking "what type of leave?" as if nothing was said —
    # that generic re-ask reads as the bot ignoring the request rather than
    # clearly telling the user that option isn't available here.
    #
    # Only honored while leave_type is STILL being collected (not already
    # known from an earlier turn). Live bug: once leave_type was already
    # confirmed as "sick_leave", a later turn answering a DIFFERENT
    # question (the reason prompt, replied to with "fever009" — a garbled
    # test value) still got flagged as unrecognized_leave_type and
    # rejected with 'We don't have a "fever009" leave type here.' The
    # extraction prompt has no signal for which specific field this turn
    # is actually answering, so it fell back to its own general
    # "unfamiliar short word → maybe an attempted type name" heuristic —
    # correct when leave_type genuinely hasn't been named yet, wrong once
    # it's already locked in. A user wanting to CHANGE an already-confirmed
    # type would need to say so explicitly ("actually I meant casual
    # leave") — plain leave_type extraction already handles that turn by
    # turn; this check is specifically about a FIRST, unprompted mention.
    if not slots.get("leave_type") and extracted.get("unrecognized_leave_type"):
        unrecognized = extracted["unrecognized_leave_type"]
        # Cross-check against this company's REAL list before rejecting —
        # extraction flagging something as unrecognized is not authoritative
        # (live bug: "Short Leave" got flagged even though short_leave was
        # right there in the list, so the bot denied having a type it then
        # listed as available in the very same sentence). See
        # _match_known_leave_type; it can only ever return a type this
        # company genuinely has, so recovering here never invents one.
        recovered = _match_known_leave_type(unrecognized, known_leave_types)
        if recovered:
            slots["leave_type"] = recovered
            leave_slot_service.set_slots(company_id, conversation_id, slots)
            logger.info(
                "[Graph] Recovered leave type flagged as unrecognized: %r -> %s",
                unrecognized, recovered,
            )
        elif known_leave_types:
            names = [t["name"] for t in known_leave_types]
            options = names[0] if len(names) == 1 else f"{', '.join(names[:-1])}, or {names[-1]}"
            return _finish(
                f'We don\'t have a "{unrecognized}" leave type — '
                f"the leave types you can apply for are: {options}."
            )
        else:
            return _finish(f'We don\'t have a "{unrecognized}" leave type here.')

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

    # Check for a date conflict the moment dates are known — before asking
    # about leave type, session, or reason, not after. The conflict check
    # only needs from_date/to_date (erp-api's own apply() call rejects an
    # overlapping date regardless of leave TYPE), so there's no reason to
    # make the user answer three more questions before finding out the date
    # itself is a dead end. Live UX complaints, fixed in sequence: first the
    # check ran only after every other slot was collected; moving it here
    # instead of merely earlier-but-still-after-leave-type closes the
    # remaining gap — "apply leave for today" (date given, type not yet)
    # still asked "what type of leave?" first even though the date alone was
    # already enough to know the request was going nowhere.
    if slots.get("from_date") and slots.get("to_date"):
        conflict = await _find_conflicting_leave(
            erp_client, bearer_token, company_id, conversation_id,
            slots.get("from_date"), slots.get("to_date"),
        )
        if conflict:
            leave_slot_service.set_slots(
                company_id, conversation_id,
                {**slots, "step": "collecting", "from_date": None, "to_date": None},
            )
            return _finish(
                f"You've already applied for {conflict.get('leave_type', 'leave')} on "
                f"{conflict.get('from_date')} to {conflict.get('to_date')} "
                f"({conflict.get('status_name')}). What dates would you like to try instead?",
                extra_data={"requires_date_input": True},
            )

    # Ask for the next missing required slot, in order.
    if not slots.get("leave_type"):
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        # Live bug: this used to always say "casual, sick, earned, or
        # something else?" even for a company that also has short_leave /
        # comp_off / other configured types — a user had no way to know
        # those were valid answers. known_leave_types (fetched above, right
        # before extraction) is this company's REAL configured list; list it
        # verbatim instead of a generic guess, falling back to the old
        # generic wording only if erp-api couldn't be reached.
        if known_leave_types:
            names = [t["name"] for t in known_leave_types]
            options = names[0] if len(names) == 1 else f"{', '.join(names[:-1])}, or {names[-1]}"
            return _finish(f"What type of leave would you like to apply for — {options}?")
        return _finish("What type of leave would you like to apply for — casual, sick, earned, or something else?")

    if not slots.get("from_date") or not slots.get("to_date"):
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        if _is_asking_for_date_suggestions(query):
            return _finish(
                "There's no fixed list of available dates — you can request almost "
                "any date; it just needs your manager's approval and can't fall on "
                "a locked or blackout date. What date or date range would you like?",
                extra_data={"requires_date_input": True},
            )
        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?",
                extra_data={"requires_date_input": True},
            )
        return _finish("What dates would you like to take off?", extra_data={"requires_date_input": True})

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

    # Live bug: erp-api requires session_type_slug on EVERY application for
    # these leave types, not just single-day ones — a multi-day sick_leave
    # request never hit the ask above (half/full day only makes sense for a
    # single day), left session_type_slug at None all the way to apply_leave,
    # and erp-api rejected it post-confirmation ("The session type slug
    # field is required when leave type slug is sick_leave"). A multi-day
    # range is always full days throughout (see the comment above), so
    # default it here instead of asking a question that wouldn't make sense
    # to the user.
    if (slots["leave_type"] in _SESSION_TYPE_REQUIRED_LEAVE_TYPES
            and not _is_single_day(slots) and not slots.get("session_type_slug")):
        slots["session_type_slug"] = "full_day"

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

    # Live bug: erp-api treats short_leave as an inherently single-unit
    # type (its apply()/update() logic force-sets leave_count="1"
    # regardless of the date range given, the same way half_day forces
    # 0.5) and rejects a multi-day short_leave range outright ("The from
    # date and to date must be the same for this leave request") — but
    # only at actual submission time, AFTER the user has already confirmed
    # (a real live repro: a 15-day short_leave range sailed through
    # confirmation and only failed on "Yes, please submit it."). Catch it
    # here instead, same "don't let the user discover this after
    # confirming" principle as the session-type-required fix above.
    if slots["leave_type"] == "short_leave" and not _is_single_day(slots):
        slots["from_date"] = None
        slots["to_date"] = None
        leave_slot_service.set_slots(company_id, conversation_id, slots)
        return _finish(
            "Short leave can only be applied for a single day. What date would you like?",
            extra_data={"requires_date_input": True},
        )

    # Validate against balance (AC#3). 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:
        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):
                current_type_label = slots["leave_type"].replace("_", " ").title()
                # A type with ZERO balance (e.g. this account's
                # leave_without_pay, total=0) can never be fixed by picking
                # different dates — the type itself is the problem. Say so
                # plainly instead of the misleading "what dates would you
                # like to try instead?", and point at other types that
                # actually have balance right now (from this SAME
                # already-fetched leave_quota/leave_settings — no extra
                # erp-api call needed).
                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")
                }
                alternatives = [
                    names_by_slug.get(slug) or slug.replace("_", " ").title()
                    for slug, info in leave_quota.items()
                    if slug != slots["leave_type"] and float(info.get("remaining") or 0) > 0
                ]
                alt_text = (
                    f" You could try {alternatives[0]}" if len(alternatives) == 1
                    else f" You could try {', '.join(alternatives[:-1])} or {alternatives[-1]}" if alternatives
                    else ""
                )
                if alt_text:
                    alt_text += " instead, if that fits your situation."

                if float(remaining) <= 0:
                    # Live bug: from_date/to_date were left untouched here, so
                    # a reply that wasn't actually a new date ("personal
                    # reasons", "fever") left the exact same insufficient
                    # combination in slots — the next turn silently re-ran
                    # this same check and repeated the identical rejection
                    # forever. Clear leave_type too here (not just dates) —
                    # a zero-balance type will reject ANY date, so there's
                    # nothing useful left to "collect" until the user picks
                    # a different type.
                    leave_slot_service.set_slots(
                        company_id, conversation_id,
                        {**slots, "step": "collecting", "leave_type": None,
                         "from_date": None, "to_date": None, "session_type_slug": None},
                    )
                    return _finish(
                        f"You have no {current_type_label} balance remaining — this request can't go "
                        f"through on any date.{alt_text}"
                    )

                # Positive but insufficient balance — a shorter date range
                # genuinely could fix this, so clearing dates (not type) and
                # asking for new ones is still the right move; the
                # alternative-type suggestion is offered alongside it.
                leave_slot_service.set_slots(
                    company_id, conversation_id,
                    {**slots, "step": "collecting", "from_date": None, "to_date": None},
                )
                return _finish(
                    f"You only have {remaining} day(s) of {current_type_label} "
                    f"remaining, but this request needs {requested_days}.{alt_text} "
                    f"What dates would you like to try instead?",
                    extra_data={"requires_date_input": True},
                )
        except (TypeError, ValueError):
            pass  # non-numeric remaining — let erp-api's own apply() gate it

    # Reason is asked LAST, AFTER the balance check above (QA report,
    # 2026-09-09): reason has no bearing on how many days are being
    # requested, so asking for it first made an employee whose request was
    # already doomed ("1 Sept to 15 Sept" of Earned Leave with 3 days left)
    # answer "what's the reason?" before being told the balance was short —
    # a wasted turn on input that could not change the outcome. Same
    # "validate as soon as the slots it needs are filled" principle as the
    # short-leave and session-type checks above.
    # 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 below, 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: the extraction prompt has no signal that THIS turn
        # is specifically answering "what's the reason" — a terse reply that
        # just restates the leave type ("sick leave") correctly gets
        # rejected by extraction's own rule (a leave-type mention must not
        # leak into reason), but from the user's side that just looks like
        # the bot ignoring every answer and repeating the same question
        # forever ("sick leave" / "I want to apply for sick leave" / "apply
        # for sick leave", same prompt three times running, no way out).
        # Once we've already asked once and extraction still came back
        # empty, accept this turn's raw text verbatim instead of asking a
        # third time — an imperfect reason beats a conversation stuck in a
        # loop the user can't escape.
        reason_attempts = slots.get("reason_attempts", 0)
        if reason_attempts >= 1 and query.strip():
            slots["reason"] = query.strip()[:200]
            slots.pop("reason_attempts", None)
        else:
            slots["reason_attempts"] = reason_attempts + 1
            leave_slot_service.set_slots(company_id, conversation_id, slots)
            return _finish('What\'s the reason for this leave request? (e.g. "fever", "family emergency")')
    else:
        slots.pop("reason_attempts", None)

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


# ── The name points at the LIVE implementation, not the copy above ───────────
# `leave_action_node = leave_action_node_impl` is already set near the
# imports, but the duplicate definition ABOVE this line is later in the
# module and so won overwrite it. The graph itself was never affected -
# add_node() is passed leave_action_node_impl directly - so the copy above is
# dead code, and has been since that wiring landed (e279d58, 2026-09-03).
#
# It was not harmless, though: anything reaching for `hr_graph.
# leave_action_node` got the dead copy. That is what ~240 tests in
# test_leave_action.py were exercising, which is why they asserted against
# behaviour no request has gone through in months.
#
# Re-pointing the name here is the whole fix. Deleting the ~735 dead lines
# above is the follow-up, kept separate so this change stays reviewable.
#
# Now a thin wrapper rather than a bare alias - see its docstring - and the
# graph registers it too, so the name and the graph agree.
async def leave_action_node(state: HRState, writer: StreamWriter) -> dict:
    """leave_action_node_impl, plus the balance card explained in the language
    the user asked for. Live: "leave balance in hindi" got the English card and
    nothing else - the card is fixed, and only "explain ... in hindi" asked
    AFTER a card reached the advisor. Now the card is shown as always, and the
    advisor's explanation of it, in that language, is the answer text."""
    language = requested_reply_language(state.get("query") or "")
    if state.get("intent") != "leave_balance" or not language:
        return await leave_action_node_impl(state, writer)

    card_done = []

    def _hold_done(event):
        (card_done.append if event.get("type") == "done" else writer)(event)

    result = await leave_action_node_impl(state, _hold_done)
    card = (card_done[-1].get("data") or {}) if card_done else {}
    if not card.get("leave_quota"):
        for event in card_done:  # an error or "no balance" - as it was
            writer(event)
        return result

    def _drop_done(event):
        if event.get("type") != "done":
            writer(event)

    context = list(state.get("context") or []) + [
        {"role": "user", "content": state.get("query") or ""},
        {"role": "assistant", "content": history_text(card)},
    ]
    out = await hr_response_node(
        {**state, "intent": "follow_up", "context": context,
         "query": f"Explain this leave balance in {language.title()}."},
        _drop_done)
    answer = (out or {}).get("response_text") or ""
    if not answer:
        for event in card_done:
            writer(event)
        return result
    usage = (out or {}).get("usage_events") or result.get("usage_events") or []
    writer({**card_done[-1], "data": {**card, "answer": answer}, "message": answer,
            "usage_events": usage})
    return {**result, "response_text": answer, "usage_events": usage}


# ── Node 5: Team pending leave requests (FR-07.1, Sprint 4) ──────────────────
# A MANAGER asking to see their team's PENDING leave requests. Deliberately a
# separate node, not a branch inside leave_action_node: that function's role
# gate BLOCKS every manager from the three individual-scoped leave intents;
# this one does the opposite (blocks non-managers), and mixing the two
# polarities into one function would risk regressing the already-tested
# manager block there. Stateless — unlike apply_leave, there is no
# multi-turn slot-filling here, so leave_slot_service is never touched.
# erp-api's GET /api/v1/ai/leave/pending/teams returns the full pending
# list unpaginated (confirmed live — no offset/limit/has_more on the wire),
# so ordering (leave start date ascending) and the top-3-by-default
# limiting happen here, not in erp_client.

async def team_leave_query_node(state: HRState, writer: StreamWriter) -> dict:
    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", []))

    # Local, not shared with leave_action_node's own _finish — that closure
    # captures leave_action_node's own writer/usage_events locals, and this
    # file already prefers a small duplicated closure over threading those
    # through an untouched, heavily-tested function (see
    # _resolve_deterministic_date_range for the same trade-off elsewhere).
    def _finish(message: str, intent: str = "HRMS_TEAM_LEAVE_QUERY", extra_data: Optional[dict] = None) -> dict:
        data = {"answer": message}
        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 — INVERTED polarity from leave_action_node's: this
    # capability is manager-ONLY, so a non-manager is who gets blocked here.
    #
    # Normally already decided by hr_graph.manager_gate_node, which runs ahead
    # of intent classification and leaves a tri-state on the state: True
    # (manager, resolved from the JWT role claim or erp-api), False (erp-api
    # said no), None (couldn't be determined — shouldn't happen once the gate
    # has run, but this node stays callable on its own too). Re-querying
    # erp-api here unconditionally threw that resolution away and asked
    # again — for a caller whose manager-ness came from the JWT role claim
    # (e.g. an "hr" role) rather than erp-api's own is_manager flag, the two
    # calls can disagree, and the fresh one silently overrode the one the
    # rest of the graph already trusted.
    is_manager = state.get("is_manager")
    _context_data = None
    if is_manager is None and not state.get("is_manager_jwt"):
        try:
            context_result = await erp_client.get_leave_context(bearer_token, company_id=company_id, conversation_id=conversation_id)
        except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable):
        # A failed ROLE LOOKUP is not this feature being unavailable, and
        # must not be reported as one. The old copy here ("I'm unable to
        # reach the HR system right now") described an outage of the team
        # capability, when what actually failed was the question "who is
        # asking?" — reported live for "show my team attendacne", where the
        # employee expected the "Not available" card and got an invitation
        # to retry something that would never succeed.
        #
        # The JWT can often answer that question with no network at all, so
        # it is asked first: a token naming a manager/HR/admin role proceeds
        # exactly as it would have. Only when nothing can decide does the
        # turn end, and then with the wording that says what really happened
        # — the same one the MANAGER_UNKNOWN branch below already uses.
            if permission_service.may_view_team(state) is True:
                logger.info("[Graph] Team leave: role lookup failed, allowed on the JWT role claim")
                is_manager = True
            else:
                return _finish("I couldn't verify your access in time — please try again in a moment.")
        else:
            _context_data = context_result["body"].get("data", {})
            is_manager = _context_data.get("is_manager", False)
    elif is_manager is None:
        is_manager = True
    logger.info(f"[Graph] Team leave query | is_manager={is_manager}")

    # A manager is not the only caller who may see a team member's record —
    # an HR user and an admin may too, and the rule for all three lives in
    # services/permission_service. Applied as a WIDENING on top of whatever
    # the is_manager resolution above produced: it can only turn a refusal
    # into an allow, never the reverse, so the manager path is untouched.
    if is_manager is not True:
        _access = permission_service.may_view_team(state, context_data=_context_data)
        if _access is True:
            is_manager = True
            logger.info("[Graph] Team leave query allowed as an HR/admin caller")
        elif _access == permission_service.ACCESS_UNKNOWN:
            is_manager = individual_report.MANAGER_UNKNOWN

    if is_manager == individual_report.MANAGER_UNKNOWN:
        return _finish("I couldn't verify your access in time — please try again in a moment.")

    # Which STATUS the manager asked for — pending (the default and FR-07.1's
    # original scope), approved, cancelled, or all. Resolved from the wording
    # before the role gate's copy is built so a refusal names the same thing
    # the question did. See services/team_leave_filter.py.
    leave_status = team_leave_filter.resolve_team_leave_status(state.get("query", ""))

    _restricted_msg = team_leave_filter.restricted_message(leave_status)

    def _refuse() -> dict:
        """HA-193 — a refusal renders as the Figma's amber "Not available"
        card, so it goes out as a structured notice as well as prose.

        The payload is written twice on purpose: the `access_notice` event is
        what the card subscribes to live, but only what lands in `done`'s
        `data` is persisted by main._persist_and_build_done, so that copy is
        what a non-streaming client and a replayed conversation see.
        """
        notice = team_leave_filter.restricted_notice(leave_status)
        writer({"type": "access_notice", "data": notice})
        return _finish(_restricted_msg, intent=access_notice.RESTRICTED_INTENT,
                       extra_data={"access_notice": notice})

    if not is_manager:
        return _refuse()

    writer({"type": "fetching_team_leaves",
            "message": team_leave_filter.fetching_message(leave_status)})
    try:
        result = await erp_client.get_team_leaves(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
            leave_status=leave_status,
        )
    except erp_client.ErpApiTimeout:
        return _finish("I couldn't reach the HR system in time — please try again in a moment.")
    except erp_client.ErpApiUnavailable as e:
        # Read what erp-api actually answered: a permission refusal (401/403,
        # or a body whose wording says so) is erp-api ANSWERING the access
        # question, so it lands on the same "Not available" card a locally-
        # refused caller gets rather than on the infrastructure sentence,
        # which blames the system for a rule and invites a doomed retry.
        # See permission_service.erp_refused_for_permission.
        if permission_service.erp_refused_for_permission(e):
            logger.info("[Graph] Team leave: erp-api refused on permission (status=%s) "
                        "- showing the access card, not an outage message",
                        getattr(e, "status_code", None))
            return _refuse()
        return _finish(erp_client.unavailable_message(e))

    # A role change between the get_leave_context check above and this call
    # (or any other disagreement with erp-api's own authoritative gate, which
    # is what actually enforces AC5) must not crash the turn — fall back to
    # the same friendly refusal rather than surfacing a raw error.
    if result.get("http_status") == 403:
        return _refuse()

    body = result["body"].get("data", {})
    leaves = body.get("leaves", [])

    if not leaves:
        # AC#6 — exact required copy, verbatim, no team_pending_leave event.
        # empty_state_message returns that same string for the pending filter.
        return _finish(team_leave_filter.empty_state_message(leave_status))

    # erp-api returns every matching leave unpaginated — sort by leave start
    # date ascending and cap at 3 here (AC#2), rather than trusting wire order.
    sorted_leaves = sorted(leaves, key=lambda lv: lv.get("from_date") or "")
    top_leaves = sorted_leaves[:3]
    has_more = len(sorted_leaves) > 3
    # leave_status_filter is this layer's OWN record of what was asked for.
    # erp-api echoes the filter back as data.type, but only that field is
    # guaranteed to exist on every shape, and a card that mislabels approved
    # rows as pending is the exact bug this feature exists to stop — so the
    # resolved value is stated here rather than inferred downstream.
    event_data = {**body, "leaves": sorted_leaves, "has_more": has_more,
                  "leave_status_filter": leave_status}

    writer({"type": "team_pending_leave", "data": event_data})

    # FR-07.4 - remember the rows this card just showed, so an instruction
    # that follows it has something real to resolve against.
    #
    # Live bug: a team with ONE pending request, manager types "approve
    # casual leave", and leave_approval._resolve_target finds no remembered
    # requests, no remembered employee, and asks "Which request would you
    # like me to approve?" - naming nothing, one turn after putting the only
    # candidate on the screen. individual_report already remembers its rows
    # (including on its own team-wide path); team_leave_query_node was the
    # one list that showed requests and forgot them.
    #
    # PENDING only, and that guard is the point rather than an optimisation:
    # the approved/cancelled/all filters return rows that are already
    # decided, and remembering those would let "approve it" resolve onto a
    # request there is nothing left to approve.
    #
    # Written in the same shape as individual_report's team-wide branch - the
    # rows, and deliberately no `last_employee`, because a team list has no
    # single subject for a later pronoun to mean.
    if leave_status == team_leave_filter.PENDING:
        leave_slot_service.set_report_state(company_id, conversation_id, {
            "step": "resolved",
            "last_leave_requests": [
                individual_report._remembered_leave(lv) for lv in sorted_leaves[:10]
            ],
        })

    lines = [
        f"{lv.get('employee_name')}: {lv.get('leave_type')} "
        f"({lv.get('from_date')} to {lv.get('to_date')}), {lv.get('leave_count')} day(s)"
        for lv in top_leaves
    ]
    summary = team_leave_filter.summary_header(leave_status) + "\n" + "\n".join(lines)
    if has_more:
        summary += "\n" + team_leave_filter.more_available_note(leave_status)

    return _finish(summary, extra_data=event_data)


EMPLOYEE_FILTER_UNSUPPORTED_MESSAGE = (
    "Currently I can't filter employees by company, role or team - I can only show you "
    "your own team's details. Would you like to see your team?")

_EMPLOYEE_WORDS_RE = re.compile(
    r"\b(?:employees?|members?|staff|people|colleagues?|users?|workers?|team\s*mates?)\b", re.IGNORECASE)
_EMPLOYEE_FILTER_RE = re.compile(
    r"\bother\s+than\b"
    r"|\b(?:another|other|different|a\s+different|some\s+other)\s+(?:company|companies|organi[sz]ations?|"
    r"firms?|teams?|departments?|depts?|branch(?:es)?|offices?)\b"
    r"|\b(?:of|in|from|at)\s+(?:a|an)\s+(?:company|organi[sz]ation|firm|team|department)\b"
    r"|\bby\s+(?:role|designation|team|department|dept|company|location|branch)\b"
    r"|\b(?:with|having|whose)\s+(?:the\s+)?(?:role|designation|title)\b"
    r"|\b(?:role|designation)\s+(?:is|=|of|as)\b"
    r"|\b(?:all|every)\s+(?:the\s+)?(?:developers|engineers|designers|testers|managers|interns)\b"
    r"|\b(?:in|from|of)\s+(?!my\b|our\b)(?:the\s+)?[a-z&]+(?:\s+[a-z&]+)?\s+(?:team|department|dept)\b",
    re.IGNORECASE)


def asks_to_filter_employees(query: str) -> bool:
    """A list of employees narrowed by company, team, department or role -
    "employees of a company other than QA Team", "members of the sales
    team", "employees with role developer". Not the caller's own team."""
    q = query or ""
    return bool(_EMPLOYEE_WORDS_RE.search(q) and _EMPLOYEE_FILTER_RE.search(q))


async def team_members_node(state: HRState, writer: StreamWriter) -> dict:
    """"Show my team members" - the caller's own roster.

    Manager-ONLY, same inverted gate polarity as team_leave_query_node and
    team_attendance_summary_node. Added because the query had no node at all:
    it reached the LLM with no roster label to choose, was classified as an
    attendance explanation, and rendered an empty attendance card.

    Scope is erp-api's to decide and is passed through untouched, so this and
    the pending-leave view can never disagree about who is on a team.
    """
    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 = "HRMS_TEAM_MEMBERS_QUERY",
                extra_data: Optional[dict] = None) -> dict:
        data = {"answer": message}
        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}

    # Same two-sentence shape as the team-leave and team-attendance refusals
    # (services/access_notice.py) so all three render identically in the
    # Figma's "Not available" card and state one consistent access rule.
    _restricted_msg = access_notice.message(
        "Team details", "check your own leave and attendance details")

    # "Is Rohan Mehta currently an employee here?" names ONE person. An
    # employee is told plainly that other employees' details are not shared -
    # decided here, before any erp-api call, so nothing about the named person
    # is even looked up. A manager/HR/admin gets the name checked against
    # their own team. ACCESS_UNKNOWN (role not resolved) falls through to
    # erp-api, whose 403 still decides.
    lookup_target = extract_employee_lookup_target(state.get("query", ""))
    _other_employee_msg = ("Sorry, I can't share information about other employees. "
                           "For someone else's details, please check with HR or your manager.")

    def _refuse() -> dict:
        # The access_notice EVENT is what the amber "Not available" card is
        # drawn from live. QA: the named-person refusal sent only the text, so
        # it rendered as a plain bubble - and as the card only after switching
        # chats, when the UI rebuilt it from the saved intent.
        if lookup_target:
            return _finish(_other_employee_msg, intent=access_notice.RESTRICTED_INTENT,
                           extra_data=access_notice.refuse(writer, "employee_details",
                                                           _other_employee_msg, other_employee=True))
        notice = access_notice.build("team_members", _restricted_msg)
        writer({"type": "access_notice", "data": notice})
        return _finish(_restricted_msg, intent=access_notice.RESTRICTED_INTENT,
                       extra_data={"access_notice": notice})

    if lookup_target and permission_service.may_view_team(state) is False:
        return _refuse()

    if lookup_target:
        return await _answer_team_member_lookup(
            lookup_target, bearer_token, company_id, conversation_id, writer, _finish, _refuse)

    # UAT UV-20 (27 Oct): "Show me employees of a company other than QA Team"
    # showed the caller's own team, as if that was what was asked. Only the
    # caller's own roster exists here - say so instead.
    if asks_to_filter_employees(state.get("query", "")):
        if permission_service.may_view_team(state) is False:
            return _refuse()
        return _finish(EMPLOYEE_FILTER_UNSUPPORTED_MESSAGE)

    writer({"type": "fetching_team_members", "message": "Looking up your team..."})
    try:
        result = await erp_client.get_team_members(
            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.")
    except erp_client.ErpApiUnavailable as e:
        # Read what erp-api actually answered: a permission refusal (401/403,
        # or a body whose wording says so) is erp-api ANSWERING the access
        # question, so it lands on the same "Not available" card a locally-
        # refused caller gets rather than on the infrastructure sentence,
        # which blames the system for a rule and invites a doomed retry.
        # See permission_service.erp_refused_for_permission.
        if permission_service.erp_refused_for_permission(e):
            logger.info("[Graph] Team members: erp-api refused on permission (status=%s) "
                        "- showing the access card, not an outage message",
                        getattr(e, "status_code", None))
            return _refuse()
        if getattr(e, "status_code", None) != 404:
            return _finish(erp_client.unavailable_message(e))
        # /leave/team/members answers 404 on the deployed erp-api (the route
        # is not there), so "show my team" read "I'm unable to reach the HR
        # system". Fall back to the roster the pending-teams search returns
        # for a term that matches nobody - its documented, live-verified
        # "pick from your team" answer, scoped by erp-api to the caller.
        logger.info("[Graph] Team members: roster route 404 - using the pending-teams roster")
        result = await _roster_via_pending_search(bearer_token, company_id, conversation_id)
        if result is None:
            return _finish(erp_client.unavailable_message(e))

    # erp-api refuses a caller with no reports. Its 403 is the authoritative
    # gate; this node does not second-guess it with a role check of its own.
    if result.get("http_status") == 403:
        return _refuse()

    body = result.get("body", {}).get("data", {}) or {}
    members = body.get("members") or []

    def _member_line(m: dict) -> str:
        # Designation is omitted rather than printed as "None" when erp-api
        # sent none - the same rule the selection cards already follow.
        role = m.get("employee_designation")
        role = f" — {role}" if role and role != "N/A" else ""
        return f"- {m.get('employee_name')} ({m.get('employee_number')}){role}"

    if not members:
        return _finish("There are no employees listed under you right now.",
                       extra_data=body)

    writer({"type": "team_members", "data": body})

    lines = [f"Your team has {len(members)} member{'s' if len(members) != 1 else ''}:"]
    lines.extend(_member_line(m) for m in members)

    return _finish(chr(10).join(lines), extra_data=body)



#: A search term no employee name can contain, so the pending-teams search
#: answers with search_matched=false and the caller's whole roster.
_MATCHES_NOBODY = "zzqxnobody"


async def _roster_via_pending_search(bearer_token, company_id, conversation_id) -> Optional[dict]:
    """The caller's roster, in get_team_members' response shape, read from
    /leave/pending/teams - for when /leave/team/members is not deployed.
    None when that call fails too; a 403 is passed through for the caller."""
    try:
        result = await erp_client.get_team_pending_leaves(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
            employee_name=_MATCHES_NOBODY,
        )
    except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable):
        return None
    if result.get("http_status") == 403:
        return result
    data = (result.get("body") or {}).get("data") or {}
    members = [{"employee_name": r.get("employee_name"), "employee_number": r.get("employee_number"),
                "employee_id": r.get("employee_id"),
                "employee_designation": r.get("employee_designation")}
               for r in data.get("employees") or []]
    return {"http_status": 200, "body": {"success": True, "data": {
        "members": members, "total_members": len(members)}}}


def _team_member_line(m: dict) -> str:
    # Designation is omitted rather than printed as "None" when erp-api sent
    # none (the pending-teams search rows carry none at all).
    role = m.get("employee_designation")
    role = f" — {role}" if role and role != "N/A" else ""
    return f"- {m.get('employee_name')} ({m.get('employee_number')}){role}"


async def _answer_team_member_lookup(target, bearer_token, company_id, conversation_id,
                                     writer, finish, refuse) -> dict:
    """"Is Rohan Mehta currently an employee here?" for a manager / HR / admin.

    Asks /leave/pending/teams?employee_name=X, NOT the roster endpoint:
    /api/v1/ai/leave/team/members answers 404 on the deployed erp-api (see
    regularisation_approval), which reached the user as "I'm unable to reach
    the HR system right now" (QA, live). The pending-teams search is
    live-verified and says exactly what this question needs, within the
    caller's own scope:

      match     -> data.employees = the matching member(s)
      no match  -> data.search_matched = false + the caller's FULL roster,
                   which is the "not found - these are your team members" reply
      no team   -> 403, refused the same way an employee is
    """
    writer({"type": "fetching_team_members", "message": "Looking up your team..."})
    try:
        result = await erp_client.get_team_pending_leaves(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
            employee_name=target,
        )
    except erp_client.ErpApiTimeout:
        return finish("I couldn't reach the HR system in time — please try again in a moment.")
    except erp_client.ErpApiUnavailable as e:
        if permission_service.erp_refused_for_permission(e):
            return refuse()
        return finish(erp_client.unavailable_message(e))
    if result.get("http_status") == 403:
        return refuse()

    body = result.get("body") or {}
    data = body.get("data") or {}
    if data.get("action_required") == "search_employee":
        # erp-api rejected the search TERM ("at least 2 characters") - its own words.
        return finish(body.get("message") or "Please give me the team member's full name or employee ID.")

    rows = data.get("employees") or ([data["employee"]] if isinstance(data.get("employee"), dict) else [])
    rows = [{"employee_name": r.get("employee_name") or r.get("name"),
             "employee_number": r.get("employee_number") or r.get("emp_no"),
             "employee_id": r.get("employee_id"),
             "employee_designation": r.get("employee_designation") or r.get("designation")}
            for r in rows]

    if data.get("search_matched") is False:
        # The roster came back instead of a match. erp-api searches the NAME
        # field only, so an employee code ("EMP101") lands here even for a
        # real report - try it against the roster before calling it a miss.
        matches = _match_team_member(target, rows)
        roster = rows
    else:
        matches = _match_team_member(target, rows) or rows
        roster = []

    # The card carries its own headline. QA: a manager asking about someone
    # not on their team saw only the "Your Team" card - the "I couldn't find
    # X" sentence travelled in the reply text alone, which the UI does not
    # show next to a team_members card. `message`, `search_term` and
    # `matched` let the card say what was searched for and whether it hit.
    def _card(members, message, matched):
        return {"members": members, "total_members": len(members), "message": message,
                "search_term": target, "matched": matched}

    if len(matches) == 1:
        m = matches[0]
        role = m.get("employee_designation")
        role = f", {role}" if role and role != "N/A" else ""
        text = (f"Yes — {m.get('employee_name')} ({m.get('employee_number')}{role}) "
                f"is a member of your team.")
        card = _card(matches, text, True)
        writer({"type": "team_members", "data": card})
        return finish(text, extra_data=card)
    if len(matches) > 1:
        headline = f"I found {len(matches)} people matching \"{target}\" in your team. Which one did you mean?"
        card = _card(matches, headline, True)
        writer({"type": "team_members", "data": card})
        return finish(chr(10).join(
            [f"I found {len(matches)} people matching \"{target}\" in your team:"]
            + [_team_member_line(m) for m in matches]
            + ["Which one did you mean?"]), extra_data=card)
    if not roster:
        return finish(f"I couldn't find {target} in your team — there are no employees "
                      f"listed under you right now.")
    headline = (f"I couldn't find {target} in your team. Please check the name — "
                f"these are the members of your team:")
    card = _card(roster, headline, False)
    writer({"type": "team_members", "data": card})
    return finish(chr(10).join([headline] + [_team_member_line(m) for m in roster]),
                  extra_data=card)

def _match_team_member(target: str, members: list) -> list:
    """Members whose name (or employee number) matches `target`: an exact
    full-name or code match wins outright; otherwise every member whose name
    contains all of the target's words ("Rohan" -> "Rohan Mehta")."""
    want = " ".join(target.lower().split())
    exact = [m for m in members
             if " ".join(str(m.get("employee_name") or "").lower().split()) == want
             or str(m.get("employee_number") or "").lower() == want]
    if exact:
        return exact
    words = want.split()
    return [m for m in members
            if words and all(w in str(m.get("employee_name") or "").lower().split() for w in words)]


# ── Node 6: Team attendance summary (FR-07.2, Sprint 5) ──────────────────────
# A MANAGER asking a TEAM-LEVEL attendance question in aggregate ("how many
# employees are absent today", "show employees with missing punches") — a
# separate node from manager_attendance_explanation for the same reason
# team_leave_query_node is separate from leave_action_node: this gate blocks
# NON-managers, the opposite polarity of the individual-report gate. Date
# resolution reuses _resolve_date_range/has_date_expression exactly like
# leave_status's own date filter — deterministic-first, LLM fallback only for
# phrasing the regex layer doesn't recognize — defaulting to
# _today_in_app_timezone() (AC#4) when the query names no date at all.
#
# erp-api's GET /api/v1/ai/attendance/summary (confirmed live) exposes
# employee-level detail ONLY for missing punches (missing_punch_details.
# employees) — there is no equivalent per-employee list for absent/on-leave
# employees in the response contract, so the expandable list this node
# builds is scoped to that same data, same "render only what erp-api
# actually returned" discipline as individual_report.py.

_PERFECT_ATTENDANCE_TEMPLATE = "All {count} members of your team are present today with no missing punches!"

# The card footer for the focused missing-punch view: this node reports the
# recorded state and never explains or corrects it (individual explanations
# are attendance_explanation_node's story, corrections the Attendance
# module's), so the view says so rather than inviting a follow-up it cannot
# serve.
_VIEW_ONLY_FOOTNOTE = ("View-only summary — individual status explanations and "
                        "corrections are handled in the Attendance module.")

# A team-attendance question that names MISSING PUNCHES specifically ("show
# employees with missing punches") asks for ONE of the summary's five
# metrics, not the whole board. Answering it with the generic five-line
# board buries the number that was actually asked for, and answering it with
# the perfect-attendance copy answers a question about punches with a claim
# about presence. Matching here only chooses which view LEADS the reply —
# the Summary Card event still carries erp-api's full body either way.
_MISSING_PUNCH_QUERY_RE = re.compile(
    r"(?:missing|missed|incomplete|no|without|forgot(?:ten)?\s+to)\s+\w*\s*"
    r"(?:punch(?:es|ed|\s*ins?|\s*outs?)?|check[\s-]?(?:in|out)s?|swipes?)",
    re.I,
)


def _first_present(row: dict, *keys):
    """First key on `row` that actually carries a value. Used so the row
    renderers below read whatever erp-api named the field without inventing
    one when it named none."""
    for key in keys:
        value = row.get(key)
        if value not in (None, "", [], {}):
            return value
    return None


def _punch_clock_12h(stamp) -> Optional[str]:
    '''"2026-09-07 09:14:00" (or "09:14:00") -> "09:14 AM". Anything that
    does not split as a clock is passed through untouched rather than
    reformatted into something that might be wrong — same discipline as
    individual_report._punch_clock, which this deliberately mirrors in 12h
    form for the missing-punch card.'''
    if not stamp:
        return None
    text = str(stamp).strip()
    parts = text.split(" ")
    clock = parts[1] if len(parts) == 2 else text
    bits = clock.split(":")
    if len(bits) < 2 or not bits[0].strip().isdigit() or not bits[1][:2].isdigit():
        return text
    hour, minute = int(bits[0]), bits[1][:2]
    if hour > 23:
        return text
    return f"{hour % 12 or 12:02d}:{minute} {'AM' if hour < 12 else 'PM'}"


def _missing_punch_relation(emp: dict) -> Optional[str]:
    '''"Indirect report · via Team Lead, Rohit S." — built ONLY from what
    erp-api actually returned. The summary endpoint's employee rows carry
    no relation field today (confirmed live: employee_id, employee_number,
    employee_name, attendance_status), so this returns None and the row
    renders without a relation line rather than asserting a place in the
    org chart the payload never stated.'''
    relation = _first_present(emp, "relation", "report_type", "reporting_type", "relationship")
    if relation is None:
        is_direct = emp.get("is_direct_report", emp.get("direct_report"))
        if is_direct is None:
            return None
        relation = "direct" if is_direct else "indirect"
    label = str(relation).replace("_", " ").strip().lower()
    if label.startswith("direct"):
        label = "Direct report"
    elif label.startswith("indirect"):
        label = "Indirect report"
    else:
        label = label[:1].upper() + label[1:]
    via = _first_present(emp, "reporting_to", "reporting_manager", "manager_name", "reports_via", "via")
    if isinstance(via, dict):
        via = _first_present(via, "name", "employee_name")
    return f"{label} · via {via}" if via else label


def _missing_punch_detail(emp: dict) -> Optional[str]:
    """"Check-in 09:14 AM · no check-out" — the punch evidence for one row.
    Falls back to whatever status erp-api recorded when it sent no punch
    stamps at all; states the evidence, never a rule."""
    check_in = _punch_clock_12h(_first_present(emp, "check_in", "check_in_time", "first_check_in", "punch_in"))
    check_out = _punch_clock_12h(_first_present(emp, "check_out", "check_out_time", "last_check_out", "punch_out"))
    if check_in and check_out:
        return f"Check-in {check_in} · Check-out {check_out}"
    if check_in:
        return f"Check-in {check_in} · no check-out"
    if check_out:
        return f"No check-in · Check-out {check_out}"
    status = _first_present(emp, "attendance_status", "punch_status", "status")
    return str(status).replace("_", " ") if status else None


def _missing_punch_type(emp: dict) -> Optional[str]:
    """"Out-punch missing" — WHICH punch this row is missing, as its own
    field, because that is the question "show employees with missing punches"
    is actually asking and reading it out of a timestamp string is the
    reader's work, not theirs.

    Derived only from the stamps erp-api sent, never from a rule about what
    a shift should contain (same discipline as _missing_punch_detail): one
    stamp present and the other absent is direct evidence of which punch is
    missing. With NEITHER stamp there is nothing to distinguish an in-punch
    from an out-punch, and with BOTH there is no missing punch to name — so
    both return None and the row falls back to erp-api's own status text
    rather than asserting a punch type the payload never established.
    """
    check_in = _first_present(emp, "check_in", "check_in_time", "first_check_in", "punch_in")
    check_out = _first_present(emp, "check_out", "check_out_time", "last_check_out", "punch_out")
    if check_in and not check_out:
        return "Out-punch missing"
    if check_out and not check_in:
        return "In-punch missing"
    return None


def _missing_punch_rows(employees: list) -> list:
    """erp-api's employee rows, each carrying the display strings the
    missing-punch card needs, with the original fields left intact."""
    rows = []
    for emp in employees:
        if not isinstance(emp, dict):
            continue
        row = dict(emp)
        row["employee_name"] = _first_present(emp, "employee_name", "name") or "Unknown"
        relation = _missing_punch_relation(emp)
        if relation:
            row["relation_label"] = relation
        punch_type = _missing_punch_type(emp)
        if punch_type:
            row["missing_punch_type"] = punch_type
        detail = _missing_punch_detail(emp)
        if detail:
            row["punch_detail"] = detail
        rows.append(row)
    return rows


def _resolve_team_attendance_date(query: str, today) -> Optional[str]:
    """AC#2/AC#3 — team attendance is a READ-ONLY, past-tolerant query
    ("yesterday", "last Monday"), unlike apply-leave's future-only dates.
    _resolve_date_range's own deterministic tier calls
    date_resolver.resolve_relative_date_phrase with its default
    allow_past=False (correct for apply-leave's forward-only guarantee),
    which would otherwise silently reject "yesterday" and every other
    past-date phrase, falling all the way through to the LLM tier for
    something date_resolver already solves deterministically at zero cost.
    Tried first, here, with allow_past=True; _resolve_date_range (whose LLM
    tier is already past-date-aware — see _build_date_range_extraction_
    prompt's "last Monday" example) is the caller's own fallback for
    anything this doesn't recognize (e.g. an explicit "August 10")."""
    # A named weekday, read BACKWARDS, before the general relative resolver -
    # the same ordering (and the same reason) individual_report._resolve_
    # attendance_date already uses: resolve_relative_date_phrase is
    # forward-only, so on a Thursday it reads "Monday" as next week's, and
    # allow_past cannot help because that answer is in the future so the
    # guard never fires. Attendance is a read-only, past-tolerant query -
    # "show missing punches for Monday" means the Monday that has passed.
    # An outright calendar date FIRST - "20 August 2026", "20th Aug", "Aug 20,
    # 2026" - and past-tolerant when no year is given ("20 August" on 17 Sept
    # is this year's 20 August; "5 October" is last year's). This step was
    # missing: AC#2 rode entirely on _resolve_date_range's LLM tier, whose
    # own deterministic chain is apply-leave forward-only (it rejects every
    # past date) and which fails OPEN to None. Any hiccup on that call - a
    # timeout, an empty reply, a provider error - and the node fell through
    # to `or today.isoformat()`, answering about the current day with a card
    # headed "Today" for a manager who had named a date three weeks back.
    # individual_report._resolve_attendance_date already runs this same
    # resolver first, for the same reason.
    explicit = date_resolver.resolve_explicit_calendar_date(query, today)
    if explicit:
        return explicit

    # A numeric spelling ("20/08/2026", day-first, as everywhere else in this
    # codebase) - the same resolver _resolve_deterministic_date_range uses.
    numeric = date_resolver.resolve_numeric_date_range(query, today)
    if numeric and numeric[0] and numeric[0].get("from_date"):
        return numeric[0]["from_date"]

    weekday = date_resolver.resolve_past_weekday_phrase(query, today)
    if weekday and weekday.get("from_date"):
        return weekday["from_date"]

    resolved = date_resolver.resolve_relative_date_phrase(query, today, allow_past=True)
    return resolved["from_date"] if resolved else None


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

    def _finish(message: str, intent: str = "HRMS_TEAM_ATTENDANCE_QUERY", extra_data: Optional[dict] = None) -> dict:
        data = {"answer": message}
        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 — manager-ONLY, same inverted polarity as team_leave_query_node.
    # Trusts hr_graph.manager_gate_node's already-resolved state["is_manager"]
    # first (JWT role claim or erp-api, whichever confirmed it) rather than
    # unconditionally re-asking erp-api and risking the two disagree — see
    # team_leave_query_node's identical gate for the full rationale.
    is_manager = state.get("is_manager")
    _context_data = None
    if is_manager is None and not state.get("is_manager_jwt"):
        try:
            context_result = await erp_client.get_leave_context(bearer_token, company_id=company_id, conversation_id=conversation_id)
        except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable):
        # A failed ROLE LOOKUP is not this feature being unavailable, and
        # must not be reported as one. The old copy here ("I'm unable to
        # reach the HR system right now") described an outage of the team
        # capability, when what actually failed was the question "who is
        # asking?" — reported live for "show my team attendacne", where the
        # employee expected the "Not available" card and got an invitation
        # to retry something that would never succeed.
        #
        # The JWT can often answer that question with no network at all, so
        # it is asked first: a token naming a manager/HR/admin role proceeds
        # exactly as it would have. Only when nothing can decide does the
        # turn end, and then with the wording that says what really happened
        # — the same one the MANAGER_UNKNOWN branch below already uses.
            if permission_service.may_view_team(state) is True:
                logger.info("[Graph] Team attendance: role lookup failed, allowed on the JWT role claim")
                is_manager = True
            else:
                return _finish("I couldn't verify your access in time — please try again in a moment.")
        else:
            _context_data = context_result["body"].get("data", {})
            is_manager = _context_data.get("is_manager", False)
    elif is_manager is None:
        is_manager = True
    logger.info(f"[Graph] Team attendance summary | is_manager={is_manager}")

    # A manager is not the only caller who may see a team member's record —
    # an HR user and an admin may too, and the rule for all three lives in
    # services/permission_service. Applied as a WIDENING on top of whatever
    # the is_manager resolution above produced: it can only turn a refusal
    # into an allow, never the reverse, so the manager path is untouched.
    if is_manager is not True:
        _access = permission_service.may_view_team(state, context_data=_context_data)
        if _access is True:
            is_manager = True
            logger.info("[Graph] Team attendance allowed as an HR/admin caller")
        elif _access == permission_service.ACCESS_UNKNOWN:
            is_manager = individual_report.MANAGER_UNKNOWN

    if is_manager == individual_report.MANAGER_UNKNOWN:
        return _finish("I couldn't verify your access in time — please try again in a moment.")

    # Copy unchanged — it was already the Figma's two-sentence shape; it now
    # routes through the shared builder so the leave/members refusals cannot
    # drift away from it, and carries the "Not available" card payload.
    _restricted_msg = access_notice.message(
        "Team attendance summaries", "check your own attendance status")

    def _refuse() -> dict:
        notice = access_notice.build("team_attendance", _restricted_msg)
        writer({"type": "access_notice", "data": notice})
        return _finish(_restricted_msg, intent=access_notice.RESTRICTED_INTENT,
                       extra_data={"access_notice": notice})

    if not is_manager:
        return _refuse()

    # AC#1-4 — explicit date, relative phrase ("yesterday"/"Monday"), or
    # default to today in the app's own configured timezone. Gated behind
    # has_date_expression (computed once in classify_node) so the common
    # no-date query never pays for the extra deterministic/LLM resolution
    # work — same gate leave_status's own date filter already uses.
    today = _today_in_app_timezone()
    # The deterministic tier runs UNCONDITIONALLY. It is a handful of regexes
    # and costs nothing, and gating it behind has_date_expression made the
    # date depend on a flag computed elsewhere: whenever that flag did not
    # arrive True - a classify path that omitted it, a pre-check that did not
    # recognise the phrasing (a bare weekday name, once) - the query's date was
    # silently swapped for today (AC#4 says today is for a query with NO date
    # reference, not for one whose reference went unnoticed). Only the LLM
    # tier is worth gating, and it consults the query itself as well as the
    # flag so a stale False cannot suppress it either.
    resolved_date = _resolve_team_attendance_date(query, today)
    if not resolved_date and (
        state.get("has_date_expression") or date_resolver.mentions_date_expression(query)
    ):
        resolved_range = await _resolve_date_range(
            query, today, purpose_hint="the team's attendance summary",
        )
        resolved_date = resolved_range[0] if resolved_range else None
    resolved_date = resolved_date or today.isoformat()

    writer({"type": "fetching_team_attendance", "message": "Checking your team's attendance..."})
    try:
        result = await erp_client.get_team_attendance_summary(
            bearer_token, company_id=company_id, conversation_id=conversation_id, date=resolved_date,
        )
    except erp_client.ErpApiTimeout:
        return _finish("I couldn't reach the HR system in time — please try again in a moment.")
    except erp_client.ErpApiUnavailable as e:
        # Read what erp-api actually answered before deciding what to say.
        #
        # A permission refusal — a 401/403, or a body whose wording says "you
        # can only view your own records" — is erp-api ANSWERING the access
        # question, so it gets the same "Not available" card a locally-refused
        # caller gets. It used to surface as the infrastructure sentence
        # instead ("I'm unable to reach the HR system right now"), which
        # blames the system for a rule and invites a retry that can never
        # succeed; reported live for "show my team attendacne".
        #
        # Anything else keeps erp-api's own words when it sent any
        # ("Attendance is locked for this date"), and the infrastructure
        # sentence only when it genuinely did not reply.
        if permission_service.erp_refused_for_permission(e):
            logger.info("[Graph] Team attendance: erp-api refused on permission (status=%s) "
                        "- showing the access card, not an outage message",
                        getattr(e, "status_code", None))
            return _refuse()
        return _finish(erp_client.unavailable_message(e))

    # Same disagreement-safety net as team_leave_query_node's own 403 handling.
    # Reachable now: get_team_attendance_summary opts into allow_403_body, so a
    # 403 is RETURNED rather than raised. Before that flag this branch was dead
    # code and the manager saw "I'm unable to reach the HR system right now".
    #
    # Deliberately NOT surfacing erp-api's own 403 text here, unlike the 400
    # branch below. A 403 body is typically a bare "Forbidden" — replacing the
    # designed two-sentence refusal (which also carries the access_notice card
    # the client renders) with that word would be a downgrade, not a fix.
    if result.get("http_status") == 403:
        return _refuse()

    # A business error erp-api answered with (400) — a date it would not accept,
    # for instance. Its own sentence is the useful one; there is no card to show.
    if result.get("http_status") == 400:
        return _finish(erp_client.extract_erp_message(result.get("body"))
                       or "I couldn't read that date — try naming it another way.")

    body = result["body"].get("data", {})
    cards = body.get("summary_cards", {}) or {}
    breakdown = body.get("breakdown", {}) or {}
    total_team = (cards.get("total_team") or {}).get("value", 0)
    present = (cards.get("present") or {}).get("value", 0)
    absent = (cards.get("absent") or {}).get("value", 0)
    on_leave = (cards.get("on_leave") or {}).get("value", 0)
    missing_punches = (cards.get("missing_punches") or {}).get("value", 0)
    not_recorded = breakdown.get("not_recorded", 0) or 0
    impacted_employees = ((body.get("missing_punch_details") or {}).get("employees")) or []

    # The date the card is labelled with is the one this node QUERIED. erp-api
    # echoes the date it served (its GET /api/v1/ai/attendance/summary honours
    # the param), so the two normally agree; if they ever do not, the answer
    # must not be relabelled to whatever came back - that is exactly how a
    # "20 August" question ends up under a "Today" header. Log the
    # disagreement loudly instead, since it would mean erp-api served a
    # different day than it was asked for.
    summary_date = resolved_date
    echoed_date = body.get("date")
    if echoed_date and echoed_date != resolved_date:
        logger.warning(
            "[Graph] Team attendance summary: asked erp-api for %s, response is dated %s "
            "- labelling the card with the queried date", resolved_date, echoed_date,
        )
    is_today = summary_date == today.isoformat()
    date_phrase = "today" if is_today else f"on {summary_date}"
    date_title = "Today" if is_today else summary_date
    wants_missing_punches = bool(_MISSING_PUNCH_QUERY_RE.search(query or ""))
    rows = _missing_punch_rows(impacted_employees)

    # AC#6 — the Summary Card itself is rendered client-side from this
    # structured event (same "full body over the wire, text is the
    # accessible fallback" pattern as team_pending_leave), never as a wall
    # of unformatted text. erp-api's body is passed through untouched (AC#7:
    # the reporting-hierarchy `scope` is its call, not this node's); `view`
    # only tells the client which of the two renderings the question asked
    # for, and missing_punch_view carries the per-row display strings so
    # that card needs no field-name guessing of its own.
    event_data = {
        **body,
        # After **body on purpose: the client builds the card title from
        # data.date, so it must be the queried date (see summary_date above),
        # not whatever erp-api happened to echo.
        "date": summary_date,
        "view": "missing_punches" if wants_missing_punches else "team_attendance_summary",
    }
    if wants_missing_punches:
        event_data["missing_punch_view"] = {
            "title": f"Missing Punches — {date_title}",
            "date": summary_date,
            "employee_count": len(rows) or missing_punches,
            "employees": rows,
            "footnote": _VIEW_ONLY_FOOTNOTE,
        }
    writer({"type": "team_attendance_summary", "data": event_data})

    # A day whose punches simply have not come in yet is NOT a clean day.
    # erp-api reports absent 0 / missing_punches 0 for exactly that team
    # (breakdown.not_recorded == total_team, present 0), and reading only
    # those two zeroes is how the reply came to state "All 5 members of your
    # team are present today" about five people whose attendance nothing had
    # recorded. Presence is claimed only where erp-api actually counted it,
    # and the shortfall is stated everywhere else.
    unrecorded_note = ""
    if not_recorded:
        unrecorded_note = (
            f"Attendance hasn't been recorded yet for {not_recorded} of "
            f"{total_team} team members, so this can still change."
        )

    if wants_missing_punches:
        if not missing_punches and not rows:
            message = f"No missing punches for your team {date_phrase}."
            if unrecorded_note:
                message = f"{message} {unrecorded_note}"
            return _finish(message, extra_data=event_data)

        count = len(rows) or missing_punches
        lines = [f"Missing Punches — {date_title} "
                 f"({count} employee{'' if count == 1 else 's'})"]
        # AC#6/AC#8 — no impacted-employee list when erp-api named no
        # employees, even where its own counter is non-zero.
        if rows:
            lines.append("")
            lines.append("Impacted employees:")
            for row in rows:
                # Punch type leads: it is the field the question asked for.
                # The relation and the raw stamps follow as the evidence
                # behind it, so a manager can see WHY the row says what it
                # says without opening the Attendance module.
                detail = " · ".join(
                    part for part in (row.get("missing_punch_type"),
                                      row.get("relation_label"),
                                      row.get("punch_detail")) if part
                )
                lines.append(f"- {row['employee_name']}" + (f" — {detail}" if detail else ""))
        if unrecorded_note:
            lines.extend(["", unrecorded_note])
        return _finish("\n".join(lines), extra_data=event_data)

    if absent == 0 and missing_punches == 0 and total_team and present == total_team:
        # AC#8 — exact required copy, verbatim; only [X] is substituted.
        message = _PERFECT_ATTENDANCE_TEMPLATE.format(count=total_team)
        return _finish(message, extra_data=event_data)

    lines = []
    if absent == 0 and missing_punches == 0:
        # Nothing adverse, but not everyone is accounted for as present
        # either — say precisely that instead of borrowing AC#8's copy, and
        # name the shortfall so the zero row below can't read as a clean day.
        lead = f"No absences or missing punches for your team {date_phrase}."
        lines.append(f"{lead} {unrecorded_note}" if unrecorded_note else lead)
        lines.append("")
    lines.extend([
        f"Team attendance summary for {summary_date}:",
        f"- Total Team: {total_team}",
        f"- Present: {present}",
        f"- Absent: {absent}",
        f"- On Leave: {on_leave}",
        f"- Missing Punches: {missing_punches}",
    ])
    if not_recorded:
        lines.append(f"- Not Recorded Yet: {not_recorded}")
    if rows:
        lines.append("")
        lines.append("Impacted employees:")
        for row in rows:
            detail = " · ".join(
                part for part in (row.get("relation_label"), row.get("punch_detail")) if part
            )
            lines.append(f"- {row['employee_name']}: {detail or 'missing punch'}")

    return _finish("\n".join(lines), extra_data=event_data)


# ── Node 7: Complex manager task routing (FR-07.5) ────────────────────────────
# Large-team review, bulk approvals, shift planning, and comparative reporting
# are never attempted in chat — this node only recognizes the request and
# returns a Navigation Card pointing at the relevant traditional page. It
# never calls a bulk-approval/shift/report/team-review API itself.

async def complex_manager_task_node(state: HRState, writer: StreamWriter) -> dict:
    intent = state["intent"]
    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, extra_data: Optional[dict] = None) -> dict:
        data = {"answer": message}
        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 guard — the role must come from the authenticated backend user
    # context: either erp-api's own is_manager flag, or the role claim inside
    # the JWT erp-api itself issued (never trusted from the frontend/LLM
    # otherwise). Trusts hr_graph.manager_gate_node's already-resolved
    # state["is_manager"] first, same as team_leave_query_node's and
    # team_attendance_summary_node's identical gates, rather than
    # unconditionally re-asking erp-api and risking the two disagree.
    is_manager = state.get("is_manager")
    context_data = {}
    if is_manager is None and not state.get("is_manager_jwt"):
        try:
            context_result = await erp_client.get_leave_context(
                bearer_token, company_id=company_id, conversation_id=conversation_id
            )
        except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable):
        # A failed ROLE LOOKUP is not this feature being unavailable, and
        # must not be reported as one. The old copy here ("I'm unable to
        # reach the HR system right now") described an outage of the team
        # capability, when what actually failed was the question "who is
        # asking?" — reported live for "show my team attendacne", where the
        # employee expected the "Not available" card and got an invitation
        # to retry something that would never succeed.
        #
        # The JWT can often answer that question with no network at all, so
        # it is asked first: a token naming a manager/HR/admin role proceeds
        # exactly as it would have. Only when nothing can decide does the
        # turn end, and then with the wording that says what really happened
        # — the same one the MANAGER_UNKNOWN branch below already uses.
            if permission_service.may_view_team(state) is True:
                logger.info("[Graph] Complex manager task: role lookup failed, allowed on the JWT role claim")
                is_manager = True
            else:
                return _finish("I couldn't verify your access in time — please try again in a moment.")
        else:
            context_data = context_result["body"].get("data", {})
            is_manager = context_data.get("is_manager", False)
    elif is_manager is None:
        is_manager = True
    logger.info(f"[Graph] Complex manager task | intent={intent} | is_manager={is_manager}")

    # A manager is not the only caller who may see a team member's record —
    # an HR user and an admin may too, and the rule for all three lives in
    # services/permission_service. Applied as a WIDENING on top of whatever
    # the is_manager resolution above produced: it can only turn a refusal
    # into an allow, never the reverse, so the manager path is untouched.
    if is_manager is not True:
        _access = permission_service.may_view_team(state, context_data=context_data)
        if _access is True:
            is_manager = True
            logger.info("[Graph] Complex manager task allowed as an HR/admin caller")
        elif _access == permission_service.ACCESS_UNKNOWN:
            is_manager = individual_report.MANAGER_UNKNOWN

    if is_manager == individual_report.MANAGER_UNKNOWN:
        return _finish("I couldn't verify your access in time — please try again in a moment.")

    if not is_manager:
        # What, why, and where to go instead - the shape every refusal takes
        # (UAT tone review, 27 Oct: "isn't something I can route you to").
        msg = (
            "That's only available to managers and HR, so I can't show it here. You can "
            "still check your own leave, attendance and holidays, or ask HR for anything else."
        )
        return _finish(msg)

    navigation = route_complex_manager_task(intent)
    if not navigation:
        # Defensive fallback (LLD §15) — should not happen since intent is
        # already gated to COMPLEX_MANAGER_INTENTS, but never invent a
        # destination if the config lookup ever comes back empty.
        msg = (
            "Could you please clarify whether you're looking for team review, "
            "bulk approvals, shift planning, or comparative reporting?"
        )
        return _finish(msg)

    log_task_routed(
        user_id=context_data.get("user_id"),
        role="manager",
        intent=intent,
        target=navigation["button"]["path"],
        conversation_id=conversation_id,
    )

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


# ── Conditional edges ─────────────────────────────────────────────────────────

# _LEAVE_ACTION_INTENTS = {"leave_balance", "apply_leave", "leave_status","cancel_leave", "leave_eligibility", "leave_type_clarify"}
# _PUNCH_DETAILS_INTENTS = {"punch_details"}
# NOTE: named distinctly from _ATTENDANCE_INTENTS below — that one is the
# plain "attendance" intent (live record lookup, attendance_node), this one
# is "attendance_explain" (WHY a specific day was classified a certain way,
# attendance_explain_node). Easy to conflate since both are attendance-
# adjacent; keep the names apart.
# _ATTENDANCE_EXPLAIN_INTENTS = {"attendance_explain"}
# _ATTENDANCE_INTENTS = {"attendance"}
# _HRMS_REGULARIZATION = {"regularisation"}
_SHIFT_QUERY_INTENTS = {"shift_query"}
_INDIVIDUAL_REPORT_INTENTS = {"manager_leave_request_lookup", "manager_attendance_explanation"}

# One route per sub-intent, so the path a query takes is visible in the graph
# instead of being a branch inside a single node. Both land on the shared
# pipeline in individual_report.py - see the node wrappers there.
_INDIVIDUAL_REPORT_ROUTES = {
    "manager_leave_request_lookup": "leave_request_node",
    "manager_attendance_explanation": "attendance_explanation_node",
}

# FR-07.4 - the one state-CHANGING manager intent (leave_approval.py).
_LEAVE_APPROVAL_INTENTS = {"manager_leave_approval"}

# Manager attendance-regularization (regularisation_approval.py). Both land
# on one node: the view is the read half of the same feature, and keeping
# them together is what lets "approve that one" follow a list without a
# second lookup.
_REGULARISATION_APPROVAL_INTENTS = {
    "manager_regularisation_view",
    "manager_regularisation_approval",
}

# The EMPLOYEE's own regularization requests - read-only, and deliberately
# separate from both the manager queue above (different scope, different
# erp-api route) and the apply flow (which CREATES a request). Without its
# own intent, "show my regularization requests" matched the apply flow and
# opened the submit form.
_MY_REGULARISATION_VIEW_INTENTS = {"my_regularisation_view"}
# An employee cancelling one of their OWN regularization requests.
_REGULARISATION_CANCEL_INTENTS = {"my_regularisation_cancel"}


def _general_chat_may_take_the_turn(state: HRState) -> bool:
    """FR-01: a turn the classifier called non-HR is answered by the general
    lane whenever general chat is switched on - for any role (employee,
    manager, HR, admin). Off, it gets the HR redirect exactly as before.

    The switch is resolved per request in main.py from the feature_flags row
    AND the GENERAL_CHAT_MASTER_ENABLED env kill-switch, both of which must
    be on. Anything other than True - including the key missing - is off.
    """
    return state.get("general_chat_enabled") is True


def _route_after_individual_report(state: HRState) -> str:
    """Normally END, as this node has always been.

    The one exception: classify_node guessed that a manager's bare message
    named an employee, erp-api checked the directory and found nobody, and
    the node withdrew the guess rather than answering a general question
    with an employee picker (see individual_report.GUESSED_SUBJECT_NOT_AN
    _EMPLOYEE). The turn has not been answered at that point, so it is handed
    on to the same two destinations a non-HR turn would have reached.

    Routed through _general_chat_may_take_the_turn so there is ONE answer to
    "may the general lane have this turn?".
    """
    if state.get("route_to") != individual_report.GUESSED_SUBJECT_NOT_AN_EMPLOYEE:
        return END
    if _general_chat_may_take_the_turn(state):
        return "general_chat_node"
    return "non_hr_node"


def _route_after_safety(state: HRState) -> str:
    """On to classification, or - when a safety check answered the turn - the
    route that answer took from classify_node before the step existed."""
    if state.get("safety_passed"):
        # A reply to a paused card goes back to its flow (Phase 5).
        flow = flow_interrupts.flow_of(state)
        return flow_interrupts.FLOWS[flow]["node"] if flow else "classify_node"
    return _route_after_classify(state)


def _route_after_classify(state: HRState) -> str:
    if state.get("error"):
        return END
    if state.get("intent") == "HRMS_TEAM_LEAVE_QUERY":
        return "team_leave_query_node"
    if state.get("intent") == "HRMS_TEAM_ATTENDANCE_QUERY":
        return "team_attendance_summary_node"
    if state.get("intent") == "HRMS_TEAM_MEMBERS_QUERY":
        return "team_members_node"
    if state.get("intent") in (reporting_manager.INTENT, reporting_manager.CONTACT_INTENT):
        return "reporting_manager_node"
    intent = state.get("intent")
    # A follow-up to the holiday answer (classify_node's QF-01 check):
    # hr_response_node answers it from the holiday calendar.
    if intent == "leave_holidays":
        return "hr_response_node"
    # classify_node already streamed the "done" event (the leave-type
    # clarifying question, e.g. "would you like your sick leave balance,
    # eligibility, ...") and set response_text itself for this sentinel —
    # nothing downstream should run, or the user gets a second, contradictory
    # answer for the same turn.
    if intent == "leave_type_clarify":
        return END
    # Two actions in one message: classify_node already asked which first.
    if intent == "two_actions_clarify":
        return END
    # Same for an unrecognised leave code ("pl"): classify_node already
    # streamed the list of leave types it can help with.
    if intent == "unknown_leave_type":
        return END
    # Applying a regularization for someone else: classify_node already
    # streamed the refusal.
    if intent == "regularization_other_employee":
        return END
    # "did you mean 03 Sep or 30 Sep?" - classify_node already asked; the
    # answer re-reads the original message on the next turn.
    if intent == "date_clarify":
        return END
    # classify_node's own access gate (someone else's records, normal user)
    # already streamed the card and the done event under the single deny
    # intent - nothing downstream may run, or the refusal gets a second answer.
    if intent == access_notice.RESTRICTED_INTENT and state.get("response_text"):
        return END
    if intent == "clarify_needed":
        return "clarify_node"
    # Checked before _LEAVE_ACTION_INTENTS and deliberately kept out of that
    # set: eligibility is a read-only question, and leave_action_node owns the
    # apply-flow slot state that must not be touched by one.
    # Product rule: a question that says "eligible"/"eligibility" (typos
    # included) is answered by the eligibility check, not the policy
    # documents - also when the classifier labelled it a policy question
    # ("what is the eligibility for earned leave").
    if intent in ("policy", "leave_policy") and _looks_like_eligibility_question(state.get("query", "")):
        logger.info("[Graph] %s question names eligibility - routing to leave_eligibility_node", intent)
        return "leave_eligibility_node"
    if intent == "leave_eligibility":
        # A conditional turns this into a policy question the node cannot
        # answer — it would reach LEAVE_TYPE_NOT_SPECIFIED and reply with a
        # menu of leave types. Send it to the documents instead. Not when the
        # user said "eligible" (see the product rule above): "am I eligible
        # for sick leave if I joined last month" is still about THEM.
        if (not mentions_eligibility(state.get("query", ""))
                and _eligibility_question_is_really_a_rule(state.get("query", ""))):
            logger.info("[Graph] eligibility question carries a condition — routing to policy")
            return "policy_rag_node"
        return "leave_eligibility_node"
    # WRITING a policy, not looking one up. Checked before the `policy`
    # branch below on purpose: that branch sends the turn to the uploaded
    # documents, which is right for "what is our WFH policy" and wrong for
    # "make me a WFH policy" — the documents have nothing to say about a
    # document that does not exist yet, and the miss was being reported to
    # the user as "I do not have this information".
    if intent == "policy_draft":
        return "policy_draft_node"
    # Retrieval-augmentation step for general policy questions — see
    # policy_rag_node's docstring. It always hands off to hr_response_node
    # itself (with or without retrieved context), so this is the only
    # branch point needed here.
    if intent == "policy":
        return "policy_rag_node"
    if intent in _LEAVE_ACTION_INTENTS:
        return "leave_action_node"
    if intent in _SHIFT_QUERY_INTENTS:
        return "shift_query_node"
    if intent in _LEAVE_APPROVAL_INTENTS:
        return "leave_approval_node"
    if intent in _REGULARISATION_APPROVAL_INTENTS:
        return "regularisation_approval_node"
    if intent in _MY_REGULARISATION_VIEW_INTENTS:
        return "my_regularisation_view_node"
    if intent in _REGULARISATION_CANCEL_INTENTS:
        return "regularisation_cancel_node"
    if intent in _INDIVIDUAL_REPORT_ROUTES:
        return _INDIVIDUAL_REPORT_ROUTES[intent]
    if intent in COMPLEX_MANAGER_INTENTS:
        return "complex_manager_task_node"
    if intent in _PUNCH_DETAILS_INTENTS:
        return "punch_details_node"
    if intent in _ATTENDANCE_EXPLAIN_INTENTS:
        return "attendance_explain_node"
    if intent in _ATTENDANCE_INTENTS:
        return "attendance_node"
    if intent in _HRMS_REGULARIZATION:
        return "regularisation_node"

    # "follow_up" is not an LLM label — classify_node applies it when a
    # short fragment arrives in an HR conversation and the classifier could
    # not name a topic for it. It reaches the generic HR responder by
    # design, but it is stated here rather than left to the fall-through
    # below, because being an unroutable label is exactly how it once
    # swallowed punch queries: a bare date fragment got labelled
    # "follow_up" and was answered as calendar trivia instead of a punch
    # lookup (see classify_node's override, which now continues the
    # previous intent for those). Any future intent that lands here
    # unroutable should be caught by name, not absorbed silently.
    if intent == "follow_up":
        return "hr_response_node"

    if not state.get("is_hr"):
        # FR-01. The ONLY branch this ticket adds, and it is deliberately the
        # LAST thing that can claim a turn: everything above has already
        # declined, so nothing an HR path does can be affected by what is
        # written here. With the flag off the helper returns False on its
        # first line and this reads exactly as it did before — one call, same
        # destination — which is what makes "disabled is identical to today"
        # something you can check rather than hope for.
        #
        # DO NOT move this branch higher or widen the helper to win a case
        # that feels like it should work. The guardrail below is also the bug
        # detector: every routing failure found in QA surfaced AS "that's
        # outside my HR expertise". Anything that reaches general chat by
        # mistake stops being a visible refusal and becomes a fluent wrong
        # answer instead.
        if _general_chat_may_take_the_turn(state):
            return "general_chat_node"
        return "non_hr_node"

    # Everything left is an INFORMATIONAL question -- it asks what something
    # IS, not what this employee's own record says. All of them used to go
    # straight to the generic responder, which answers from general HR
    # knowledge plus a web search, so a question the company's own documents
    # answer got a reply assembled from other companies' HR blogs instead.
    #
    # They check the documents FIRST now. policy_rag_node hands off to
    # hr_response_node either way, so a question the documents do not cover
    # is answered exactly as before -- this only adds a lookup, never removes
    # a path. It also means the classifier no longer has to be perfect: a
    # policy question that lands on employee_management or compliance still
    # reaches the documents, which is what "check the policy first" buys.
    #
    # Deliberately excludes the record-backed intents (attendance, punch,
    # leave balance/status, the manager views): those have a real API answer
    # and must not be answered from a document.
    return "policy_rag_node" if intent in _DOCUMENT_BACKED_INTENTS else "hr_response_node"

# ── Build & compile ───────────────────────────────────────────────────────────

# ── Reliability: retries + one clear fallback per node ───────────────────────
# A node that raises used to end the turn with main.py's generic greeting.
# Now:
#   * a TRANSIENT failure (a dropped or refused connection, a pool wait, an
#     erp-api timeout, a 429/5xx from race-api) re-raises, and LangGraph's
#     RetryPolicy runs the node once more - on READ-ONLY nodes only;
#   * anything else, or a transient one that survives the retry on a node
#     with no retry, ends the turn with NODE_FAILURE_MESSAGE as an ordinary
#     reply (a done event), tagged with the node's name.
# Write nodes are never retried: an erp-api write is not idempotent, and they
# clear their confirmation card before calling erp-api on purpose.
NODE_FAILURE_MESSAGE = ("Sorry, I couldn't finish that just now - please try again in a moment. "
                        "I'm Helix AI and can help with your leave, attendance, regularization and shifts.")

_WRITE_NODES = frozenset({
    "leave_action_node", "leave_approval_node", "regularisation_approval_node",
    "regularisation_cancel_node", "regularisation_eligibility_node", "regularisation_node",
    "policy_draft_node",
})


def _is_transient(exc: BaseException) -> bool:
    if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout,
                        httpx.RemoteProtocolError, erp_client.ErpApiTimeout)):
        return True
    if isinstance(exc, httpx.HTTPStatusError):
        return exc.response is not None and exc.response.status_code in (429, 500, 502, 503, 504)
    return False


_READ_RETRY_POLICY = RetryPolicy(max_attempts=2, initial_interval=0.5, backoff_factor=2.0,
                                 max_interval=2.0, jitter=True, retry_on=_is_transient)


def with_fallback(name: str, node):
    """`node`, closing the turn with NODE_FAILURE_MESSAGE when it raises. A
    transient error on a retried node is re-raised for the RetryPolicy."""
    takes_writer = "writer" in inspect.signature(node).parameters
    retried = name not in _WRITE_NODES

    async def _node(state: HRState, writer: StreamWriter):
        try:
            result = node(state, writer) if takes_writer else node(state)
            if inspect.isawaitable(result):
                result = await result
            return result
        except GraphBubbleUp:
            raise   # interrupt() pausing the run (Phase 5) - not a failure
        except Exception as e:
            if retried and _is_transient(e):
                raise
            logger.exception(f"[Graph] {name} failed - closing the turn with the fallback reply: {e}")
            usage_events = list(state.get("usage_events") or [])
            writer({"type": "chunk", "content": NODE_FAILURE_MESSAGE})
            writer({"type": "done", "intent": state.get("intent") or "general", "is_hr": True,
                    "data": {"answer": NODE_FAILURE_MESSAGE}, "message": NODE_FAILURE_MESSAGE,
                    "usage_events": usage_events, "failure_stage": name})
            # Any card waiting in the graph state is dropped with the turn: a
            # crash may have come mid-write, and a later "yes" must not resend.
            return {"response_text": NODE_FAILURE_MESSAGE, "usage_events": usage_events,
                    "error": "node_failed",
                    **{key: None for key in flow_interrupts.PERSISTED_KEYS if state.get(key)}}

    _node.__name__ = getattr(node, "__name__", name)
    return _node


def _add_node(graph, name: str, node):
    """add_node with the fallback wrapper, and the retry policy on read-only
    nodes. `retry_policy=` is LangGraph 1.x's name; 0.2/0.3 call it `retry=`."""
    wrapped = with_fallback(name, node)
    if name in _WRITE_NODES:
        return graph.add_node(name, wrapped)
    try:
        return graph.add_node(name, wrapped, retry_policy=_READ_RETRY_POLICY)
    except TypeError:
        return graph.add_node(name, wrapped, retry=_READ_RETRY_POLICY)


def build_hr_graph(checkpointer=None):
    """The compiled graph. `checkpointer` saves its state between messages
    (services/graph_checkpointer, Phase 4); None keeps every run stateless."""
    graph = StateGraph(HRState)
    _add_node(graph, "ownership_guard_node", ownership_guard_node_impl)

    _add_node(graph, "safety_node", safety_node)
    _add_node(graph, "classify_node", classify_node)
    _add_node(graph, "non_hr_node", non_hr_node)
    _add_node(graph, "general_chat_node", general_chat_node)
    _add_node(graph, "policy_rag_node", policy_rag_node)
    _add_node(graph, "hr_response_node", hr_response_node)
    _add_node(graph, "leave_action_node", leave_action_node)
    _add_node(graph, "team_leave_query_node", team_leave_query_node)
    _add_node(graph, "shift_query_node", shift_query_node)
    _add_node(graph, "policy_draft_node", policy_draft_node_impl)
    _add_node(graph, "my_regularisation_view_node", my_regularisation_view_node)
    _add_node(graph, "regularisation_cancel_node", regularisation_cancel_node)
    _add_node(graph, "team_attendance_summary_node", team_attendance_summary_node)
    _add_node(graph, "team_members_node", team_members_node)
    _add_node(graph, "reporting_manager_node", reporting_manager.reporting_manager_node)
    _add_node(graph, "complex_manager_task_node", complex_manager_task_node)
    # The manager gate runs before classification, not after it: whether the
    # caller may act on a colleague's record is settled before anything
    # decides WHICH question they asked, so a non-manager never reaches the
    # sub-intent classifier whatever the routing does later. It never
    # branches - every query passes through to classify_node - so ordinary
    # HR chat is unaffected beyond one cached flag on the state.
    _add_node(graph, "manager_gate_node", manager_gate_node)
    _add_node(graph, "leave_eligibility_node", leave_eligibility_node_impl)
    _add_node(graph, "punch_details_node", punch_details_node_impl)
    _add_node(graph, "leave_request_node", leave_request_node)
    _add_node(graph, "attendance_explain_node", attendance_explain_node_impl)
    _add_node(graph, "attendance_explanation_node", attendance_explanation_node)
    
    _add_node(graph, "leave_approval_node", leave_approval_node)
    _add_node(graph, "regularisation_approval_node", regularisation_approval_node)
    _add_node(graph, "attendance_node", attendance_node_impl)
    _add_node(graph, "regularisation_eligibility_node", regularisation_eligibility_node_impl)
    _add_node(graph, "regularisation_node", regularisation_node_impl)
    _add_node(graph, "clarify_node", clarify_node)
    # Phase 5: each pausing flow's wait step (interrupt). Its reply goes
    # through the safety step and back to the flow - see flow_interrupts.
    for _flow_name, _flow in flow_interrupts.FLOWS.items():
        _add_node(graph, _flow["wait"], flow_interrupts.make_wait_node(_flow_name))

    graph.add_edge(START, "manager_gate_node")
    # Both gates run before classification, chained rather than either/or:
    # the merge that brought sprint-4 in wired START straight to the manager
    # gate and left the ownership guard registered but with no inbound edge,
    # which silently switched off the other-employee privacy check.
    #
    # Order matters and is the reason the guard can be re-enabled safely:
    # manager_gate_node resolves is_manager FIRST (JWT claim, then erp-api),
    # so by the time ownership_guard_node asks "may this caller see someone
    # else's record" the answer is already on the state — see the is_manager
    # short-circuit in ownership_guard_node. Guard before gate would block
    # every manager whose status only erp-api knows.
    graph.add_edge("manager_gate_node", "ownership_guard_node")

    # The safety step sits between the guards and classification (Phase 3):
    # a message passes it or is answered by it - see services/safety_node.py.
    graph.add_conditional_edges(
        "ownership_guard_node",
        _route_after_ownership,
        {
            END: END,
            "classify_node": "safety_node",
        },
    )
    after_classify = {
            END: END,
            "hr_response_node": "hr_response_node",
            "non_hr_node": "non_hr_node",
            "general_chat_node": "general_chat_node",
            "leave_action_node": "leave_action_node",
            "team_leave_query_node": "team_leave_query_node",
            "reporting_manager_node": "reporting_manager_node",
            "shift_query_node": "shift_query_node",
            "policy_draft_node": "policy_draft_node",
            "leave_request_node": "leave_request_node",
            "attendance_explanation_node": "attendance_explanation_node",
            "leave_approval_node": "leave_approval_node",
            "regularisation_approval_node": "regularisation_approval_node",
            "my_regularisation_view_node": "my_regularisation_view_node",
            "regularisation_cancel_node": "regularisation_cancel_node",
            "team_attendance_summary_node": "team_attendance_summary_node",
            "team_members_node": "team_members_node",
            "complex_manager_task_node": "complex_manager_task_node",
            "leave_eligibility_node": "leave_eligibility_node",
            "punch_details_node": "punch_details_node",
            "attendance_explain_node": "attendance_explain_node",
            "attendance_node": "attendance_node",
            "policy_rag_node": "policy_rag_node",
            # Direct entry into regularisation (no prior attendance/
            # attendance_explain lookup this conversation) goes through the
            # eligibility gate first — see regularisation_eligibility_node's
            # own docstring in regularisation_node.py. attendance_node/
            # attendance_explain_node's own hand-off below is wired straight
            # to "regularisation_node" instead, since it already screened
            # the date's status before ever routing here.
            "regularisation_node": "regularisation_eligibility_node",
            "clarify_node": "clarify_node",
    }
    graph.add_conditional_edges("classify_node", _route_after_classify, after_classify)
    graph.add_conditional_edges("safety_node", _route_after_safety,
                                {**after_classify, "classify_node": "classify_node"})
    graph.add_edge("hr_response_node", END)
    graph.add_edge("policy_rag_node", "hr_response_node")
    graph.add_edge("non_hr_node", END)
    graph.add_edge("general_chat_node", END)
    graph.add_edge("leave_action_node", END)
    graph.add_edge("team_leave_query_node", END)
    graph.add_edge("shift_query_node", END)
    graph.add_edge("policy_draft_node", END)
    graph.add_edge("my_regularisation_view_node", END)
    # Ends the turn - or, while its card waits on a reply and the flow pauses
    # (INTERRUPT_REG_CANCEL), goes on to its wait step (Phase 5).
    for _flow_name, _flow in flow_interrupts.FLOWS.items():
        graph.add_conditional_edges(_flow["node"], flow_interrupts.route_after_flow(_flow_name, END),
                                    {_flow["wait"]: _flow["wait"], END: END})
        graph.add_edge(_flow["wait"], "safety_node")
    # NOT a plain edge to END any more: a withdrawn employee-name guess is
    # handed back here instead of being answered. See
    # _route_after_individual_report. attendance_explanation_node keeps its
    # plain edge - the guess only ever produces manager_leave_request_lookup,
    # so that node cannot be reached by one.
    graph.add_conditional_edges(
        "leave_request_node",
        _route_after_individual_report,
        {
            "general_chat_node": "general_chat_node",
            "non_hr_node": "non_hr_node",
            END: END,
        },
    )
    # Same conditional edge as its sibling above. Today the guess can only
    # produce manager_leave_request_lookup, so this node cannot be reached by
    # one - but the handoff deliberately emits NO done event, so if that ever
    # changes and this is still a plain edge to END, the turn ends with no
    # answer at all and nothing in the logs to say why. Cheap insurance
    # against a silent empty response.
    graph.add_conditional_edges(
        "attendance_explanation_node",
        _route_after_individual_report,
        {
            "general_chat_node": "general_chat_node",
            "non_hr_node": "non_hr_node",
            END: END,
        },
    )
    graph.add_edge("leave_approval_node", END)
    graph.add_edge("regularisation_approval_node", END)
    graph.add_edge("team_attendance_summary_node", END)
    graph.add_edge("team_members_node", END)
    graph.add_edge("reporting_manager_node", END)
    graph.add_edge("complex_manager_task_node", END)
    graph.add_edge("leave_eligibility_node", END)
    graph.add_edge("punch_details_node", END)
    graph.add_conditional_edges(
        "attendance_node",
        _route_after_attendance,
        {
            END: END,
            "regularisation_node": "regularisation_node",
        },
    )
    graph.add_conditional_edges(
            "attendance_explain_node",
            _route_after_attendance,
            {
                END: END,
                "regularisation_node": "regularisation_node",
            },
        )
    graph.add_conditional_edges(
        "regularisation_eligibility_node",
        _route_after_regularisation_eligibility,
        {
            END: END,
            "regularisation_node": "regularisation_node",
        },
    )
    graph.add_edge("regularisation_node", END)


    return graph.compile(checkpointer=checkpointer)


class _CompoundAwareGraph:
    """The compiled graph, answering both halves of a two-part message.

    "what's my leave balance and who invented radio?" reached one node and
    the second question was dropped (pilot run, 28 Oct: 26 of 35). With
    services.compound_query.split() finding two asks, the graph runs once per
    part: the first part's events pass through as usual, the second part's
    text follows it, and ONE done event closes the turn with both answers.
    A refusal on either part ends with that refusal, as a single message
    would. Everything else (nodes, get_graph, ...) is the compiled graph's."""

    def __init__(self, compiled):
        self._compiled = compiled

    def __getattr__(self, name):
        return getattr(self._compiled, name)

    async def astream(self, state, *args, stream_mode="custom", **kwargs):
        # A resumed run (a Command) or a reply sent to a flow's card is one
        # answer to that card, never two questions (Phase 5).
        is_card_reply = not isinstance(state, dict) or state.get("resumed_flow")
        parts = (compound_query.split(state.get("query", ""))
                 if stream_mode == "custom" and not is_card_reply else None)
        if not parts:
            async for event in self._compiled.astream(state, *args, stream_mode=stream_mode, **kwargs):
                yield event
            return

        first, second = parts
        logger.info("[Graph] two questions in one message - answering %r, then %r", first[:60], second[:60])

        def _part_state(query, extra=None):
            nlp_intent, _, nlp_confidence = fast_classify(query)
            return {**state, **(extra or {}), "query": query,
                    "intent": nlp_intent if (nlp_intent and nlp_confidence >= 0.5) else "general"}

        first_done = None
        async for event in self._compiled.astream(_part_state(first), *args, stream_mode=stream_mode, **kwargs):
            if event.get("type") == "done":
                first_done = event
                continue
            yield event
            if event.get("type") == "guardrail" and event.get("status") == "failed":
                return
        if first_done is None:
            return

        first_data = first_done.get("data") if isinstance(first_done.get("data"), dict) else {}
        first_answer = first_data.get("answer") or first_done.get("message") or ""
        context = list(state.get("context") or []) + [
            {"role": "user", "content": first},
            {"role": "assistant", "content": first_answer}]
        second_done, second_answer = None, ""
        yield {"type": "chunk", "content": "\n\n"}
        async for event in self._compiled.astream(
                _part_state(second, {"context": context, "last_intent": first_done.get("intent")}),
                *args, stream_mode=stream_mode, **kwargs):
            etype = event.get("type")
            if etype == "intent":
                continue  # the turn keeps the first part's intent
            if etype == "done":
                second_done = event
                continue
            if etype == "guardrail":
                if event.get("status") == "failed":
                    second_answer = event.get("message") or ""
                continue
            yield event

        if second_done is not None:
            second_data = second_done.get("data") if isinstance(second_done.get("data"), dict) else {}
            second_answer = second_data.get("answer") or second_done.get("message") or second_answer
        else:
            second_data = {}
        # One card at most on the done event: the first part's, else the second's.
        card = {k: v for k, v in first_data.items() if k != "answer"} \
            or {k: v for k, v in second_data.items() if k != "answer"}
        combined = "\n\n".join(a for a in (first_answer, second_answer) if a)
        yield {**first_done, "data": {**card, "answer": combined}, "message": combined,
               "usage_events": list(first_done.get("usage_events") or [])
               + list((second_done or {}).get("usage_events") or [])}


hr_graph = _CompoundAwareGraph(build_hr_graph(graph_checkpointer.from_env()))