"""Four ways a manager's approve instruction was not understood.

Reported together, all on the approve flow:

1. "approve <name> sick leave" was answered with the SELF-SERVICE leave-type
   menu - "Would you like to know your sick leave balance, view your applied
   sick leaves, check your sick leave eligibility, or apply for sick leave?"
   fast_classify scores that query leave_policy at 1.0 off "sick leave"
   alone, and classify_node's bare-leave-type branch returned before the
   approval route (which already recognised the phrasing) could run.

2. The leave TYPE in that instruction was then ignored: a member with two
   pending requests got "which one?" even though the message said which.

3. A verb typo - "appove", "aprove", "approv" - matched no pattern at all and
   fell through to general chat.

4. A bare request ID or name typed AT the confirmation card ("310", "abc
   testing") carried no action verb, so it was not recognised as a re-aim and
   went to general classification, where the chat model answered from context
   and nothing was looked up.

The line none of this may cross: a QUESTION about approvals, and a policy
question, must still never route into the state-changing node - which is what
the exclusion tests below pin.
"""

import pytest
from unittest.mock import AsyncMock

import services.classify_node as classify_node
import services.leave_approval as leave_approval
from services.leave_approval import leave_approval_node


SICK = {
    "id": 400, "employee_id": 489, "employee_number": "test07",
    "employee_name": "ABC Testing", "employee_designation": "Selenium",
    "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
    "session_type": "Full Day", "from_date": "2026-09-22",
    "to_date": "2026-09-22", "leave_count": "1", "status_name": "pending",
    "reason": "ddd", "applied_date": "2026-09-18",
}
CASUAL = {**SICK, "id": 401, "leave_type": "Casual Leave",
          "leave_type_slug": "casual_leave", "from_date": "2026-09-25",
          "to_date": "2026-09-25", "reason": "family"}
OTHER_PERSON = {
    "id": 310, "employee_id": 692, "employee_number": "em6",
    "employee_name": "A Khan Test", "employee_designation": "IT",
    "leave_type": "Short Leave", "leave_type_slug": "short_leave",
    "session_type": "Full Day", "from_date": "2026-09-16",
    "to_date": "2026-09-16", "leave_count": "1", "status_name": "pending",
    "reason": "work", "applied_date": "2026-09-17",
}


# =============================================================================
# 1 + 3 - the instruction is recognised as one
# =============================================================================

class TestTheInstructionRoutesToApproval:

    @pytest.mark.parametrize("query", [
        # the reported phrasing - a name AND a leave type
        "approve abc testing sick leave",
        "approve a khan sick leave",
        "approve abc testing casual leave",
        "reject abc testing sick leave",
        # a name with no type
        "approve abc testing",
        "approve a khan test",
        # verb typos
        "appove abc testing",
        "aprove abc testing",
        "approv abc testing",
        "aprove abc testing sick leave",
        # the shapes that already worked, kept as a floor
        "approve request 310",
        "approve his leave",
        "approve abc testing's leave",
    ])
    def test_it_is_a_leave_approval_query(self, query):
        assert classify_node._is_leave_approval_query(query) is True

    @pytest.mark.parametrize("query", [
        # questions about approvals, not instructions
        "is my leave approved",
        "was my leave approved",
        "how do i approve leave",
        "what is the approval policy",
        "how long does approval take",
        # a bare leave type - this is what the self-service menu IS for
        "sick leave",
        "casual leave",
        # the same verbs aimed at something else entirely
        "reject this candidate",
        # real words that merely resemble an approval verb
        "improve my attendance",
        "what is the approach for leave",
    ])
    def test_it_is_not_a_leave_approval_query(self, query):
        assert classify_node._is_leave_approval_query(query) is False


