"""Structural guards for the LangGraph wiring in services/hr_graph.py.

These exist because the sprint1-2 -> sprint-4 merge (2026-09-12) found three
failure modes that produce NO error, NO failing test and NO log line — the
graph simply routes differently, or a value quietly vanishes:

1. THE SHADOWING FORK. hr_graph.py once carried its own local
   `async def classify_node(...)`, a 700-line copy of the one in
   services/classify_node.py. Because the local def is bound AFTER the
   import, `graph.add_node("classify_node", classify_node)` wired the copy,
   and every intent the copy did not know about (all of the sprint-4
   manager routing) became unreachable while the code that implemented it
   sat in the module untouched. A re-paste of that fork — which has
   already happened twice in this repo's history — would do it again.

2. A KEY THAT IS NOT A CHANNEL. `StateGraph(HRState)` only carries the keys
   HRState declares. A node that returns any other key has that value
   dropped before the router sees it (`regularisation_blocked`), and a node
   annotated with a TypedDict missing a key reads it back as None no matter
   what an earlier node set (`is_manager`). Both happened while two
   hand-synced copies of HRState existed; there is now one, and these tests
   pin every key any node reads or returns to it.

3. A NODE FALLING OUT OF build_hr_graph. Ten nodes exist only on the
   sprint-4 side and two only on the sprint1-2 side; a bad conflict
   resolution can drop any of them and the graph still compiles.

Everything here is import-time / AST-level: no LLM, no erp-api, no Redis.
"""
import ast
import glob
import inspect
import os

import pytest

import schema.agent as schema_agent
import services.classify_node as classify_node_mod
import services.hr_graph as hr_graph

REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
HR_GRAPH_PY = os.path.join(REPO, "services", "hr_graph.py")
CLASSIFY_NODE_PY = os.path.join(REPO, "services", "classify_node.py")


def _module_ast(path):
    with open(path, encoding="utf-8") as fh:
        return ast.parse(fh.read())


def _top_level_defs(tree, name):
    return [n for n in tree.body
            if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == name]


def _top_level_classes(tree, name):
    return [n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == name]


# ─── 1. exactly one classify_node, and it is the one the graph runs ──────────

class TestClassifierIsNotShadowed:

    def test_hr_graph_classify_node_is_the_module_implementation(self):
        assert hr_graph.classify_node is classify_node_mod.classify_node, (
            "services.hr_graph.classify_node is not services.classify_node.classify_node. "
            "Something in hr_graph.py rebinds the name after the import — almost certainly a "
            "local `async def classify_node` pasted back in. The graph will run THAT copy and "
            "every intent it does not handle becomes unreachable with no error."
        )

    def test_hr_graph_defines_no_local_classify_node(self):
        tree = _module_ast(HR_GRAPH_PY)
        local = _top_level_defs(tree, "classify_node")
        assert not local, (
            f"hr_graph.py defines classify_node at line {local[0].lineno}. The classifier lives "
            f"in services/classify_node.py only; delete the local copy and port any behaviour it "
            f"alone has into the module."
        )

    def test_graph_wires_the_module_classifier(self):
        """`add_node("classify_node", X)` — X must resolve to the module function.
        Reads the call from the source so a future `classify_node_impl` alias or a
        lambda wrapper is caught too, not just a rebinding of the bare name."""
        tree = _module_ast(HR_GRAPH_PY)
        wired = []
        for n in ast.walk(tree):
            # graph.add_node("classify_node", X), or build_hr_graph's
            # _add_node(graph, "classify_node", X) (retry + fallback, 28 Oct).
            if (isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
                    and n.func.attr == "add_node" and n.args
                    and isinstance(n.args[0], ast.Constant) and n.args[0].value == "classify_node"):
                wired.append(ast.unparse(n.args[1]) if len(n.args) > 1 else None)
            if (isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == "_add_node"
                    and len(n.args) >= 3 and isinstance(n.args[1], ast.Constant)
                    and n.args[1].value == "classify_node"):
                wired.append(ast.unparse(n.args[2]))
        assert wired == ["classify_node"], f"unexpected classify_node wiring: {wired}"
        assert getattr(hr_graph, "classify_node") is classify_node_mod.classify_node

    def test_ported_sprint12_behaviour_is_in_the_live_classifier(self):
        """The four behaviours that lived ONLY in the deleted fork. If the module
        loses them the graph still compiles and every other test here passes,
        so they are pinned by name as calls/reads inside classify_node itself."""
        tree = _module_ast(CLASSIFY_NODE_PY)
        fn = _top_level_defs(tree, "classify_node")[0]
        called = set()
        read_keys = set()
        for n in ast.walk(fn):
            if isinstance(n, ast.Call):
                f = n.func
                called.add(f.attr if isinstance(f, ast.Attribute) else getattr(f, "id", None))
                if (isinstance(f, ast.Attribute) and f.attr == "get" and isinstance(f.value, ast.Name)
                        and f.value.id == "state" and n.args and isinstance(n.args[0], ast.Constant)):
                    read_keys.add(n.args[0].value)
        for name in ("detect_bare_verb_query", "resolve_bare_verb_clarification",
                     "set_last_resolved_date", "is_explicit_leave_action_instruction"):
            assert name in called, f"classify_node no longer calls {name}"
        assert "last_intent" in read_keys, "classify_node no longer reads state['last_intent']"
        assert "is_manager" in read_keys, "classify_node no longer reads state['is_manager'] (sprint-4 gating)"


