"""
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"),
        ("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"

    @pytest.mark.parametrize("query", ["cancel", "cancel it", "I want to cancel"])
    async def test_a_bare_cancel_asks_rather_than_reaching_the_classifier(self, query):
        """The one short fragment deliberately NOT sent to the classifier.

        "cancel it" names an action but not its object, and with no flow
        open there is nothing for "it" to refer to. Guessing costs more than
        asking — a wrong guess starts a slot-filling flow the employee then
        has to abandon — so the bare-verb fast path ends the turn on a
        clarify card (see bare_verb_config._BARE_VERB_CONFIGS).

        This is not the removed "Fast-path 2" coming back: that one swallowed
        ANY short query into generic LLM chat with no way out. This one fires
        only on a closed list of objectless verbs, only when no flow is open
        (every mid-flow branch above it gets first refusal), and it asks a
        question whose answer Fast-path 0.45 then resolves."""
        writer = FakeWriter()
        with _mocks("cancel_leave") as m:
            result = await hr_graph.classify_node(_state(query), writer)

        assert result["intent"] == "clarify_needed"
        assert result["clarify_message"] == "What would you like to cancel?"
        assert result["clarify_options"] == ["Leave request"]
        # No point spending an LLM call on a turn that ends in a question.
        assert not m["classify_intent_structured"].called

    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.


class TestCalendarTriviaIsNotAnHRFollowUp:
    """Reported: {"query": "today date"} in an HR conversation came back with
    "Today's date is **Monday, September 21, 2026**", intent "follow_up",
    across three LLM calls (11,814 tokens).

    Every condition of the short-fragment override was satisfied - the
    classifier said non_hr, the conversation had HR context, no non-HR
    trigger word was present, and two words is a short fragment - so the
    override relabelled it "follow_up". That label routes to
    hr_response_node, which hands the message to the chat model, and the
    model answered the question. non_hr_node's own prompt forbids exactly
    that ("Do NOT include ANY facts... about what they asked"); it just
    never got the turn.
    """

    @pytest.mark.parametrize("query", [
        "today date", "date today", "today's date", "todays date",
        "what is the date", "what's today's date", "current date",
        "what day is it", "current time",
    ])
    async def test_it_is_not_rescued_into_follow_up(self, query):
        writer = FakeWriter()
        with _mocks("non_hr"):
            result = await hr_graph.classify_node(_state(query), writer)

        assert result["intent"] != "follow_up"
        assert result["intent"] == "non_hr"

    async def test_it_routes_to_the_redirect_not_generic_chat(self):
        writer = FakeWriter()
        with _mocks("non_hr"):
            result = await hr_graph.classify_node(_state("today date"), writer)

        assert hr_graph._route_after_classify(result) == "non_hr_node"
        assert hr_graph._route_after_classify(result) != "hr_response_node"

    @pytest.mark.parametrize("query,classified_as", [
        # The rescue exists for these and must keep working: a bare date
        # fragment continuing the punch lookup before it, and an elliptical
        # follow-up to a leave answer.
        ("last wednesday", "punch_details"),
        ("and earned leave?", "leave_balance"),
    ])
    async def test_real_follow_ups_are_untouched(self, query, classified_as):
        writer = FakeWriter()
        with _mocks(classified_as):
            result = await hr_graph.classify_node(_state(query), writer)

        assert result["intent"] == classified_as

    @pytest.mark.parametrize("query", [
        "my joining date", "leave date", "punch time", "half day",
        "which day", "attendance for today",
    ])
    def test_hr_wording_that_mentions_a_date_is_not_trivia(self, query):
        """The detector is narrow on purpose - "date" and "time" appear all
        over real HR wording, so a possessive or any HR term disqualifies."""
        assert classify_node_mod._asks_a_calendar_fact(query) is False
