"""A bare employee name continues the individual-report question before it.

Live bug (conversation 00127b84):

    "Show Ayush Jio leave request"  -> manager_leave_request_lookup, card,
                                       10 rows fetched from erp-api
    "Ayush Jio"    (same thread)    -> general_hr

The second turn still produced a confident, well-formatted list of those ten
requests - because the general_hr fallback hands the turn to the chat model,
which reconstructed the answer by READING THE PREVIOUS TURN out of the
conversation history. Nothing was fetched. The manager saw stale data
formatted as a fresh answer, with no card, for ~6.7k tokens.

That failure mode is the reason this is worth a deterministic fast path
rather than a better classifier prompt: an intent that falls through to
general chat does not fail loudly, it fabricates something plausible from
context. The routing has to be right.

The mechanism mirrors the bare-DATE continuation that already exists
(_DATE_REFINABLE_INTENTS / _is_bare_date_fragment): when the previous turn
was ABOUT a named person, a bare name means "same question, different (or
same) person".
"""

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


LEAVE_LOOKUP = "manager_leave_request_lookup"
ATTENDANCE_LOOKUP = "manager_attendance_explanation"


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 _state(query, last_intent=LEAVE_LOOKUP, is_manager=True):
    return {
        "query": query, "context": [], "bearer_token": "t",
        "company_id": "3735", "conversation_id": "conv-1", "usage_events": [],
        "is_manager": is_manager, "intent": "general", "last_intent": last_intent,
    }


@contextmanager
def _mocks(detected="general_hr"):
    """Everything downstream of the fast path. If the fast path does its job
    none of these is touched, which is itself asserted below."""
    clf = AsyncMock(return_value=(detected, {"total_tokens": 5795}, False))
    mod = AsyncMock(return_value={"flagged": False})
    shift = AsyncMock(return_value=(None, 0.0, {"total_tokens": 397}))
    ir = AsyncMock(return_value=(None, 0.0, {"total_tokens": 629}))
    slot_store = MagicMock(get_slots=MagicMock(return_value=None))
    # The manager pre-checks ahead of the fast path read Redis. Left real
    # they make every case here wait on a dead connection, which is slow
    # enough to look like a hang - and none of them is what these tests are
    # about. "No pending card" is the state this scenario describes anyway:
    # the previous turn ANSWERED, it did not ask anything.
    none_pending = MagicMock(return_value=None)
    with patch.multiple(classify_node_mod,
                        classify_intent_structured=clf, _check_moderation=mod,
                        _resolve_shift_route=shift,
                        _resolve_individual_report_route=ir,
                        leave_slot_service=slot_store),             patch.object(classify_node_mod.leave_approval,
                         "resolve_pending_approval_intent", none_pending),             patch.object(classify_node_mod.regularisation_approval,
                         "resolve_pending_regularisation_intent", none_pending),             patch.object(classify_node_mod.individual_report,
                         "resolve_pending_selection_intent", none_pending):
        yield {"classify": clf, "shift": shift, "individual_report": ir}


# =============================================================================
# The continuation
# =============================================================================

class TestABareNameContinuesTheLastLookup:

    @pytest.mark.parametrize("last_intent,expected_node", [
        (LEAVE_LOOKUP, "leave_request_node"),
        (ATTENDANCE_LOOKUP, "attendance_explanation_node"),
    ])
    async def test_the_previous_intent_is_carried_forward(self, last_intent, expected_node):
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(
                _state("Ayush Jio", last_intent=last_intent), writer)

        assert result["intent"] == last_intent
        assert result["error"] is None
        assert hr_graph._route_after_classify(result) == expected_node

    async def test_it_never_lands_in_general_chat(self):
        """general_hr is the specific wrong answer this fixes - that route
        answers from conversation history instead of erp-api."""
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(_state("Ayush Jio"), writer)

        assert result["intent"] != "general_hr"
        assert hr_graph._route_after_classify(result) != "hr_response_node"

    async def test_an_intent_event_is_still_streamed(self):
        writer = FakeWriter()
        with _mocks():
            await hr_graph.classify_node(_state("Ayush Jio"), writer)

        assert writer.of_type("intent")[0]["intent"] == LEAVE_LOOKUP

    async def test_no_llm_call_is_made_at_all(self):
        """Deterministic, so it still works when the classifier is
        rate-limited - and the turn stops costing ~6.7k tokens."""
        writer = FakeWriter()
        with _mocks() as m:
            await hr_graph.classify_node(_state("Ayush Jio"), writer)

        assert not m["classify"].called
        assert not m["shift"].called
        assert not m["individual_report"].called

    @pytest.mark.parametrize("query", [
        "Ayush Jio", "ayush jio", "AYUSH JIO", "Ayush", "geo3",
        "B Sharma", "Mary-Jane O'Neill",
    ])
    async def test_name_shapes_that_must_continue(self, query):
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(_state(query), writer)

        assert result["intent"] == LEAVE_LOOKUP


# =============================================================================
# A bare name after a TEAM card narrows it to one person
# =============================================================================