# ─── 2. one HRState, and every key any node touches is declared on it ────────

class TestSingleStateSchema:

    def test_hr_graph_uses_the_schema_hrstate(self):
        assert hr_graph.HRState is schema_agent.HRState, (
            "hr_graph.HRState is not schema.agent.HRState — a second copy of the state "
            "TypedDict has been reintroduced. Two hand-synced copies produced the is_manager "
            "and regularisation_blocked bugs; there must be exactly one."
        )
        tree = _module_ast(HR_GRAPH_PY)
        assert not _top_level_classes(tree, "HRState"), "hr_graph.py defines a local class HRState"

    @staticmethod
    def _declared():
        return set(schema_agent.HRState.__annotations__)

    @staticmethod
    def _state_taking_functions():
        files = [f for f in glob.glob(os.path.join(REPO, "services", "*.py"))
                 if "hr_graphsprint2_3" not in f] + [os.path.join(REPO, "main.py")]
        for f in files:
            tree = _module_ast(f)
            for fn in ast.walk(tree):
                if (isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef))
                        and fn.args.args and fn.args.args[0].arg == "state"):
                    yield os.path.basename(f), fn

    @staticmethod
    def _own_body(fn):
        """Nodes of fn's body WITHOUT entering nested defs/lambdas/classes — a
        helper closure's own return dict is not the node's return."""
        stack = list(fn.body)
        while stack:
            n = stack.pop()
            # A nested def/lambda/class is skipped WHOLE — including when it is a
            # direct statement of fn.body, which is where a helper closure lives.
            if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
                continue
            yield n
            stack.extend(ast.iter_child_nodes(n))

    def test_every_state_key_read_by_a_node_is_declared(self):
        """`state.get("k")` / `state["k"]` for an undeclared k reads back None
        forever — the exact shape of the is_manager bug."""
        declared = self._declared()
        offenders = {}
        for fname, fn in self._state_taking_functions():
            for n in ast.walk(fn):  # closures share the enclosing `state`, so walk fully here
                key = None
                if (isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and n.func.attr == "get"
                        and isinstance(n.func.value, ast.Name) and n.func.value.id == "state"
                        and n.args and isinstance(n.args[0], ast.Constant) and isinstance(n.args[0].value, str)):
                    key = n.args[0].value
                elif (isinstance(n, ast.Subscript) and isinstance(n.value, ast.Name) and n.value.id == "state"
                        and isinstance(n.slice, ast.Constant) and isinstance(n.slice.value, str)):
                    key = n.slice.value
                if key is not None and key not in declared:
                    offenders.setdefault(key, set()).add(f"{fname}:{fn.name}")
        assert not offenders, (
            "state keys read but not declared on schema.agent.HRState (they will always be None): "
            f"{ {k: sorted(v) for k, v in offenders.items()} }"
        )

    def test_every_key_a_node_returns_is_a_channel(self):
        """A key returned by a *_node that HRState does not declare is dropped by
        LangGraph before any router runs — the exact shape of the
        regularisation_blocked bug."""
        declared = self._declared()
        offenders = {}
        for fname, fn in self._state_taking_functions():
            if not fn.name.endswith("_node"):
                continue
            for n in self._own_body(fn):
                if isinstance(n, ast.Return) and isinstance(n.value, ast.Dict):
                    for k in n.value.keys:
                        if isinstance(k, ast.Constant) and isinstance(k.value, str) and k.value not in declared:
                            offenders.setdefault(k.value, set()).add(f"{fname}:{fn.name}")
        assert not offenders, (
            "keys returned by graph nodes but not declared on schema.agent.HRState "
            f"(LangGraph silently drops them): { {k: sorted(v) for k, v in offenders.items()} }"
        )


