"""
Multi-turn, same-thread conversation tests for the HR AI Assistant.

Turn 1 asks a leave-apply query; turn 2, in the SAME conversation, asks a
different HR-related question. hr_graph's StateGraph is compiled with no
checkpointer (see hr_graph.py's build_graph — StateGraph(HRState).compile()),
so nothing here is "free" continuity — every cross-turn effect exercised
below comes from one of two real, independently-existing mechanisms:

  1. classify_node's has_hr_context override (hr_graph.py:74-112, 435-437) —
     the caller (main.py's /hr-assist-stream) threads recent chat history
     into HRState["context"] on every call; a short turn-2 follow-up that an
     isolated classifier call would mark non_hr gets corrected to
     "follow_up" (still HR) purely because turn 1's content is present in
     that list.

  2. leave_slot_service's mid-flow interruption path (classify_node's
     Fast-path 0.5, hr_graph.py:255-370) — an unrelated-but-HR question
     asked while a leave application is still being collected gets answered
     directly, without disturbing the in-progress slots, so the original
     thread can resume afterward.

Same mocking conventions as test_leave_action.py (FakeWriter, FakeSlotStore,
base_state, mock_extraction, not_manager_context) — real node logic, fake
Redis/erp-api/LLM underneath.
"""

import services.hr_graph as hr_graph
import services.classify_node as classify_node_mod
import services.leave_action_service as leave_action_service
from tests.test_leave_action import (
    FakeWriter,
    FakeSlotStore,
    base_state,
    mock_extraction,
    not_manager_context,
    _no_conflicting_leaves,
)


async def _balance_ok(token, **kwargs):
    return {"http_status": 200, "body": {"success": True, "data": {
        "leave_quota": {"casual_leave": {"total": "20", "remaining": "20"}},
    }}}


class TestContextRescuesShortFollowup:
    """classify_node only, no apply-leave slots in progress — the general
    classification path (hr_graph.py:372-456), not the mid-flow one."""

    async def test_turn2_short_followup_rescued_by_turn1_hr_context(self, monkeypatch):
        # Turn 1: a real leave-apply query.
        async def _classify_turn1(prompt, valid_labels, fallback_label="general_hr"):
            return "apply_leave", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _classify_turn1)

        writer1 = FakeWriter()
        turn1 = await hr_graph.classify_node(
            base_state("I want to apply for leave next week", intent="general"), writer1,
        )
        assert turn1["intent"] == "apply_leave"
        assert turn1["is_hr"] is True

        # Turn 2, same conversation: a short 5-word HR-adjacent follow-up.
        # The classifier is deliberately mocked to STILL return non_hr in
        # isolation here — exactly what a paraphrase outside the intent
        # prompt's closed keyword list would do — so that the assertion
        # below actually proves the override engages, not that the
        # classifier happened to get it right on its own.
        async def _classify_turn2(prompt, valid_labels, fallback_label="general_hr"):
            return "non_hr", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _classify_turn2)

        state2 = {
            "query": "what about sick leave instead?",
            "context": [
                {"role": "user", "content": "I want to apply for leave next week"},
                {"role": "assistant", "content": "Sure — what type of leave would you like to apply for?"},
            ],
            "intent": "general", "usage_events": [],
            "bearer_token": "caller-token", "company_id": 1, "conversation_id": "conv-1",
        }
        writer2 = FakeWriter()
        turn2 = await hr_graph.classify_node(state2, writer2)

        # hr_graph.py:435-437 — non_hr + has_hr_context + short fragment
        # (<=5 words) + no non-HR trigger word -> overridden to "follow_up".
        assert turn2["intent"] == "follow_up"
        assert turn2["is_hr"] is True

    async def test_same_query_with_no_prior_context_is_not_rescued(self, monkeypatch):
        """Control for the test above: identical turn-2 query and classifier
        mock, but an EMPTY context — proves the override really is driven by
        turn 1's content being present, not some other property of the
        query itself."""
        async def _classify(prompt, valid_labels, fallback_label="general_hr"):
            return "non_hr", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _classify)

        state = {
            "query": "what about sick leave instead?",
            "context": [],
            "intent": "general", "usage_events": [],
            "bearer_token": "caller-token", "company_id": 1, "conversation_id": "conv-2",
        }
        writer = FakeWriter()
        result = await hr_graph.classify_node(state, writer)

        assert result["intent"] == "non_hr"
        assert result["is_hr"] is False


