"""Regression tests for the bare-date follow-up continuation in
services/hr_graph.py's classify_node.

Confirmed live (2026-09-08): "punch in details for last month 4th
wednesday" answered correctly, then "4th Wednesday of August 2026" on the
very next turn came back as a plain calendar fact ("was August 26, 2026")
instead of that day's punch details. The classifier returned non_hr for the
bare fragment (it contains no HR word), classify_node's override rescued it
to "follow_up", and no branch of _route_after_classify claims that label —
so it fell through to the generic hr_response_node.
"""
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

import services.classify_node as classify_node_mod
import services.hr_graph as hr_graph
import services.leave_slot_service as leave_slot_service
from services.hr_graph import _context_has_hr_signal, _route_after_classify


# A prior punch turn whose answer carries NO shift line — the weakest form
# of HR context a punch conversation can leave behind (see the punch
# vocabulary added to _HR_CONTEXT_SIGNALS).
PUNCH_CONTEXT = [
    {"role": "user", "content": "punch in details for last month 4th wednesday"},
    {"role": "assistant", "content": "No punch records found for 2026-08-26."},
]


# A conversation id unique to this module. leave_slot_service keeps
# apply-leave slots in process, keyed by (company_id, conversation_id), and
# classify_node has a mid-flow branch that answers a pending leave
# conversation BEFORE the follow-up override is ever reached. Sharing a
# generic id like "conv-1" with other test modules meant whichever of them
# ran first left an in-progress leave application behind, and every test
# here was silently exercising that branch instead of the one it names.
CONVERSATION_ID = "bare-date-followup-routing-tests"


@pytest.fixture(autouse=True)
def _no_leftover_leave_flow():
    """Belt and braces alongside the unique id above — guarantees a clean
    slot state regardless of what any other module did."""
    leave_slot_service.clear_slots(1, CONVERSATION_ID)
    yield
    leave_slot_service.clear_slots(1, CONVERSATION_ID)


async def _classify(query: str, last_intent, context=PUNCH_CONTEXT, detected="non_hr"):
    """Runs the real classify_node with the intent classifier and the
    moderation call stubbed — the LLM returning non_hr for a bare date
    fragment is the live behavior being compensated for, so it's pinned
    here rather than mocked away as an edge case."""
    state = {
        "query": query, "context": context, "last_intent": last_intent,
        "bearer_token": "jwt", "company_id": 1, "conversation_id": CONVERSATION_ID,
    }
    # Patched on classify_node, NOT hr_graph. hr_graph.classify_node IS
    # classify_node.classify_node, so it reads that module's globals -
    # patches on hr_graph never reached it, the real DeepSeek call ran, and
    # every test here failed on a 401 with intent "unclear" rather than on
    # anything to do with bare-date continuation.
    #
    # _resolve_shift_route is stubbed for the same reason: left real it is
    # another live call on every one of these turns.
    with patch.object(classify_node_mod, "classify_intent_structured",
                      new=AsyncMock(return_value=(detected, None, False))), \
         patch.object(classify_node_mod, "_check_moderation",
                      new=AsyncMock(return_value={"flagged": False})), \
         patch.object(classify_node_mod, "_resolve_shift_route",
                      new=AsyncMock(return_value=(None, 0.0, None))):
        out = await hr_graph.classify_node(state, MagicMock())
    return out, _route_after_classify({**state, **out})


class TestBareDateFollowUpContinuesThePreviousIntent:

    @pytest.mark.asyncio
    async def test_the_reported_case_reaches_punch_details_not_the_generic_responder(self):
        """The exact live repro. Before the fix this returned intent
        "follow_up" and routed to hr_response_node."""
        out, route = await _classify("4th Wednesday of August 2026", "punch_details")
        assert out["intent"] == "punch_details"
        assert route == "punch_details_node"

    @pytest.mark.asyncio
    @pytest.mark.parametrize("fragment", [
        "4th Wednesday of August 2026",
        "26 august",
        "last friday",
        "yesterday",
        "2nd wednesday of august",
    ])
    async def test_every_bare_date_shape_continues_punch_details(self, fragment):
        """"last friday" matters specifically: date_resolver (the leave
        side's) does NOT recognize it, so has_date_expression is False —
        it is caught only because _is_bare_date_fragment also consults
        date_query_resolver, the attendance family's own resolver."""
        out, route = await _classify(fragment, "punch_details")
        assert out["intent"] == "punch_details", fragment
        assert route == "punch_details_node", fragment

    @pytest.mark.asyncio
    @pytest.mark.parametrize("previous,expected_node", [
        ("attendance", "attendance_node"),
        ("attendance_explain", "attendance_explain_node"),
        ("regularisation", "regularisation_node"),
    ])
    async def test_the_other_date_driven_intents_continue_too(self, previous, expected_node):
        out, route = await _classify("4th Wednesday of August 2026", previous)
        assert out["intent"] == previous
        assert route == expected_node


