"""The three-turn drill-down: team -> a member -> a leave type.

    manager: show my team pending leaves   -> the team card
    manager: A Khan Test                   -> his pending requests
    manager: casual leave                  -> HIS casual leave

Two defects sat in this path.

1. TEAM LEAVE HAD NO DETERMINISTIC ROUTE. _is_team_attendance_query and
   _is_team_members_query each had one; team LEAVE did not, so turn 1
   depended entirely on the LLM classifier. When that answered general_hr or
   leave_status the manager got chat prose, or their OWN pending leaves -
   the reported "sometimes it shows my pending leaves instead of the team's".
   fast_classify scores the question at 1.0, so the route is now taken from
   there.

2. A BARE LEAVE TYPE WAS READ AS THE CALLER'S OWN. Turn 3 scored leave_policy
   and got the self-service menu - "would you like your casual leave balance,
   view your applied casual leaves ...?" - which is a different person's data
   and a different question from the one being asked about A Khan Test.

All three turns are deterministic: no LLM call is made on any of them, so the
drill-down keeps working while the classifier is rate-limited.
"""

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

import services.hr_graph as hr_graph
import services.classify_node as classify_node
import services.individual_report as individual_report
import services.erp_client as erp_client


TEAM_LEAVE = "HRMS_TEAM_LEAVE_QUERY"
LOOKUP = "manager_leave_request_lookup"

KHAN_CASUAL = {
    "id": 308, "employee_id": 692, "employee_number": "em6",
    "employee_name": "A Khan Test", "employee_designation": "IT",
    "leave_type": "Casual Leave", "leave_type_slug": "casual_leave",
    "session_type": "Full Day", "from_date": "2026-09-01",
    "to_date": "2026-09-02", "leave_count": "2", "status_name": "pending",
    "reason": "Family", "applied_date": "2026-09-17",
}
KHAN_SHORT = {**KHAN_CASUAL, "id": 310, "leave_type": "Short Leave",
              "leave_type_slug": "short_leave", "from_date": "2026-09-16",
              "to_date": "2026-09-16", "leave_count": "1", "reason": "work"}
ABC_SICK = {**KHAN_CASUAL, "id": 320, "employee_id": 489,
            "employee_number": "test07", "employee_name": "ABC Testing",
            "employee_designation": "Selenium", "leave_type": "Sick Leave",
            "leave_type_slug": "sick_leave", "from_date": "2026-09-22",
            "to_date": "2026-09-22", "leave_count": "1", "reason": "ddd"}
TEAM = [KHAN_CASUAL, KHAN_SHORT, ABC_SICK]

ROSTER = [
    {"employee_id": 692, "employee_number": "em6",
     "employee_name": "A Khan Test", "designation": "IT"},
    {"employee_id": 489, "employee_number": "test07",
     "employee_name": "ABC Testing", "designation": "Selenium"},
]


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

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

    def types(self):
        return [e.get("type") for e in self.events]

    def of_type(self, etype):
        return [e for e in self.events if e.get("type") == etype]


def state(query, last_intent=None, 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": last_intent, "has_date_expression": False}


@contextmanager
def _classifier(llm_says="general_hr"):
    """Everything the classifier could reach. The LLM deliberately answers
    general_hr - every turn here must be decided without it."""
    clf = AsyncMock(return_value=(llm_says, None, False))
    none_pending = MagicMock(return_value=None)
    with 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)),
        # A regularisation mid-flow left behind by another test module
        # otherwise claims these turns - slot_store is a SEPARATE store
        # from leave_slot_service and needs neutralising of its own.
        slot_store=MagicMock(get_slots=MagicMock(return_value=None)),
    ), 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):
        yield clf


@pytest.fixture
def report_store(monkeypatch):
    store = {}
    monkeypatch.setattr(individual_report.leave_slot_service, "get_report_state",
                        lambda c, k: store.get((str(c), k)))
    monkeypatch.setattr(individual_report.leave_slot_service, "set_report_state",
                        lambda c, k, v: bool(store.__setitem__((str(c), k), v)) or True)
    monkeypatch.setattr(individual_report.leave_slot_service, "clear_report_state",
                        lambda c, k: store.pop((str(c), k), None))
    return store


@pytest.fixture
def erp(monkeypatch):
    async def _lookup(token, company_id=None, conversation_id=None,
                      employee_id=None, employee_name=None):
        if employee_id is None:
            squash = (employee_name or "").lower().replace(" ", "")
            matches = [e for e in ROSTER
                       if squash in e["employee_name"].lower().replace(" ", "")]
            return {"http_status": 200, "body": {"success": True, "data": {
                "action_required": "select_employee",
                "search_matched": bool(matches),
                "employees": matches or list(ROSTER)}}}
        rows = [lv for lv in TEAM if lv["employee_id"] == employee_id]
        return {"http_status": 200, "body": {"success": True, "data": {
            "employee": {"employee_id": employee_id,
                         "employee_name": rows[0]["employee_name"]},
            "total_pending_leaves": len(rows), "leaves": rows}}}
    monkeypatch.setattr(erp_client, "get_team_pending_leaves", _lookup)

    async def _ctx(token, **kw):
        return {"http_status": 200, "body": {"success": True,
                                             "data": {"is_manager": True}}}

    async def _team(token, **kw):
        return {"http_status": 200, "body": {"success": True, "data": {
            "access_scope": "direct_reports", "total_pending_leaves": len(TEAM),
            "leaves": list(TEAM)}}}
    monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _ctx)
    monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", _team)


