"""FR-07.5's out-of-chat intents, detected deterministically.

Only bulk_approvals had a detector. large_team_review, shift_planning and
comparative_reporting existed purely as labels in the LLM classifier's
prompt, so they were reached only when it happened to pick them - and two of
them were being intercepted before it ever ran:

    "compare my team attendance this quarter against last quarter,
     broken down by department"
        -> matched _is_team_attendance_query, which returned TODAY's
           attendance card for a question about two quarters.

    "review attendance for all my team members"
        -> scored HRMS_TEAM_MEMBERS_QUERY off "my team members" and
           returned the roster.

Both fast paths return before the classifier, so no prompt wording could
have rescued either. The detector runs ahead of them instead.

Misspellings are folded first, because they were deciding the route:
"review attendacne for alla my team members" and "plan next months roaster
for the support team" both went somewhere else entirely. The fold is a
closed HR word list, not a spell-checker - names must survive it untouched,
which the last class here pins.
"""

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

import services.hr_graph as hr_graph
import services.classify_node as classify_node
from services.complex_manager_router import COMPLEX_MANAGER_INTENTS


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


def _classifier(llm_says="general_hr"):
    none_pending = MagicMock(return_value=None)
    clf = AsyncMock(return_value=(llm_says, None, False))
    return patch.multiple(
        classify_node, classify_intent_structured=clf,
        _check_moderation=AsyncMock(return_value={"flagged": False}),
        _resolve_shift_route=AsyncMock(return_value=(None, 0.0, None)),
        _resolve_individual_report_route=AsyncMock(return_value=(None, 0.0, None)),
        leave_slot_service=MagicMock(get_slots=MagicMock(return_value=None)),
        leave_cancel_state=MagicMock(get_state=MagicMock(return_value=None)),
        slot_store=MagicMock(get_slots=MagicMock(return_value=None)),
        bare_verb_clarify_state=MagicMock(get_state=MagicMock(return_value=None),
                                          set_state=MagicMock(return_value=True)),
    ), patch.object(classify_node.leave_approval,
                    "resolve_pending_approval_intent", none_pending), \
        patch.object(classify_node.regularisation_approval,
                     "resolve_pending_regularisation_intent", none_pending), \
        patch.object(classify_node.individual_report,
                     "resolve_pending_selection_intent", none_pending), clf


# =============================================================================
# The detector
# =============================================================================

class TestLargeTeamReview:

    @pytest.mark.parametrize("query", [
        "i want to review attendance for all my team members",
        "i want to review attendacne for alla my team members",
        "i need to review attendance for all 40 people in my org",
        "review attendance for every employee",
        "go through attendance for the whole team",
        "audit records for all staff",
    ])
    def test_it_is_detected(self, query):
        assert classify_node.complex_manager_intent(query) == "large_team_review"

    @pytest.mark.parametrize("query", [
        # The reported pair. These two differ by one word, and only the
        # second used to be detected - the first fell through to
        # _is_team_attendance_query and answered with TODAY's card.
        "now i want to review my team attandance",
        "now i want to review all my team attandance",
        "review my team attendance",
        "i want to review my teams attendance",
        "go through my team attendance",
        "audit my team attendance",
        "review the team attendance",
        "assess our staff attendance",
        "review my team performance",
        "review my team timesheets",
    ])
    def test_a_plain_possessive_team_counts_as_the_whole_team(self, query):
        """"my team" is how a manager says it; the quantifier is optional.
        The REVIEW VERB is what makes this a large-team review."""
        assert classify_node.complex_manager_intent(query) == "large_team_review"

    @pytest.mark.parametrize("query", [
        "review my team pending leaves",
        "go through my team leave requests",
        "review my teams pending leave requests",
        "review my team roster",
        "review my team shifts",
        "audit my team members",
    ])
    def test_subjects_with_their_own_node_are_left_in_chat(self, query):
        """Widening the scope to "my team" also reaches these, and each has a
        working in-chat answer - team_leave_query_node's card (which the
        approve flow then resolves against), the roster, the shift lookup.
        A dashboard link would be a downgrade, so they hand back None."""
        assert classify_node.complex_manager_intent(query) is None

    def test_naming_attendance_still_wins_over_that_exclusion(self):
        """The exclusion is only consulted when no review SUBJECT is named,
        so the suite's own "all my team members" case is untouched."""
        assert classify_node.complex_manager_intent(
            "review attendance for all my team members") == "large_team_review"


