"""
Tests for FR-07.5 (Routing Complex Manager Tasks):
  - services/hr_graph.py::complex_manager_task_node (role guard, Navigation
    Card emission, correct deep-link per category, no execution)
  - services/hr_graph.py::_route_after_classify (routes the four complex
    manager intents to complex_manager_task_node)

complex_manager_task_node is exercised directly (not through the HTTP layer)
with a fake StreamWriter, same pattern as test_leave_action.py.
"""

import pytest
from unittest.mock import MagicMock

import services.hr_graph as hr_graph
from services.complex_manager_router import COMPLEX_MANAGER_INTENTS


class FakeWriter:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)

    def of_type(self, etype):
        return [e for e in self.events if e.get("type") == etype]


def base_state(intent: str) -> dict:
    return {
        "query": "irrelevant for this node", "intent": intent, "usage_events": [],
        "bearer_token": "caller-token", "company_id": 1, "conversation_id": "conv-1",
    }


def manager_context(user_id=42):
    async def _f(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {"is_manager": True, "user_id": user_id}}}
    return _f


def not_manager_context():
    async def _f(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {"is_manager": False}}}
    return _f


EXPECTED = {
    "large_team_review": ("Team Review", "/team/review", "Open Team Review Page"),
    "bulk_approvals": ("Bulk Approvals", "/payroll/approvals/bulk", "Open Bulk Approvals Page"),
    "shift_planning": ("Shift Planning", "/shifts/planner", "Open Shift Planning Page"),
    "comparative_reporting": ("Comparative Reports", "/reports/comparative", "Open Comparative Reports Page"),
}


# ═════════════════════════════════════════════════════════════════════════════
# Role guard
# ═════════════════════════════════════════════════════════════════════════════

class TestComplexManagerTaskRoleGate:

    async def test_non_manager_gets_no_navigation_card(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        writer = FakeWriter()
        result = await hr_graph.complex_manager_task_node(base_state("bulk_approvals"), writer)

        assert writer.of_type("navigation_card") == []
        done = writer.of_type("done")
        assert len(done) == 1
        assert "only available to managers" in result["response_text"]

    async def test_erp_api_timeout_returns_graceful_message_no_card(self, monkeypatch):
        async def _timeout(token, **kwargs):
            raise hr_graph.erp_client.ErpApiTimeout("timed out")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _timeout)

        writer = FakeWriter()
        result = await hr_graph.complex_manager_task_node(base_state("shift_planning"), writer)

        assert writer.of_type("navigation_card") == []
        assert "try again" in result["response_text"]

    async def test_erp_api_unavailable_returns_graceful_message_no_card(self, monkeypatch):
        """What fails here is the ROLE LOOKUP, not this feature, and the copy
        now says so: "I couldn't verify your access in time" rather than "I'm
        unable to reach the HR system right now". The old sentence described
        an outage of the capability and invited a retry, for a caller whose
        permission simply could not be established — see
        tests/test_team_refusal_vs_outage.py for the reported symptom."""
        async def _unavailable(token, **kwargs):
            raise hr_graph.erp_client.ErpApiUnavailable("down")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _unavailable)

        writer = FakeWriter()
        result = await hr_graph.complex_manager_task_node(base_state("shift_planning"), writer)

        assert writer.of_type("navigation_card") == []
        assert "couldn't verify your access" in result["response_text"]
        assert "unable to reach" not in result["response_text"]


# ═════════════════════════════════════════════════════════════════════════════
# AC1-AC5 — each category routes to its correct Navigation Card
# ═════════════════════════════════════════════════════════════════════════════