class TestABareNameNarrowsATeamCard:
    """Second live report, same root cause, different previous turn:

        "show my team pending leaves" -> the team card, 10 pending, top 3 shown
        "ayush jio"                   -> general_hr

    The chat model answered by re-reading the CARD out of the conversation
    history - so it listed only the three rows that card happened to show and
    added "There may be more pending requests available". The card's top-3
    truncation was silently inherited as if it were the whole answer.
    """

    @pytest.mark.parametrize("last_intent,expected_intent,expected_node", [
        ("HRMS_TEAM_LEAVE_QUERY", LEAVE_LOOKUP, "leave_request_node"),
        ("HRMS_TEAM_ATTENDANCE_QUERY", ATTENDANCE_LOOKUP, "attendance_explanation_node"),
    ])
    async def test_the_team_intent_becomes_its_per_employee_counterpart(
        self, last_intent, expected_intent, expected_node
    ):
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(
                _state("ayush jio", last_intent=last_intent), writer)

        assert result["intent"] == expected_intent
        assert hr_graph._route_after_classify(result) == expected_node

    async def test_it_does_not_land_in_general_chat(self):
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(
                _state("ayush jio", last_intent="HRMS_TEAM_LEAVE_QUERY"), writer)

        assert result["intent"] != "general_hr"
        assert hr_graph._route_after_classify(result) != "hr_response_node"

    async def test_the_team_roster_falls_back_to_the_default(self):
        """After a roster card a bare name could mean leave OR attendance, so
        HRMS_TEAM_MEMBERS_QUERY is still absent from the mapping - but it no
        longer falls to general chat either. It takes the same default any
        lone name takes (see TestABareNameAloneIsStillAboutThatPerson), which
        is a real lookup rather than an answer improvised from context."""
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(
                _state("ayush jio", last_intent="HRMS_TEAM_MEMBERS_QUERY"), writer)

        assert result["intent"] == LEAVE_LOOKUP
        assert result["intent"] != "general_hr"


# =============================================================================
# The guards - everything that must NOT be treated as a name
# =============================================================================

class TestWhatMustStillReachTheClassifier:

    async def test_a_non_manager_is_unaffected(self):
        """Both continuable intents are manager-only; for anyone else a
        stray name must keep falling through."""
        writer = FakeWriter()
        with _mocks() as m:
            result = await hr_graph.classify_node(
                _state("Ayush Jio", is_manager=False), writer)

        assert result["intent"] == "general_hr"
        assert m["classify"].called

    @pytest.mark.parametrize("last_intent", [
        "leave_balance", "apply_leave", "attendance", "general_hr", None,
    ])
    async def test_an_unrelated_previous_turn_takes_the_default_not_chat(self, last_intent):
        """This pinned the narrower first version: only a question ABOUT a
        named person could be continued, and a name after anything else fell
        to the classifier.

        That is no longer the behaviour, deliberately - falling through meant
        landing in general chat, which answers a name from conversation
        context instead of fetching anything (reported three separate times).
        A lone name is now a lookup whatever came before it. Which INTENT the
        previous turn selects is still governed by the mapping, covered in
        TestABareNameContinuesTheLastLookup.
        """
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(
                _state("Ayush Jio", last_intent=last_intent), writer)

        assert result["intent"] == LEAVE_LOOKUP
        assert result["intent"] != "general_hr"

    @pytest.mark.parametrize("query", [
        "yes", "no", "ok", "thanks", "hi", "please", "cancel", "why", "more",
    ])
    async def test_conversational_replies_are_not_names(self, query):
        """These are alphabetic and short - exactly the shape a surname takes
        - so they are excluded by name, not by luck.

        Asserted as "did not continue the lookup" rather than "reached the
        classifier", because some of these have their own earlier fast path
        ("cancel" is caught by the bare-verb clarify) and never reach it for
        reasons that have nothing to do with this change."""
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(_state(query), writer)

        assert result["intent"] != LEAVE_LOOKUP,             f"{query!r} was wrongly read as an employee name"

    @pytest.mark.parametrize("query", [
        "26 august", "last friday", "monday", "august", "yesterday",
    ])
    async def test_bare_dates_are_left_to_the_date_continuation(self, query):
        """A bare date is the OTHER continuation. Swallowing it here would
        re-run the lookup for a person called "last friday"."""
        writer = FakeWriter()
        with _mocks() as m:
            await hr_graph.classify_node(_state(query), writer)

        assert m["classify"].called, f"{query!r} was wrongly read as a name"

    @pytest.mark.parametrize("query", [
        "show my leave balance", "leave balance", "team attendance",
        "show pending leave requests for my team",
    ])
    async def test_a_real_question_is_still_classified_normally(self, query):
        writer = FakeWriter()
        with _mocks() as m:
            result = await hr_graph.classify_node(_state(query), writer)

        assert result["intent"] != LEAVE_LOOKUP or m["classify"].called

    async def test_a_long_sentence_is_never_a_name(self):
        writer = FakeWriter()
        with _mocks() as m:
            await hr_graph.classify_node(
                _state("can you tell me about Ayush Jio please"), writer)

        assert m["classify"].called


