"""A slightly-wrong name should find the right person - or offer the team.

Reported: the employee is "A Khan Test"; the manager typed "approve akhan"
(no space) and got

    "Pending leave request was not found in your team."

erp-api matches the employee_name field exactly, and the roster fallback in
_resolve_from_roster only did a plain substring test - "akhan" is not a
substring of "a khan test", because the space is in the way. So a one-space
typo dead-ended a request the manager plainly owns.

Two changes, both asked for:

1. NEAREST-NAME MATCHING. Spacing first (the common case), then per-word
   prefixes, then a similarity score for real misspellings.
2. NO DEAD END. A term that still matches nobody is answered with the
   caller's own team to pick from, instead of a refusal with nothing to act
   on next.

The safety line these must not cross is the one the refusal was protecting:
nothing may be approved, and nothing may be revealed about the person who was
actually named. erp-api returns the same search_matched=false WITH the same
roster for gibberish, a typo, and a real employee on another manager's team,
so showing that roster distinguishes none of them - which is why
individual_report.py's read path already does it.
"""

import pytest

import services.individual_report as individual_report
import services.leave_approval as leave_approval
from services.leave_approval import leave_approval_node


ROSTER = [
    {"employee_id": 692, "employee_number": "em6", "employee_name": "A Khan Test",
     "employee_designation": "IT"},
    {"employee_id": 3735, "employee_number": "geo3", "employee_name": "Ayush Jio",
     "employee_designation": "IT"},
    {"employee_id": 3777, "employee_number": "ac1", "employee_name": "Ayush Chandra",
     "employee_designation": "N/A"},
    {"employee_id": 489, "employee_number": "test07", "employee_name": "ABC Testing",
     "employee_designation": "Selenium"},
]

PENDING_ROW = {
    "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",
}


def names_of(rows):
    return [r["employee_name"] for r in rows]


# =============================================================================
# 1 - The matcher
# =============================================================================

