"""The ONE graph state schema.

services/hr_graph.py builds its StateGraph from this class and every node —
in hr_graph.py and in the service modules — annotates its `state` parameter
with it. There used to be a second, hand-maintained copy of this TypedDict
inside hr_graph.py; keeping the two in step by eye produced two silent bugs
(is_manager missing from this file, regularisation_blocked missing from that
one — each time the key simply was not a channel, so the value a node
returned vanished before the router saw it). It was removed. Do not add
another copy; add keys here.

Two LangGraph rules make a missing key silent rather than loud, which is why
tests/test_graph_wiring.py asserts every key any node reads or returns is
declared here:
  1. StateGraph(HRState) — a key not declared is not a channel; a node that
     returns it has that value dropped.
  2. A node's input is filtered to the keys of its annotated TypedDict; a
     key not declared reads back as None inside the node no matter what the
     previous node set.
"""
from typing_extensions import TypedDict
from typing import Optional


class HRState(TypedDict):
    query: str
    context: list
    intent: str
    is_hr: bool
    # Derived, not separately LLM-classified — see classify_node's
    # _DATABASE_WIRED_INTENTS/_DATABASE_CAPABLE_INTENTS and
    # date_resolver.mentions_date_expression. Both are cheap frozenset/regex
    # checks computed once per query alongside intent/is_hr, never a second
    # LLM call.
    is_database_related: bool
    has_date_expression: bool
    moderation: dict
    output_guardrail: dict
    response_text: str
    error: Optional[str]
    usage_events: list
    # Apply-leave / leave-balance conversation (see leave_action_node).
    # No role field here: leave is open to every caller, and the identity
    # context leave_action_node fetches is a per-turn access check, not
    # conversation state worth carrying.
    bearer_token: str
    company_id: str
    conversation_id: str
    # Resolved by hr_graph.manager_gate_node BEFORE classification, and read
    # by every manager-gated shortcut in classify_node (leave approval,
    # individual report, regularisation view/approve, and the pending-card
    # resolvers).
    #
    # History worth keeping: while is_manager was missing from this class,
    # `state.get("is_manager") is True` was false on every request no matter
    # what manager_gate_node had resolved, and every manager-gated rung fell
    # through to the ~4k-token LLM classifier instead of routing
    # deterministically. The nodes still re-check the role themselves, so
    # nothing was ever wrongly ALLOWED by this — it silently cost the
    # shortcuts, and with them the stability they exist to provide. See the
    # module docstring for why a missing key fails silently.
    #
    # is_manager is tri-state: True / False / MANAGER_UNKNOWN (erp-api was
    # unreachable), so callers test `is True` rather than truthiness.
    is_manager: object
    is_manager_jwt: bool
    # The caller's HR role, resolved by the same manager_gate_node round trip
    # (erp-api answers is_manager and is_hr in one response) and tri-state for
    # the same reason: True / False / MANAGER_UNKNOWN.
    #
    # NOT to be confused with `is_hr` above, which says the QUERY is
    # HR-related. Two different questions that share a word; conflating them
    # would make every HR-topic question look like an HR-ROLE caller, which
    # is a permission decision. Hence the _role suffix.
    is_hr_role: object
    # Same-turn node handoff (see attendance_node -> regularisation_node).
    # Set by a node that wants the graph to continue straight into another
    # node in the SAME invocation rather than ending on END. Any node that
    # reads this should treat it as consumed (it isn't auto-cleared between
    # turns since a fresh HRState is built per request).
    route_to: Optional[str]
    # Set by ownership_guard_node (the very first node, START -> here) — True
    # when the query asks for another employee's/a group's attendance data
    # and the caller isn't privileged; _route_after_ownership reads this to
    # end the turn immediately instead of continuing to classify_node.
    blocked: Optional[bool]
    # Set by regularisation_eligibility_node (classify_node's direct route
    # into regularisation only — see hr_graph.py's build_hr_graph) — True
    # when THIS message named an explicit date that isn't regularisable
    # (status not Absent/Half Day Absent, or outside the regularization
    # window); _route_after_regularisation_eligibility reads this to end the
    # turn immediately instead of continuing into regularisation_node.
    regularisation_blocked: Optional[bool]
    # The intent of the PREVIOUS turn in this conversation, seeded by
    # main.py from chat_service.get_last_intent. The only piece of
    # cross-turn intent memory this graph has: state is rebuilt from
    # scratch every query and redis_chat_service stores role + content
    # only, so without this a follow-up naming just a date has nothing to
    # tell classify_node WHICH topic it is refining. None on the first
    # turn of a conversation.
    #
    last_intent: Optional[str]
    # Set by classify_node's bare-verb fast-path and consumed by
    # clarify_node in the same turn — see services/bare_verb_config.py.
    # A lone verb ("apply", "cancel", "regularise", "check") names no
    # object, so the turn ends on a clarify card carrying the prompt and
    # the choices rather than guessing which flow was meant.
    clarify_message: Optional[str]
    clarify_options: Optional[list]
    # Set by classify_node for a turn the model must answer under one strict
    # instruction, with no earlier messages ("...", another employee's pay -
    # UAT UV-12). turn_fallback is said if the model gives nothing.
    turn_instruction: Optional[str]
    turn_fallback: Optional[str]
    # Set by policy_rag_node — a summary of race-api RAG-retrieved policy
    # document excerpts for a policy question, or None when RAG isn't
    # configured/the lookup found nothing. hr_response_node injects it as
    # extra system context when present; every other node ignores it.
    policy_context: Optional[str]
    # True when the company's own documents were searched and do not answer
    # the question. hr_response_node says so plainly instead of falling back
    # to general HR knowledge and a web search — that fallback is how "what is
    # my company policy" came back as an essay sourced from other companies'
    # HR blogs, citations and all.
    #
    # MUST be declared here. LangGraph validates a node's return against this
    # schema and silently drops any key it does not know, so an undeclared
    # flag reads back as None and the branch that depends on it never fires.
    policy_lookup_failed: Optional[bool]
    # True when policy_context is an OVERVIEW of every policy document ("show
    # my policy", "what policies do we have") rather than an answer to one
    # question. hr_response_node sends it as the answer as written: a second
    # model pass over it turned the overview into "Which specific policy would
    # you like to see?" and the employee never saw the policies.
    policy_overview: Optional[bool]
    # The tenant's leave policy from its erp-api leave configuration, fetched
    # by policy_rag_node BEFORE the document search so a leave-policy
    # question does not wait ~8 s for retrieval it will not use.
    configured_policy_answer: Optional[str]
    # Whether the general-purpose (non-HR) lane may claim this turn, resolved
    # ONCE per request in main.py and carried in here as a plain bool.
    #
    # Resolved outside the graph on purpose: the decision needs a DB session
    # (the feature_flags row) and no node has one. Reading it here instead
    # would mean either a session per node or a module-level cache, and a
    # cache is exactly what makes a kill-switch stop being a kill-switch.
    # main.py reads it per request, so flipping the flag takes effect on the
    # next message with no restart.
    #
    # Absent/None is the SAME as False — the lane is off unless something
    # positively turned it on. _route_after_classify is the only reader.
    general_chat_enabled: Optional[bool]
    # FR-08: this user has used up their general-chat allowance for the
    # current window (GENERAL_CHAT_HOURLY_LIMIT). Counted in main.py, read
    # only by general_chat_node, which then answers with the limit message.
    # HR turns never look at it.
    general_chat_over_limit: Optional[bool]
    # True when `intent` is a GUESS that this message is an employee's name,
    # not something the message actually says.
    #
    # classify_node has a rung (~4347) that reads a manager's bare 1-4 word
    # message as a person's name, because for a manager "arshdeep" really
    # does mean "show me Arshdeep's leave requests". It has to guess BEFORE
    # the classifier runs, and it cannot check the guess: the only thing that
    # separates a name from a topic is the employee directory, which lives an
    # erp-api call away. Measured, the classifier is no help either - it
    # labels the real employees `abctest` and `a khan test` non_hr exactly as
    # it labels `photosynthesis`.
    #
    # So the guess is made, and THIS flag carries "that was a guess" forward
    # to individual_report, which resolves the term against the directory
    # anyway. Matched: nothing changes. Matched nobody: the guess was simply
    # wrong, and the turn is handed back instead of answering a general
    # question with an employee picker.
    #
    # Only the UNPROMPTED guess sets it. When a previous turn asked "which
    # person?" the bare reply genuinely is a name and a no-match must still
    # re-show the picker - that is the user answering a question, not us
    # guessing.
    report_subject_was_guessed: Optional[bool]
    # Set by classify_node when it re-reads a message whose mistyped date
    # ("3o sept") the employee has just clarified - so the re-read is not
    # asked about again. See classify_node._date_typo_turn.
    date_typo_checked: Optional[bool]
    # Set by safety_node: the safety checks ran this turn (classify_node then
    # skips them), and whether the message passed them (on to classify_node)
    # or one of them answered the turn. See classify_node.run_safety_checks.
    safety_checked: Optional[bool]
    safety_passed: Optional[bool]
    # Phase 5 (services/flow_interrupts.py): the flows whose confirmation card
    # pauses the run (interrupt) this turn - set by main.py from the INTERRUPT_*
    # flags - and the flow a reply to its card is going back to.
    interrupt_flows: Optional[list]
    resumed_flow: Optional[str]
    # The regularization-cancel card waiting on a reply, when that flow pauses
    # (INTERRUPT_REG_CANCEL). Kept across messages in the saved graph state -
    # main.py's per-turn reset leaves it alone. Otherwise it lives in Redis.
    reg_cancel_pending: Optional[dict]