class TestVerbTypoFolding:

    @pytest.mark.parametrize("typed,corrected", [
        ("appove abc testing", "approve abc testing"),
        ("aprove abc testing", "approve abc testing"),
        ("approv abc testing", "approve abc testing"),
        ("rejct a khan", "reject a khan"),
    ])
    def test_a_misspelled_verb_is_corrected(self, typed, corrected):
        assert classify_node._normalise_action_verbs(typed) == corrected

    @pytest.mark.parametrize("text", [
        "improve my process",
        "approach the team",
        "my approval is pending",
        "declined offer letter",
        "cancel it",
        "and earned leave?",
    ])
    def test_real_words_are_left_alone(self, text):
        """The risk of folding typos is corrupting words that were correct.
        "improve" scores 0.71 against "approve" and stays itself."""
        assert classify_node._normalise_action_verbs(text) == text

    def test_short_words_are_never_folded(self):
        """Below five characters the score stops discriminating - "den"
        would otherwise reach "deny"."""
        assert classify_node._normalise_action_verbs("den the app") == "den the app"


class TestTheSelfServiceMenuStillWorks:
    """The menu must keep firing for what it is actually for: a bare leave
    type with no verb and no target."""

    @pytest.mark.parametrize("query", ["sick leave", "casual leave", "earned leave"])
    def test_a_bare_type_is_not_an_approval(self, query):
        assert classify_node._is_leave_approval_query(query) is False


# =============================================================================
# 2 + 4 - the node acts on what was said
# =============================================================================

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]


@pytest.fixture(autouse=True)
def action_store(monkeypatch):
    store = {}
    monkeypatch.setattr(leave_approval.leave_slot_service, "get_manager_action",
                        lambda c, k: store.get((str(c), k)))
    monkeypatch.setattr(leave_approval.leave_slot_service, "set_manager_action",
                        lambda c, k, v: bool(store.__setitem__((str(c), k), v)) or True)
    monkeypatch.setattr(leave_approval.leave_slot_service, "clear_manager_action",
                        lambda c, k: store.pop((str(c), k), None))
    return store


@pytest.fixture(autouse=True)
def _report_store(monkeypatch):
    store = {}
    monkeypatch.setattr(leave_approval.leave_slot_service, "get_report_state",
                        lambda c, k: store.get((str(c), k)))
    monkeypatch.setattr(leave_approval.leave_slot_service, "set_report_state",
                        lambda c, k, v: bool(store.__setitem__((str(c), k), v)) or True)
    return store


def serve(monkeypatch, rows):
    approved = []

    async def _pending(token, company_id=None, conversation_id=None,
                       employee_id=None, employee_name=None):
        return {"http_status": 200, "body": {"success": True, "data": {
            "employee": {"employee_id": 489, "employee_name": "ABC Testing"},
            "total_pending_leaves": len(rows), "leaves": list(rows)}}}

    async def _approve(token, leave_request_id, company_id=None, conversation_id=None):
        approved.append(leave_request_id)
        return {"http_status": 200, "body": {"success": True, "data": {}}}

    monkeypatch.setattr(leave_approval.erp_client, "get_team_pending_leaves", _pending)
    monkeypatch.setattr(leave_approval.erp_client, "approve_leave_request", _approve)
    return approved


def extraction(monkeypatch, name=None, rid=None):
    monkeypatch.setattr(leave_approval.ai_service, "extract_leave_approval_fields",
                        AsyncMock(return_value=(
                            {"action": "approve", "leave_request_id": rid,
                             "employee_id": None, "employee_name": name,
                             "uses_pronoun": False, "targets_multiple": False}, None)))


def state(query):
    return {"query": query, "intent": "leave_approval", "usage_events": [],
            "bearer_token": "t", "company_id": 1, "conversation_id": "conv-1",
            "is_manager": True}