class TestComplexManagerTaskNavigationCards:

    @pytest.mark.parametrize("intent", list(EXPECTED.keys()))
    async def test_manager_gets_correct_navigation_card(self, monkeypatch, intent):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        writer = FakeWriter()
        result = await hr_graph.complex_manager_task_node(base_state(intent), writer)

        expected_title, expected_path, expected_label = EXPECTED[intent]

        cards = writer.of_type("navigation_card")
        assert len(cards) == 1
        nav = cards[0]["data"]
        assert nav["category"] == intent
        assert nav["title"] == expected_title
        assert nav["button"]["path"] == expected_path
        assert nav["button"]["label"] == expected_label

        done = writer.of_type("done")
        assert len(done) == 1
        assert done[0]["intent"] == intent
        assert done[0]["data"]["navigation"]["button"]["path"] == expected_path
        assert result["response_text"] == nav["message"]

    async def test_deep_link_targets_are_never_substituted(self, monkeypatch):
        """AC5 — each category maps to exactly its own target, not another's."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        seen_paths = set()
        for intent in EXPECTED:
            writer = FakeWriter()
            await hr_graph.complex_manager_task_node(base_state(intent), writer)
            path = writer.of_type("navigation_card")[0]["data"]["button"]["path"]
            assert path not in seen_paths
            seen_paths.add(path)

    async def test_no_underlying_operation_is_ever_called(self, monkeypatch):
        """The node must only route — it must never call a bulk-approval,
        shift-planning, team-review, or report-generation API itself."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        # get_pending_leaves alongside get_leave_status: erp_client split the
        # two apart, and the pending-leaves call is the one real code makes —
        # guarding only the old name would leave the actual call unguarded.
        for forbidden in ("get_leave_balance", "apply_leave", "get_leave_status",
                          "get_pending_leaves"):
            monkeypatch.setattr(
                hr_graph.erp_client, forbidden,
                MagicMock(side_effect=AssertionError(f"{forbidden} must never be called by complex_manager_task_node")),
            )

        writer = FakeWriter()
        await hr_graph.complex_manager_task_node(base_state("bulk_approvals"), writer)
        # No assertion error raised above => none of the forbidden calls fired.


# ═════════════════════════════════════════════════════════════════════════════
# _route_after_classify — the four intents route to complex_manager_task_node
# ═════════════════════════════════════════════════════════════════════════════

class TestRouteAfterClassify:

    @pytest.mark.parametrize("intent", list(COMPLEX_MANAGER_INTENTS))
    def test_complex_manager_intents_route_to_the_new_node(self, intent):
        state = {"intent": intent, "is_hr": True, "error": None}
        assert hr_graph._route_after_classify(state) == "complex_manager_task_node"

    def test_ordinary_hr_intent_still_routes_to_hr_response_node(self):
        # general_hr is document-backed now (checked against the policy
        # documents first - see _DOCUMENT_BACKED_INTENTS), so the "ordinary"
        # case is a label with no document behind it.
        state = {"intent": "follow_up", "is_hr": True, "error": None}
        assert hr_graph._route_after_classify(state) == "hr_response_node"

    def test_general_hr_checks_the_policy_documents_first(self):
        state = {"intent": "general_hr", "is_hr": True, "error": None}
        assert hr_graph._route_after_classify(state) == "policy_rag_node"

    def test_leave_policy_routes_through_policy_rag_node(self):
        # "leave_policy" was renamed "policy" (85ff98d, rag rework).
        state = {"intent": "policy", "is_hr": True, "error": None}
        assert hr_graph._route_after_classify(state) == "policy_rag_node"

    def test_error_state_still_short_circuits_to_end(self):
        from langgraph.graph import END
        state = {"intent": "bulk_approvals", "is_hr": True, "error": "flagged"}
        assert hr_graph._route_after_classify(state) == END


# ═════════════════════════════════════════════════════════════════════════════
# _build_intent_prompt — regression guard: the LLM prompt must keep naming all
# four categories, or classify_node would silently stop recognizing them.
# ═════════════════════════════════════════════════════════════════════════════

class TestIntentPromptRecognizesComplexManagerCategories:

    def test_prompt_names_every_complex_manager_intent_label(self):
        prompt = hr_graph._build_intent_prompt("some query", [], False)
        # _build_intent_prompt returns a chat-messages list (system + recent
        # turns + the query), not the single f-string sprint-4's own copy of
        # this function returned. Flattened here rather than indexed so the
        # guard keeps working whichever message carries the taxonomy — the
        # string form would have made `intent in prompt` a list-membership
        # check that can never pass.
        prompt_text = (
            "".join(m.get("content", "") for m in prompt)
            if isinstance(prompt, list) else str(prompt)
        )
        for intent in COMPLEX_MANAGER_INTENTS:
            assert intent in prompt_text, f"{intent} missing from intent classification prompt"