def names(monkeypatch, employee_name):
    async def _extract(query, today):
        return {"employee_id": None, "employee_name": employee_name,
                "uses_pronoun": False, "attendance_date": None,
                "attendance_status": None}, None
    monkeypatch.setattr(individual_report.ai_service,
                        "extract_individual_report_fields", _extract)


# =============================================================================
# Turn 1 - the team question routes deterministically
# =============================================================================

class TestTurn1TheTeamCard:

    @pytest.mark.parametrize("query", [
        "show my team pending leaves",
        "show my team pending leave request",
        "show my team leave requests",
        "pending leave for my team",
        "team leave requests",
    ])
    async def test_it_routes_to_the_team_node(self, query):
        with _classifier():
            result = await hr_graph.classify_node(state(query), FakeWriter())

        assert result["intent"] == TEAM_LEAVE
        assert hr_graph._route_after_classify(result) == "team_leave_query_node"

    async def test_it_does_not_need_the_llm(self):
        """The reported flakiness: the identical question answered correctly
        one run and as the caller's own leaves the next, because only the LLM
        decided it."""
        with _classifier() as clf:
            await hr_graph.classify_node(
                state("show my team pending leaves"), FakeWriter())

        assert not clf.called

    async def test_it_is_never_the_callers_own_leave_status(self):
        with _classifier(llm_says="leave_status"):
            result = await hr_graph.classify_node(
                state("show my team pending leaves"), FakeWriter())

        assert result["intent"] != "leave_status"
        assert result["intent"] == TEAM_LEAVE

    async def test_the_card_carries_the_team(self, erp):
        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            {**state("show my team pending leaves"), "intent": TEAM_LEAVE}, writer)

        card = writer.of_type("team_pending_leave")[0]["data"]
        assert [lv["employee_name"] for lv in card["leaves"]] == [
            "A Khan Test", "A Khan Test", "ABC Testing"]

    async def test_a_personal_leave_question_is_untouched(self):
        """The fast path must not swallow the caller's OWN leave question."""
        with _classifier(llm_says="leave_status"):
            result = await hr_graph.classify_node(
                state("show my pending leaves"), FakeWriter())

        assert result["intent"] != TEAM_LEAVE


# =============================================================================
# Turn 2 - a member's name drills into that person
# =============================================================================