class TestTheLeaveTypeNarrowsTheChoice:

    async def test_the_named_type_is_picked_without_asking(self, monkeypatch, action_store):
        """ABC Testing has a sick AND a casual request pending. "approve abc
        testing sick leave" says which, so the table is not the answer."""
        serve(monkeypatch, [SICK, CASUAL])
        extraction(monkeypatch, name="ABC Testing")

        writer = FakeWriter()
        result = await leave_approval_node(
            state("approve abc testing sick leave"), writer)

        assert len(writer.of_type("leave_approval_confirmation")) == 1
        assert "Sick Leave" in result["response_text"]
        assert "Which one should I approve" not in result["response_text"]
        assert action_store[("1", "conv-1")]["leave_request_id"] == 400

    async def test_the_other_type_picks_the_other_request(self, monkeypatch, action_store):
        serve(monkeypatch, [SICK, CASUAL])
        extraction(monkeypatch, name="ABC Testing")

        await leave_approval_node(state("approve abc testing casual leave"), FakeWriter())

        assert action_store[("1", "conv-1")]["leave_request_id"] == 401

    async def test_no_type_still_asks_which_one(self, monkeypatch):
        """Narrowing only applies when a type was actually named."""
        serve(monkeypatch, [SICK, CASUAL])
        extraction(monkeypatch, name="ABC Testing")

        writer = FakeWriter()
        result = await leave_approval_node(state("approve abc testing"), writer)

        assert "Which one should I approve" in result["response_text"]
        assert writer.of_type("leave_approval_confirmation") == []

    async def test_a_type_matching_two_requests_still_asks(self, monkeypatch):
        """Naming a type that narrows to two has resolved nothing."""
        serve(monkeypatch, [SICK, {**SICK, "id": 402, "from_date": "2026-09-28",
                                   "to_date": "2026-09-28"}])
        extraction(monkeypatch, name="ABC Testing")

        writer = FakeWriter()
        result = await leave_approval_node(
            state("approve abc testing sick leave"), writer)

        assert "Which one should I approve" in result["response_text"]

    async def test_narrowing_still_only_proposes(self, monkeypatch):
        approved = serve(monkeypatch, [SICK, CASUAL])
        extraction(monkeypatch, name="ABC Testing")

        await leave_approval_node(state("approve abc testing sick leave"), FakeWriter())

        assert approved == [], "narrowing must not approve anything by itself"


class TestReAimingTheConfirmationCard:

    @pytest.fixture
    async def card_for_310(self, monkeypatch, action_store):
        serve(monkeypatch, [OTHER_PERSON])
        extraction(monkeypatch, rid=310)
        await leave_approval_node(state("approve 310"), FakeWriter())
        assert action_store[("1", "conv-1")]["leave_request_id"] == 310
        return action_store

    async def test_a_bare_request_id_re_aims_the_card(self, monkeypatch, card_for_310):
        """"400" at the card is the manager pointing at a different request -
        it must be looked up, not answered from conversation history."""
        serve(monkeypatch, [SICK])
        extraction(monkeypatch)   # the extractor returns nothing

        writer = FakeWriter()
        await leave_approval_node(state("400"), writer)

        assert len(writer.of_type("leave_approval_confirmation")) == 1
        assert card_for_310[("1", "conv-1")]["leave_request_id"] == 400

    async def test_a_bare_name_re_aims_the_card(self, monkeypatch, card_for_310):
        serve(monkeypatch, [SICK])
        extraction(monkeypatch)

        writer = FakeWriter()
        result = await leave_approval_node(state("abc testing"), writer)

        assert len(writer.of_type("leave_approval_confirmation")) == 1
        assert "ABC Testing" in result["response_text"]

    @pytest.mark.parametrize("reply", ["400", "#400", "request 400", "abc testing"])
    async def test_these_all_route_back_to_approval(self, monkeypatch, card_for_310, reply):
        assert leave_approval.resolve_pending_approval_intent(1, "conv-1", reply) == \
            leave_approval.APPROVAL_INTENT

    async def test_re_aiming_executes_nothing(self, monkeypatch, card_for_310):
        approved = serve(monkeypatch, [SICK])
        extraction(monkeypatch)

        await leave_approval_node(state("400"), FakeWriter())

        assert approved == []

    @pytest.mark.parametrize("reply", [
        "yes", "no", "cancel", "what happens if I approve?", "thanks",
    ])
    def test_answers_to_the_card_are_not_re_aims(self, reply):
        """A yes, a no, and a question are answers to the card - they must
        keep their own handling rather than being read as a new target."""
        assert leave_approval._looks_like_a_target_reply(reply) is False

    @pytest.mark.parametrize("reply", ["400", "#400", "request 400", "abc testing", "geo3"])
    def test_ids_and_names_are_target_replies(self, reply):
        assert leave_approval._looks_like_a_target_reply(reply) is True