class TestNearestNameMatching:

    @pytest.mark.parametrize("typed,expected", [
        # the reported typo, and the shapes around it
        ("akhan", "A Khan Test"),
        ("a khan", "A Khan Test"),
        ("akhantest", "A Khan Test"),
        ("a khan test", "A Khan Test"),
        ("khan", "A Khan Test"),
        ("ayushjio", "Ayush Jio"),
        ("abctesting", "ABC Testing"),
        # real misspellings
        ("kahn", "A Khan Test"),
        ("ayus jio", "Ayush Jio"),
    ])
    def test_a_near_name_resolves_to_that_person(self, typed, expected):
        assert names_of(individual_report._resolve_from_roster(typed, ROSTER)) == [expected]

    def test_an_employee_number_still_wins_outright(self):
        assert names_of(individual_report._resolve_from_roster("em6", ROSTER)) == \
            ["A Khan Test"]

    def test_a_shared_first_name_offers_both(self):
        """"ayush" is genuinely ambiguous here - both are returned so the
        caller is asked, which is what the selection card is for."""
        assert names_of(individual_report._resolve_from_roster("ayush", ROSTER)) == \
            ["Ayush Jio", "Ayush Chandra"]

    @pytest.mark.parametrize("typed", ["zzzz", "rahul", "someone else", "qqq"])
    def test_a_name_that_is_nobody_matches_nobody(self, typed):
        assert individual_report._resolve_from_roster(typed, ROSTER) == []

    def test_an_unknown_code_is_never_matched_to_a_name(self):
        """A term with a digit is an identifier and resolves exactly or not
        at all. "geo99" once scored 0.75 against the name token "Geo" and was
        offered as "B Geo" - a code for nobody, answered with somebody."""
        roster = ROSTER + [{"employee_id": 1, "employee_number": "geo6",
                            "employee_name": "B Geo"}]
        assert individual_report._resolve_from_roster("geo99", roster) == []
        assert names_of(individual_report._resolve_from_roster("geo6", roster)) == ["B Geo"]

    @pytest.mark.parametrize("typed,expected", [
        ("rudraveer1111", "Rudraveer"),
        ("abctesting11", "ABC Testing"),
        ("akhantest2", "A Khan Test"),
        ("ayushjio9", "Ayush Jio"),
    ])
    def test_a_whole_name_with_junk_digits_still_resolves(self, typed, expected):
        """Reported: "rudraveer1111" is Rudraveer with noise on the end.
        Refusing it sent the turn to the chat model, which answered about
        Rudraveer anyway - correctly, but with no intent and no card."""
        roster = ROSTER + [{"employee_id": 233, "employee_number": "FNF-004",
                            "employee_name": "Rudraveer"}]
        assert names_of(individual_report._resolve_from_roster(typed, roster)) == [expected]

    @pytest.mark.parametrize("typed", ["geo99", "test99", "em99", "abc99", "xyz123"])
    def test_an_identifier_shaped_term_still_resolves_to_nobody(self, typed):
        """The exception is EXACT full names only. "geo99" reduces to "geo",
        which is a token of "B Geo" but not that person's whole name - so the
        identifier rule that stopped it being offered as "B Geo" still
        holds."""
        roster = ROSTER + [{"employee_id": 1, "employee_number": "geo6",
                            "employee_name": "B Geo"}]
        assert individual_report._resolve_from_roster(typed, roster) == []

    def test_an_exact_full_name_wins_outright(self):
        """Reported: on a roster holding both "Ayush" and "Ayush Chandra",
        typing "Ayush" came back with every Ayush - so the manager was asked
        to choose between people, one of whom they had just named in full.
        A name that IS somebody's whole name is not ambiguous, whoever else
        happens to contain it."""
        roster = [
            {"employee_id": 1, "employee_number": "a1", "employee_name": "Ayush"},
            {"employee_id": 2, "employee_number": "a2", "employee_name": "Ayush Chandra"},
            {"employee_id": 3, "employee_number": "a3", "employee_name": "Ayush Jio"},
        ]
        assert names_of(individual_report._resolve_from_roster("Ayush", roster)) == ["Ayush"]
        assert names_of(individual_report._resolve_from_roster("ayush", roster)) == ["Ayush"]

    def test_a_partial_name_is_still_ambiguous(self):
        """Only an EXACT match short-circuits - "Ayu" matches all three and
        must still ask."""
        roster = [
            {"employee_id": 1, "employee_number": "a1", "employee_name": "Ayush"},
            {"employee_id": 2, "employee_number": "a2", "employee_name": "Ayush Chandra"},
        ]
        assert len(individual_report._resolve_from_roster("Ayu", roster)) == 2

    def test_two_real_namesakes_still_ask(self):
        """Two colleagues with the same full name ARE ambiguous."""
        twins = [
            {"employee_id": 1, "employee_number": "t1", "employee_name": "Ayush"},
            {"employee_id": 2, "employee_number": "t2", "employee_name": "Ayush"},
        ]
        assert len(individual_report._resolve_from_roster("Ayush", twins)) == 2

    def test_two_letters_are_not_evidence(self):
        """A fragment that short matches far too much to mean anything."""
        assert individual_report._nearest_roster_matches("ak", ROSTER) == []

    def test_different_people_are_kept_apart(self):
        """The whole risk of fuzzy matching: offering the wrong colleague."""
        assert "Ayush Jio" not in names_of(
            individual_report._resolve_from_roster("akhan", ROSTER))
        assert "A Khan Test" not in names_of(
            individual_report._resolve_from_roster("ayus jio", ROSTER))

    def test_an_empty_term_matches_nobody(self):
        assert individual_report._resolve_from_roster("", ROSTER) == []
        assert individual_report._resolve_from_roster("akhan", []) == []


# =============================================================================
# 2 - The approve path, end to end
# =============================================================================

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