class TestShiftPlanning:

    @pytest.mark.parametrize("query", [
        "help me plan next months roaster for the support team",
        "help me plan next months roster for the support team",
        "i want to create shift for my team for next month",
        "plan the rota for my team",
        "build next months schedule for support",
        "prepare the shift schedule for october",
        "set up shifts for my team",
    ])
    def test_it_is_detected(self, query):
        assert classify_node.complex_manager_intent(query) == "shift_planning"

    @pytest.mark.parametrize("query", [
        "what shift am i on", "shift details of geo3", "show team roster",
        "my shift timing",
    ])
    def test_asking_what_a_shift_IS_is_not_planning_one(self, query):
        """shift_query answers these, and it carries no planning verb."""
        assert classify_node.complex_manager_intent(query) is None


class TestComparativeReporting:

    @pytest.mark.parametrize("query", [
        "compare my team attendance this quarter against last quarter, "
        "broken down by department",
        "compare attendance this month vs last month",
        "show attendance broken down by department compared to last quarter",
        "compare team performance versus previous quarter",
    ])
    def test_it_is_detected(self, query):
        assert classify_node.complex_manager_intent(query) == "comparative_reporting"

    @pytest.mark.parametrize("query", [
        "compare my leave balance", "compare these two requests",
    ])
    def test_a_comparison_with_no_period_or_breakdown_is_not_a_report(self, query):
        """It needs TWO periods or an explicit breakdown - that is what keeps
        the word "compare" from taking over unrelated turns."""
        assert classify_node.complex_manager_intent(query) is None


class TestOrdinaryQueriesAreUntouched:

    @pytest.mark.parametrize("query", [
        "show my team attendance",
        "who was absent today",
        "show my team pending leaves",
        "my leave balance",
        "show my team members",
        "approve a khan test",
        "apply casual leave tomorrow",
    ])
    def test_they_are_not_complex_manager_tasks(self, query):
        assert classify_node.complex_manager_intent(query) is None


# =============================================================================
# Routing - ahead of the fast paths that were intercepting
# =============================================================================