class TestTurn2TheMemberName:

    @pytest.mark.parametrize("name", ["A Khan Test", "a khan", "abc testing"])
    async def test_the_name_routes_to_the_individual_lookup(self, name):
        with _classifier() as clf:
            result = await hr_graph.classify_node(
                state(name, last_intent=TEAM_LEAVE), FakeWriter())

        assert result["intent"] == LOOKUP
        assert hr_graph._route_after_classify(result) == "leave_request_node"
        assert not clf.called

    async def test_it_returns_that_persons_requests(self, monkeypatch, erp, report_store):
        names(monkeypatch, "A Khan Test")
        writer = FakeWriter()

        result = await individual_report.individual_report_node(
            {**state("A Khan Test"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            writer)

        assert writer.of_type("individual_leave_request")
        assert "A Khan Test" in result["response_text"]
        assert "2 pending leave requests" in result["response_text"]
        assert "ABC Testing" not in result["response_text"]


# =============================================================================
# Turn 3 - a leave type narrows THAT person
# =============================================================================

class TestTurn3TheLeaveType:

    async def test_it_continues_the_lookup_not_the_self_service_menu(self):
        with _classifier() as clf:
            result = await hr_graph.classify_node(
                state("casual leave", last_intent=LOOKUP), FakeWriter())

        assert result["intent"] == LOOKUP
        assert result["intent"] != "leave_type_clarify"
        assert not clf.called

    async def test_it_filters_that_persons_requests(self, monkeypatch, erp, report_store):
        """The subject comes from the previous turn; the message only says
        which KIND."""
        names(monkeypatch, "A Khan Test")
        await individual_report.individual_report_node(
            {**state("A Khan Test"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            FakeWriter())

        names(monkeypatch, None)
        writer = FakeWriter()
        result = await individual_report.individual_report_node(
            {**state("casual leave"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            writer)

        assert "A Khan Test" in result["response_text"]
        assert "casual leave request" in result["response_text"].lower()
        assert "Short Leave" not in result["response_text"]

    async def test_a_type_that_person_does_not_have_says_so(self, monkeypatch, erp, report_store):
        """Not a denial, and not somebody else's sick leave - A Khan Test has
        none, and ABC Testing's must not be borrowed to fill the gap.

        The wording is asserted in TestATypeThatMemberDoesNotHave below; what
        this pins is the scoping, which is what could go quietly wrong.
        """
        names(monkeypatch, "A Khan Test")
        await individual_report.individual_report_node(
            {**state("A Khan Test"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            FakeWriter())

        names(monkeypatch, None)
        result = await individual_report.individual_report_node(
            {**state("sick leave"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            FakeWriter())

        assert "doesn't have a pending sick leave request" in result["response_text"]
        assert "A Khan Test" in result["response_text"]
        assert "ABC Testing" not in result["response_text"]

    async def test_the_menu_still_fires_without_that_context(self):
        """A bare leave type with no individual lookup behind it is still the
        caller asking about their own - that is what the menu is for."""
        with _classifier():
            result = await hr_graph.classify_node(
                state("casual leave", last_intent=None), FakeWriter())

        assert result["intent"] != LOOKUP

    async def test_a_non_manager_never_gets_the_continuation(self):
        with _classifier():
            result = await hr_graph.classify_node(
                state("casual leave", last_intent=LOOKUP, is_manager=False),
                FakeWriter())

        assert result["intent"] != LOOKUP

    @pytest.mark.parametrize("leave_type", [
        "casual leave", "sick leave", "short leave", "comp off", "earned leave",
    ])
    async def test_every_leave_type_continues_the_lookup(self, leave_type):
        """"short leave" was the one that slipped through. The continuation
        used to ask fast_classify whether the message looked like
        leave_policy, which it says for "casual leave" and "sick leave" but
        not for "short leave" - so that one reached the LLM and came back as
        the self-service menu."""
        with _classifier(llm_says="leave_policy"):
            result = await hr_graph.classify_node(
                state(leave_type, last_intent=LOOKUP), FakeWriter())

        assert result["intent"] == LOOKUP


class TestATypeThatMemberDoesNotHave:
    """Reported: looking at Rudraveer's Casual and Sick requests, the manager
    typed "short leave" and got a blank grey box - the card rendered from an
    empty `leaves` list, with a sentence underneath saying only that he had
    none. Neither told them what he DID have, nor that another team member
    might."""

    async def test_it_says_what_that_person_actually_has(
            self, monkeypatch, erp, report_store):
        names(monkeypatch, "A Khan Test")
        await individual_report.individual_report_node(
            {**state("A Khan Test"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            FakeWriter())

        names(monkeypatch, None)
        result = await individual_report.individual_report_node(
            {**state("sick leave"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            FakeWriter())

        text = result["response_text"]
        assert "doesn't have a pending sick leave request" in text
        assert "Casual Leave" in text and "Short Leave" in text
        assert "another team member" in text

    async def test_the_card_shows_those_requests_not_an_empty_shell(
            self, monkeypatch, erp, report_store):
        """The blank box was the card itself, drawn from `leaves: []`."""
        names(monkeypatch, "A Khan Test")
        await individual_report.individual_report_node(
            {**state("A Khan Test"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            FakeWriter())

        names(monkeypatch, None)
        writer = FakeWriter()
        await individual_report.individual_report_node(
            {**state("sick leave"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            writer)

        card = writer.of_type("individual_leave_request")[0]["data"]
        assert len(card["leaves"]) == 2, "the card must show what they DO have"
        assert card["requested_leave_type_unavailable"] == "sick leave"

    async def test_a_type_they_do_have_is_unaffected(
            self, monkeypatch, erp, report_store):
        names(monkeypatch, "A Khan Test")
        await individual_report.individual_report_node(
            {**state("A Khan Test"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            FakeWriter())

        names(monkeypatch, None)
        result = await individual_report.individual_report_node(
            {**state("casual leave"), "intent": individual_report.LEAVE_REQUEST_INTENT},
            FakeWriter())

        assert "doesn't have a pending" not in result["response_text"]
        assert "casual leave request" in result["response_text"].lower()


class TestTheSelfServiceMenuWording:

    @pytest.mark.parametrize("type_word,expected", [
        ("short leave", "your short leave balance"),
        ("sick", "your sick leave balance"),
        ("casual", "your casual leave balance"),
        ("compoff", "your comp off leave balance"),
    ])
    def test_the_noun_is_not_doubled(self, type_word, expected):
        """Live: "Would you like to know your short leave leave balance ...
        or apply for short leave leave?" - the slug map already spells some
        types with "leave" in them, and every sentence appends another."""
        message = classify_node._leave_type_clarify_message(type_word)

        assert expected in message
        assert "leave leave" not in message
        assert "compoff" not in message