@pytest.fixture
def erp(monkeypatch):
    """erp-api's real shape: a name it cannot match comes back
    search_matched=false WITH the whole roster attached."""
    approved = []

    async def _pending(token, company_id=None, conversation_id=None,
                       employee_id=None, employee_name=None):
        if employee_id is not None:
            return {"http_status": 200, "body": {"success": True, "data": {
                "employee": {"employee_id": 692, "employee_name": "A Khan Test"},
                "total_pending_leaves": 1, "leaves": [PENDING_ROW]}}}
        return {"http_status": 200, "body": {"success": True, "data": {
            "action_required": "select_employee", "search_matched": False,
            "employees": list(ROSTER)}}}

    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, employee_name):
    async def _extract(query, today):
        return {"action": "approve", "leave_request_id": None, "employee_id": None,
                "employee_name": employee_name, "uses_pronoun": False,
                "targets_multiple": False}, None
    monkeypatch.setattr(leave_approval.ai_service,
                        "extract_leave_approval_fields", _extract)


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 TestApprovingWithATypo:

    async def test_the_reported_turn_reaches_the_right_person(self, monkeypatch, erp):
        """'approve akhan' for 'A Khan Test'."""
        extraction(monkeypatch, "akhan")

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

        assert len(writer.of_type("leave_approval_confirmation")) == 1
        assert "A Khan Test" in result["response_text"]
        assert "not found in your team" not in result["response_text"]

    async def test_it_still_only_proposes(self, monkeypatch, erp):
        extraction(monkeypatch, "akhan")
        await leave_approval_node(state("approve akhan"), FakeWriter())

        assert erp == [], "a fuzzy name match must not approve anything by itself"


class TestAnUnknownNameOffersTheTeam:

    async def test_the_team_is_listed(self, monkeypatch, erp):
        extraction(monkeypatch, "zzzz")

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

        answer = result["response_text"]
        assert "No employee matched that name" in answer
        for employee in ROSTER:
            assert employee["employee_name"] in answer

    async def test_the_selection_event_carries_the_rows(self, monkeypatch, erp):
        extraction(monkeypatch, "zzzz")

        writer = FakeWriter()
        await leave_approval_node(state("approve zzzz"), writer)

        offered = writer.of_type("employee_selection")
        assert len(offered) == 1
        assert offered[0]["data"]["search_matched"] is False
        assert len(offered[0]["data"]["employees"]) == len(ROSTER)

    async def test_the_shortlist_is_armed_so_a_reply_resolves(self, monkeypatch, erp, action_store):
        extraction(monkeypatch, "zzzz")
        await leave_approval_node(state("approve zzzz"), FakeWriter())

        pending = action_store[("1", "conv-1")]
        assert pending["step"] == "awaiting_employee_selection"
        assert pending["action"] == "approve"

    async def test_picking_from_the_list_then_works(self, monkeypatch, erp):
        """The point of listing them: the manager can finish the job."""
        extraction(monkeypatch, "zzzz")
        await leave_approval_node(state("approve zzzz"), FakeWriter())

        writer = FakeWriter()
        result = await leave_approval_node(state("A Khan Test"), writer)

        assert len(writer.of_type("leave_approval_confirmation")) == 1
        assert "A Khan Test" in result["response_text"]

    async def test_nothing_is_approved_and_the_name_is_not_confirmed(self, monkeypatch, erp):
        """The line the old refusal was drawn to protect: an unknown name
        must approve nothing and must not tell the caller whether that person
        exists."""
        extraction(monkeypatch, "Rahul")

        writer = FakeWriter()
        result = await leave_approval_node(state("approve Rahul's leave"), writer)

        assert erp == []
        assert "Rahul" not in result["response_text"]

    async def test_an_unmatched_term_is_never_auto_resolved(self, monkeypatch, erp):
        """Even onto a one-person team: acting on somebody the manager never
        named is worse than asking."""
        async def _one_person(token, company_id=None, conversation_id=None,
                              employee_id=None, employee_name=None):
            return {"http_status": 200, "body": {"success": True, "data": {
                "action_required": "select_employee", "search_matched": False,
                "employees": [ROSTER[0]]}}}
        monkeypatch.setattr(leave_approval.erp_client, "get_team_pending_leaves", _one_person)
        extraction(monkeypatch, "zzzz")

        writer = FakeWriter()
        await leave_approval_node(state("approve zzzz"), writer)

        assert writer.of_type("leave_approval_confirmation") == []
        assert len(writer.of_type("employee_selection")) == 1