class TestThePredicateDirectly:

    @pytest.mark.parametrize("query,is_name", [
        ("Ayush Jio", True),
        ("geo3", True),
        ("B Sharma", True),
        ("26 august", False),
        ("last friday", False),
        ("thanks", False),
        ("yes", False),
        ("leave balance", False),
        ("show ayush jio leave request", False),
        ("", False),
        ("   ", False),
    ])
    def test_is_bare_person_fragment(self, query, is_name):
        assert classify_node_mod._is_bare_person_fragment(query, False) is is_name

    def test_a_flagged_date_expression_is_never_a_name(self):
        assert classify_node_mod._is_bare_person_fragment("Ayush Jio", True) is False


# =============================================================================
# A bare name with NO prior question still gets a real intent
# =============================================================================

class TestABareNameAloneIsStillAboutThatPerson:
    """Third report of the same shape. A manager typed "abctest" and got a
    tidy markdown list of ABC Testing's three pending requests - written by
    the chat model from conversation context, with no intent and no card.
    Nothing was fetched.

    The continuation above only fired when the PREVIOUS turn was one it could
    carry forward. With no such turn there is still only one thing a lone
    name can mean, so it now defaults to that person's pending leave
    requests - the same thing the chat model was improvising.
    """

    @pytest.mark.parametrize("query", [
        "abctest", "abc testing", "Ayush Jio", "a khan", "geo3",
    ])
    async def test_a_name_gets_a_real_intent(self, query):
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(
                _state(query, last_intent=None), writer)

        assert result["intent"] == LEAVE_LOOKUP
        assert hr_graph._route_after_classify(result) == "leave_request_node"
        assert writer.of_type("intent")[0]["intent"] == LEAVE_LOOKUP

    @pytest.mark.parametrize("query", [
        "payroll", "salary", "policy", "holiday", "appraisal", "pf", "hr",
        "manager", "probation", "reimbursement", "timesheet", "overtime",
    ])
    async def test_an_hr_topic_is_not_a_person(self, query):
        """These are one alphabetic word that fast_classify does not label -
        identical in shape to a surname. Routing them to an employee lookup
        would answer "payroll" with "no employee matched that name"."""
        writer = FakeWriter()
        with _mocks() as m:
            result = await hr_graph.classify_node(
                _state(query, last_intent=None), writer)

        assert result["intent"] != LEAVE_LOOKUP
        # Either the classifier decides, or - for words configured as bare
        # topics in bare_verb_config ("payroll", "salary"; HA-802) - the
        # "what about your payroll?" clarify card answers first. Both treat
        # it as a topic; neither looks up a person.
        assert m["classify"].called or result["intent"] == "clarify_needed"

    async def test_a_non_manager_is_unaffected(self):
        """The lookup is manager-only, so for anyone else a stray name must
        keep falling through to the classifier."""
        writer = FakeWriter()
        with _mocks() as m:
            result = await hr_graph.classify_node(
                _state("abctest", last_intent=None, is_manager=False), writer)

        assert result["intent"] == "general_hr"
        assert m["classify"].called

    async def test_it_still_costs_no_llm_call(self):
        writer = FakeWriter()
        with _mocks() as m:
            await hr_graph.classify_node(_state("abctest", last_intent=None), writer)

        assert not m["classify"].called

    @pytest.mark.parametrize("query", ["328", "3735", "61", "12345"])
    async def test_a_bare_number_is_a_request_ref_not_a_person(self, query):
        """Live regression this closes: the cards print request refs ("Ref
        #328"), a manager typed "328" to point at one, and it was routed as
        an employee name - answered with "I cannot retrieve attendance or
        leave information for this employee"."""
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(
                _state(query, last_intent=None), writer)

        assert result["intent"] != LEAVE_LOOKUP

    @pytest.mark.parametrize("query", [
        "rudraveer1111", "abctesting11", "akhantest2", "ayushjio9",
    ])
    async def test_a_name_with_trailing_digits_still_routes(self, query):
        """The token pattern allowed digits only inside a SHORT all-alnum
        token (for codes like "geo3"), so a long name with digits stuck on
        matched nothing and never reached the lookup - the chat model
        answered it instead, with no intent and no card."""
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(
                _state(query, last_intent=None), writer)

        assert result["intent"] == LEAVE_LOOKUP

    @pytest.mark.parametrize("query", ["geo3", "em6", "test07"])
    def test_an_employee_code_is_still_a_person(self, query):
        """A code carries letters, which is what separates it from a request
        number."""
        assert classify_node_mod._is_bare_person_fragment(query, False) is True

    @pytest.mark.parametrize("query", ["thanks", "yes", "ok", "why", "26 august"])
    async def test_conversational_replies_and_dates_are_still_excluded(self, query):
        writer = FakeWriter()
        with _mocks():
            result = await hr_graph.classify_node(
                _state(query, last_intent=None), writer)

        assert result["intent"] != LEAVE_LOOKUP
