"""
Regression tests for short-fragment intent routing in classify_node.

Background: a "Fast-path 2" shortcut used to assign intent='follow_up' to any
query of <= 4 words that arrived with HR context, and return BEFORE either
classifier ran. follow_up routes to hr_response_node (generic LLM chat), so a
short but actionable request never reached the node that does the real work.

Three live bugs came from it:
  "apply for tomorrow"       -> the LLM drafted a leave-request email; nothing
                                was ever submitted to erp-api, but the user was
                                told "sure, you can apply for tomorrow".
  "meri saari leaves dikhao" -> generic chat. Every keyword list in
                                nlp_service is English-only, so Hinglish scores
                                nothing and looked like a conversational
                                fragment.
  "meri leave balance batao" -> follow_up despite fast_classify returning
                                leave_balance at confidence 1.0 — the fast path
                                returned before consulting it.

The shortcut was removed. These tests pin the behaviour that replaced it: a
short query with HR context must reach the LLM classifier, and whatever the
classifier decides must be what routes.
"""

from contextlib import contextmanager

import pytest
from unittest.mock import patch, AsyncMock, MagicMock

import services.hr_graph as hr_graph
import services.classify_node as classify_node_mod


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

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

    def intent_events(self):
        return [e for e in self.events if e.get("type") == "intent"]


HR_CONTEXT = [
    {"role": "user", "content": "what is my leave balance"},
    {"role": "assistant", "content": "You have 14 Casual Leave day(s) remaining out of 24."},
]


def _state(query, context=None):
    return {
        "query": query,
        "context": context if context is not None else HR_CONTEXT,
        "bearer_token": "t", "company_id": "3735",
        "conversation_id": "conv-1", "usage_events": [],
    }


@contextmanager
def _mocks(returned_intent, slots=None):
    """classify_node's two concurrent LLM calls, plus a slot store that is
    empty by default so the mid-flow fast path (Fast-path 0.5) stays out of
    the way. Yields the mock handles so tests can assert on call counts —
    patch.multiple only returns a dict for DEFAULT sentinels, not for
    explicitly supplied mocks."""
    clf = AsyncMock(return_value=(returned_intent, None, False))
    mod = AsyncMock(return_value={"flagged": False})
    slot_store = MagicMock(get_slots=MagicMock(return_value=slots))
    with patch.multiple(classify_node_mod, classify_intent_structured=clf,
                        _check_moderation=mod, leave_slot_service=slot_store):
        yield {"classify_intent_structured": clf, "_check_moderation": mod,
               "leave_slot_service": slot_store}


class TestShortFragmentsReachTheClassifier:
    @pytest.mark.parametrize("query,classified_as", [
        ("apply for tomorrow", "apply_leave"),
        ("meri saari leaves dikhao", "leave_balance"),
        ("meri leave balance batao", "leave_balance"),
        ("chutti kitni bachi hai", "leave_balance"),
        ("cancel it", "apply_leave"),
        ("and earned leave?", "leave_balance"),
    ])
    async def test_short_actionable_query_is_classified_not_shortcut(self, query, classified_as):
        """<= 4 words + HR context must NOT be forced to follow_up."""
        writer = FakeWriter()
        with _mocks(classified_as) as m:
            result = await hr_graph.classify_node(_state(query), writer)

        assert m["classify_intent_structured"].called, \
            f"{query!r} never reached the classifier — the fast path is back"
        assert result["intent"] == classified_as
        assert result["intent"] != "follow_up"

    async def test_short_eligibility_query_reaches_its_node(self):
        """HEL-280 regression: eligibility answers must be ERP-backed, so a
        short eligibility follow-up must never be answered by generic chat."""
        writer = FakeWriter()
        with _mocks("leave_eligibility"):
            result = await hr_graph.classify_node(_state("am i eligible?"), writer)

        assert result["intent"] == "leave_eligibility"
        assert hr_graph._route_after_classify(result) == "leave_eligibility_node"

    @pytest.mark.parametrize("query,classified_as,expected_node", [
        ("apply for tomorrow", "apply_leave", "leave_action_node"),
        ("meri saari leaves dikhao", "leave_balance", "leave_action_node"),
        ("am i eligible?", "leave_eligibility", "leave_eligibility_node"),
    ])
    async def test_classified_intent_routes_to_the_real_node(self, query, classified_as, expected_node):
        """End of the chain: the intent the classifier picked must be the one
        the router acts on."""
        writer = FakeWriter()
        with _mocks(classified_as):
            result = await hr_graph.classify_node(_state(query), writer)
        assert hr_graph._route_after_classify(result) == expected_node


class TestGenuineFollowUpsStillWork:
    async def test_non_hr_short_fragment_still_becomes_follow_up(self):
        """The second follow_up path (LLM says non_hr + HR context + <= 5
        words) is deliberately kept — it catches genuine continuations like
        'what about India?' that are not actionable."""
        writer = FakeWriter()
        with _mocks("non_hr"):
            result = await hr_graph.classify_node(_state("what about India?"), writer)

        assert result["intent"] == "follow_up"
        assert result["is_hr"] is True
        assert hr_graph._route_after_classify(result) == "hr_response_node"

    async def test_no_hr_context_leaves_non_hr_alone(self):
        """Without HR context there is nothing to continue, so a non_hr answer
        must stay non_hr rather than being rescued into follow_up."""
        writer = FakeWriter()
        with _mocks("non_hr"):
            result = await hr_graph.classify_node(_state("what about India?", context=[]), writer)

        assert result["intent"] == "non_hr"
        assert result["is_hr"] is False
        assert hr_graph._route_after_classify(result) == "non_hr_node"

# Removed (2026-09-01): TestMidFlowStillTakesPrecedence::
# test_in_progress_apply_flow_still_short_circuits asserted a bare date
# reply must bypass classify_intent_structured entirely when
# slots["step"] == "awaiting_dates" — but that step value is never
# produced anywhere in the real implementation (leave_action_service.py
# only ever sets "collecting"/"awaiting_confirmation"; which slot is being
# awaited is inferred structurally from which fields are still None, see
# classify_node._describe_awaited_leave_slot). Its expected behavior also
# contradicted TestClassifyNodeMidFlowInterruption::
# test_fallback_prompt_describes_awaited_dates_slot (test_leave_action.py),
# which deliberately keeps dates going through the LLM fallback — unlike
# a reason reply, a date reply still needs classify_intent_structured so
# the awaited-slot hint reaches the prompt. Attempting to make the
# "awaiting_dates" premise real broke that already-correct, already-tested
# behavior, so the test was removed rather than the design it contradicted.