class TestApplyLeaveThenHRQuestionSameThread:
    """A real in-progress apply-leave flow (via leave_action_node, same
    pattern as test_leave_action.py) interrupted by an unrelated HR
    question, then resumed — all within one conversation_id."""

    async def test_policy_question_interrupts_without_losing_in_progress_application(
        self, monkeypatch,
    ):
        fake_slots = FakeSlotStore()
        monkeypatch.setattr(classify_node_mod, "leave_slot_service", fake_slots)
        # Turn 1 calls hr_graph.leave_action_node directly, which persists
        # slots via leave_action_service.py's OWN leave_slot_service import
        # — a separate module-level binding from classify_node's, unaffected
        # by the patch above. Without this, turn 1's slots were never
        # actually captured by fake_slots at all, even though the response
        # text (the "what type of leave?" ask) looked correct.
        monkeypatch.setattr(leave_action_service, "leave_slot_service", fake_slots)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance_ok)
        # "next week" is now resolved deterministically the moment it's
        # typed (see date_resolver.resolve_next_calendar_week_phrase), so
        # turn 1 already has both dates known — which means the existing
        # "check for a date conflict the moment dates are known" branch
        # (hr_graph.py, before the leave_type ask) now runs in turn 1 too,
        # same as any other apply-branch test that reaches that point.
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _no_conflicting_leaves)

        async def _no_holidays(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "year": 2026, "department": "Shopfloor Team",
                "total_holidays": 0, "holidays": [],
            }}}
        # Same date-known-in-turn-1 branch above also fetches the holiday
        # calendar (see leave_action_service._fetch_holidays_or_none) —
        # unmocked, this made a REAL network call to erp-api's live host,
        # which then failed 401 and slowed the test down by several
        # seconds for nothing.
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_holidays", _no_holidays, raising=False)

        # Turn 1: "I want to apply for leave next week" — starts the flow,
        # nothing extracted yet, asks which type of leave.
        mock_extraction(monkeypatch, {})
        writer1 = FakeWriter()
        turn1 = await hr_graph.leave_action_node(
            base_state("I want to apply for leave next week"), writer1,
        )
        # "next week" is a range, so the flow now pins the exact days first
        # ("Which exact dates would you like to take off?") and asks the type
        # after - either way it is the apply flow asking, with a draft saved.
        assert ("type of leave" in turn1["response_text"].lower()
                or "which exact dates" in turn1["response_text"].lower())
        slots_after_turn1 = fake_slots.get_slots(1, "conv-1")
        assert slots_after_turn1 is not None

        # Turn 2, SAME conversation_id — a genuinely different HR question,
        # not a leave-type reply. Mocked the same way test_leave_action.py's
        # own mid-flow tests mock the ambiguous-fallback classifier (fast_classify
        # alone doesn't confidently score this phrasing — see module docstring).
        async def _classify_turn2(prompt, valid_labels, fallback_label="general_hr"):
            return "policy", None, False   # renamed from leave_policy (85ff98d)
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _classify_turn2)

        writer2 = FakeWriter()
        turn2 = await hr_graph.classify_node(
            base_state("What's the policy on carrying forward unused leave?", intent="general"),
            writer2,
        )
        assert turn2["intent"] == "policy"
        assert turn2["is_hr"] is True

        # The interrupted application must be exactly where turn 1 left it —
        # this is what lets turn 3 resume the same thread.
        assert fake_slots.get_slots(1, "conv-1") == slots_after_turn1

        # Turn 3: resume the original application - unaffected by the
        # digression in turn 2. "next week" is a range, so the flow still needs
        # the exact days (turn 1 asked for them), and now that the type is
        # given it asks for those dates next.
        mock_extraction(monkeypatch, {"leave_type": "casual_leave"})
        writer3 = FakeWriter()
        turn3 = await hr_graph.leave_action_node(base_state("casual leave"), writer3)

        assert fake_slots.get_slots(1, "conv-1")["leave_type"] == "casual_leave"
        assert "dates" in turn3["response_text"].lower()