_DATE_REFINABLE = classify_node_mod._DATE_REFINABLE_INTENTS


class TestContinuationIsNotAppliedWhereItWouldDoHarm:

    # These three all assert the same invariant: the fragment must NOT be
    # continued as the previous intent. They used to spell the alternative
    # as "follow_up", which is the label the override applied to everything
    # it could not continue - and that label routes to generic chat, which
    # is precisely the leak fixed in _looks_like_an_hr_continuation. The
    # not-continued outcome is now "non_hr", so the redirect answers instead
    # of the chat model. The invariant each test exists for is unchanged and
    # is asserted first.

    @pytest.mark.asyncio
    async def test_a_date_after_a_leave_intent_is_never_continued(self):
        """A date arriving mid-apply-leave is a SLOT REPLY, owned by
        leave_slot_service's own mid-flow handling. Re-classifying it as
        apply_leave here would pre-empt that flow, so the leave intents are
        deliberately outside _DATE_REFINABLE_INTENTS."""
        out, _ = await _classify("4th Wednesday of August 2026", "apply_leave")
        assert out["intent"] != "apply_leave"
        # A bare date carries no HR word and no elliptical opener, so with
        # no continuable intent behind it there is nothing to make it HR.
        assert out["intent"] == "non_hr"

    @pytest.mark.asyncio
    async def test_first_turn_of_a_conversation_has_nothing_to_continue(self):
        out, _ = await _classify("4th Wednesday of August 2026", None)
        assert out["intent"] not in _DATE_REFINABLE
        assert out["intent"] == "non_hr"

    @pytest.mark.asyncio
    async def test_a_short_fragment_that_is_not_a_date_stays_uncontinued(self):
        """The continuation is keyed on the fragment being a DATE — a
        generic short reply must not inherit the punch lookup.

        Hypothetical input: fast_classify scores "how are you" as `greeting`
        at 1.0 and the classifier prompt says outright that greetings are
        NEVER non_hr, so the mocked non_hr verdict here is not something the
        real classifier produces. What it pins is the shape - an unrelated
        short reply does not become a punch query.
        """
        out, route = await _classify("how are you", "punch_details")
        assert out["intent"] != "punch_details"
        assert route != "punch_details_node"

    @pytest.mark.asyncio
    async def test_an_off_topic_trigger_word_still_wins(self):
        """has_non_hr_trigger short-circuits the override entirely — a
        genuine topic change is not swallowed by conversation context."""
        out, route = await _classify("what is the weather", "punch_details")
        assert out["intent"] == "non_hr"
        assert route == "non_hr_node"

    @pytest.mark.asyncio
    async def test_a_confidently_classified_query_is_untouched(self):
        """The override only ever fires on non_hr. A real classification
        must pass through unchanged."""
        out, route = await _classify("show my leave balance", "punch_details", detected="leave_balance")
        assert out["intent"] == "leave_balance"


class TestPunchConversationsRegisterAsHrContext:
    """has_hr_context gates the whole override. A punch conversation used
    to satisfy it only by accident — the answer happened to contain
    "shift" ("Shift: General-Shift (09:00:00-18:30:00)"), and
    punch_details emits that line only when erp-api returns a shift."""

    def test_a_punch_answer_without_a_shift_line_still_counts_as_hr_context(self):
        assert _context_has_hr_signal([
            {"role": "assistant", "content": "No punch records found for 2026-08-18."},
        ]) is True

    def test_a_punch_question_counts_on_its_own(self):
        assert _context_has_hr_signal([
            {"role": "user", "content": "what time did I check in"},
        ]) is True

    def test_work_hours_phrasing_counts(self):
        assert _context_has_hr_signal([
            {"role": "assistant", "content": "Total work hours: 08:44."},
        ]) is True

    def test_genuinely_unrelated_chat_still_does_not(self):
        assert _context_has_hr_signal([
            {"role": "user", "content": "what is the capital of France"},
            {"role": "assistant", "content": "Paris."},
        ]) is False


class TestFollowUpIsExplicitlyRouted:
    """"follow_up" reaching hr_response_node is intended — but it must be
    stated, not left to the fall-through, because being an unroutable
    label is exactly how it swallowed punch queries."""

    def test_follow_up_routes_to_the_generic_hr_responder(self):
        assert _route_after_classify({"intent": "follow_up", "is_hr": True, "error": None}) == "hr_response_node"

    def test_error_still_short_circuits(self):
        assert _route_after_classify({"intent": "follow_up", "is_hr": True, "error": "boom"}) is not None