# ─── 3. the graph has exactly the nodes both branches contributed ────────────

EXPECTED_NODES = frozenset({
    # shared
    "ownership_guard_node", "classify_node", "hr_response_node", "policy_rag_node", "non_hr_node",
    # the safety checks, ahead of classification (Phase 3, 29 Oct)
    "safety_node",
    # a paused regularization-cancel card waiting on its reply (Phase 5, 29 Oct)
    "regularisation_cancel_wait",
    "leave_action_node", "leave_eligibility_node", "attendance_node",
    "attendance_explain_node", "punch_details_node", "regularisation_node",
    # sprint1-2 only
    "clarify_node", "regularisation_eligibility_node",
    # sprint-4 only
    "manager_gate_node", "shift_query_node", "leave_request_node",
    "attendance_explanation_node", "leave_approval_node", "regularisation_approval_node",
    "complex_manager_task_node", "team_leave_query_node", "team_attendance_summary_node",
    "team_members_node",
    "reporting_manager_node",
    # The EMPLOYEE's own regularization requests, read-only. Separate from
    # regularisation_approval_node (the manager queue, different scope and
    # erp-api route) and from regularisation_node (which CREATES a request).
    "my_regularisation_view_node",
    "regularisation_cancel_node",
    # WRITING a policy, as opposed to policy_rag_node's reading of the
    # uploaded ones. Deliberately its own node and not a branch inside that
    # one: the two have opposite contracts — the documents are the authority
    # for what the company's policy IS, and a draft is not a claim about this
    # company at all.
    "policy_draft_node",
    # The general-purpose (non-HR) lane. Reached only from the LAST branch of
    # _route_after_classify, after every HR intent and every mid-flow gate has
    # declined the turn — so it adds a destination without changing any path
    # above it. Its own prompt, no web search, buffered so the answer can be
    # moderated before it reaches the screen.
    "general_chat_node",
    # policy_rag_node (race-api's POST /v1/rag/query retrieval step for
    # leave_policy questions, always handing off to hr_response_node) is
    # listed under "shared" above — both branches now carry it.
})


class TestGraphNodeSet:

    def test_build_hr_graph_wires_exactly_the_expected_nodes(self):
        graph = hr_graph.build_hr_graph()
        got = {n for n in graph.nodes if not n.startswith("__")}
        missing = EXPECTED_NODES - got
        extra = got - EXPECTED_NODES
        assert not missing, (
            f"nodes missing from build_hr_graph: {sorted(missing)} — a conflict resolution or "
            f"refactor dropped them; the graph still compiles, so nothing else will notice."
        )
        assert not extra, (
            f"new nodes not in EXPECTED_NODES: {sorted(extra)} — if intentional, add them here "
            f"so the next merge cannot silently lose them."
        )


# ─── 4. state-writing intents are never served from the query cache ──────────

class TestStatefulIntentsAreNotCached:

    def test_intents_whose_fast_path_writes_redis_are_excluded_from_the_cache(self):
        """main._STATEFUL_QUERY_INTENTS is keyed on company_id + query text with
        no caller identity. An intent whose classify_node fast-path WRITES a
        redis state before answering must be in it: a cache hit would replay
        the card while recording nothing for the reply to resolve against."""
        from main import _STATEFUL_QUERY_INTENTS
        writes_state_before_answering = {
            "clarify_needed",        # bare_verb_clarify_state.set_state
            "leave_type_clarify",    # leave_type_clarify_state.set_state
            "apply_leave", "cancel_leave", "regularisation",   # slot / cancel flows
        }
        missing = writes_state_before_answering - set(_STATEFUL_QUERY_INTENTS)
        assert not missing, f"state-writing intents missing from _STATEFUL_QUERY_INTENTS: {sorted(missing)}"

    def test_caller_scoped_intents_are_excluded_from_the_cache(self):
        from main import _STATEFUL_QUERY_INTENTS
        caller_scoped = {"punch_details", "attendance_explain", "leave_balance", "leave_status",
                         "manager_leave_approval", "manager_leave_request_lookup",
                         "manager_attendance_explanation", "HRMS_TEAM_LEAVE_QUERY",
                         "HRMS_TEAM_ATTENDANCE_QUERY", "shift_query"}
        missing = caller_scoped - set(_STATEFUL_QUERY_INTENTS)
        assert not missing, f"caller-scoped intents missing from _STATEFUL_QUERY_INTENTS: {sorted(missing)}"