class TestTheyReachTheNavigationCard:

    @pytest.mark.parametrize("query,expected", [
        ("I want to review attendacne for alla my team members", "large_team_review"),
        ("I need to review attendance for all 40 people in my org", "large_team_review"),
        ("help me plan next months roaster for the support team", "shift_planning"),
        ("i want to create shift for my team for next month", "shift_planning"),
        ("compare my team attendance this quarter against last quarter, "
         "broken down by department", "comparative_reporting"),
        ("approve all pending leave requests for my team", "bulk_approvals"),
    ])
    async def test_the_intent_is_the_complex_manager_one(self, query, expected):
        outer, a, b, c, clf = _classifier()
        with outer, a, b, c:
            result = await hr_graph.classify_node(state(query), FakeWriter())

        assert result["intent"] == expected
        assert result["intent"] in COMPLEX_MANAGER_INTENTS
        assert hr_graph._route_after_classify(result) == "complex_manager_task_node"

    async def test_comparative_beats_the_team_attendance_fast_path(self):
        """The reported one: it used to answer with today's attendance card."""
        outer, a, b, c, clf = _classifier()
        with outer, a, b, c:
            result = await hr_graph.classify_node(
                state("compare my team attendance this quarter against last "
                      "quarter, broken down by department"), FakeWriter())

        assert result["intent"] != "HRMS_TEAM_ATTENDANCE_QUERY"
        assert result["intent"] == "comparative_reporting"

    @pytest.mark.parametrize("query", [
        "now i want to review my team attandance",
        "now i want to review all my team attandance",
        "review my team attendance",
    ])
    async def test_the_reported_pair_both_reach_the_team_review_card(self, query):
        """Reported: these two differed by the word "all", and only the one
        that had it produced the navigation card. The other answered with
        today's team attendance instead."""
        outer, a, b, c, clf = _classifier()
        with outer, a, b, c:
            result = await hr_graph.classify_node(state(query), FakeWriter())

        assert result["intent"] == "large_team_review"
        assert result["intent"] != "HRMS_TEAM_ATTENDANCE_QUERY"
        assert hr_graph._route_after_classify(result) == "complex_manager_task_node"

        writer = FakeWriter()
        await hr_graph.complex_manager_task_node(
            {**state(query), **result, "is_manager": True}, writer)
        cards = writer.of_type("navigation_card")
        assert cards, "manager got no navigation card"
        assert cards[0]["data"]["button"]["path"] == "/team/review"

    async def test_review_beats_the_team_roster_fast_path(self):
        """It used to score HRMS_TEAM_MEMBERS_QUERY and return the roster."""
        outer, a, b, c, clf = _classifier()
        with outer, a, b, c:
            result = await hr_graph.classify_node(
                state("review attendance for all my team members"), FakeWriter())

        assert result["intent"] != "HRMS_TEAM_MEMBERS_QUERY"
        assert result["intent"] == "large_team_review"

    async def test_no_llm_call_is_needed(self):
        """Deterministic, so a rate-limited classifier cannot lose the
        route - and a typo cannot change it."""
        outer, a, b, c, clf = _classifier()
        with outer, a, b, c:
            await hr_graph.classify_node(
                state("help me plan next months roaster for the support team"),
                FakeWriter())

        assert not clf.called

    async def test_a_non_manager_does_not_get_these_routes(self):
        outer, a, b, c, clf = _classifier()
        with outer, a, b, c:
            result = await hr_graph.classify_node(
                state("help me plan next months roaster for the support team",
                      is_manager=False), FakeWriter())

        assert result["intent"] not in COMPLEX_MANAGER_INTENTS

    @pytest.mark.parametrize("query,expected", [
        ("show my team pending leaves", "HRMS_TEAM_LEAVE_QUERY"),
        ("show my team attendance", "HRMS_TEAM_ATTENDANCE_QUERY"),
        ("show my team members", "HRMS_TEAM_MEMBERS_QUERY"),
    ])
    async def test_the_ordinary_team_routes_still_win(self, query, expected):
        """Sitting this detector first must not take the everyday team
        questions away from the nodes that answer them."""
        outer, a, b, c, clf = _classifier()
        with outer, a, b, c:
            result = await hr_graph.classify_node(state(query), FakeWriter())

        assert result["intent"] == expected


# =============================================================================
# The typo fold
# =============================================================================

class TestHrTypoFolding:

    @pytest.mark.parametrize("typed,corrected", [
        ("attendacne", "attendance"),
        ("attendence", "attendance"),
        ("roaster", "roster"),
        ("shedule", "schedule"),
        ("alla", "all"),
        ("compair", "compare"),
    ])
    def test_common_misspellings_are_corrected(self, typed, corrected):
        assert classify_node.fold_hr_typos(typed) == corrected

    @pytest.mark.parametrize("text", [
        "rudraveer", "abc testing", "a khan test", "ayush jio", "b sharma",
        "improve my performance", "who was absent today", "my leave balance",
        "apply casual leave tomorrow",
    ])
    def test_names_and_ordinary_words_survive(self, text):
        """A closed word list, not a spell-checker: an employee name must
        never be rewritten into an HR term."""
        assert classify_node.fold_hr_typos(text) == text

    def test_short_words_are_left_alone(self):
        assert classify_node.fold_hr_typos("all of it") == "all of it"

    def test_it_tolerates_empty_input(self):
        assert classify_node.fold_hr_typos("") == ""
        assert classify_node.fold_hr_typos(None) is None
