"""An exactly-typed name is not a question.

Live report: a manager typed "show ayush jio leave request" and was handed a
"Which one did you mean?" card offering **Ayush Chandra** and **Ayush Jio** -
naming, as one of two options, the very person they had just spelled out in
full. Picking Ayush Jio then worked; typing the same full name again brought
the card back.

Cause: erp-api's ?employee_name= search matches on ANY name token, so
searching "ayush jio" returns everyone called Ayush. individual_report_node
offered the whole shortlist whenever it had more than one row, without ever
checking whether one of them was an exact match for what was typed.

The fix narrows to an exact full-name (or employee-number) match before the
card is considered. What must NOT change is the genuinely ambiguous case: a
partial name, a typo, or two real namesakes still get the card, because those
are the ambiguity the card exists for.
"""

import pytest

import services.individual_report as individual_report
import services.erp_client as erp_client


AYUSH_CHANDRA = {"employee_id": 3777, "employee_name": "Ayush Chandra",
                 "employee_number": "ac1", "employee_designation": "N/A"}
AYUSH_JIO = {"employee_id": 3735, "employee_name": "Ayush Jio",
             "employee_number": "geo3", "employee_designation": "IT"}
BOTH = [AYUSH_CHANDRA, AYUSH_JIO]

PENDING_ROW = {
    "id": 113, "employee_id": 3735, "employee_name": "Ayush Jio",
    "employee_designation": "IT", "leave_type": "Sick Leave",
    "leave_type_slug": "sick_leave", "from_date": "2026-08-26",
    "to_date": "2026-08-27", "leave_count": "2", "status_name": "pending",
}


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 _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, s: bool(store.__setitem__((str(c), k), s)) or True)
    monkeypatch.setattr(individual_report.leave_slot_service, "clear_report_state",
                        lambda c, k: store.pop((str(c), k), None))
    return store


def names_it(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)


def search_returns(monkeypatch, candidates, resolved=AYUSH_JIO):
    """erp-api's fuzzy shortlist on a name search; the record on an id fetch."""
    calls = []

    async def _fake(bearer_token, company_id=None, conversation_id=None,
                    employee_id=None, employee_name=None):
        calls.append({"employee_id": employee_id, "employee_name": employee_name})
        if employee_id is None:
            return {"http_status": 200, "body": {"success": True, "data": {
                "action_required": "select_employee", "search_matched": True,
                "employees": list(candidates)}}}
        return {"http_status": 200, "body": {"success": True, "data": {
            "employee": dict(resolved), "total_pending_leaves": 1,
            "leaves": [PENDING_ROW]}}}
    monkeypatch.setattr(erp_client, "get_team_pending_leaves", _fake)
    return calls


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


# =============================================================================
# The matcher
# =============================================================================

class TestExactNameMatcher:

    @pytest.mark.parametrize("term,expected", [
        ("Ayush Jio", ["Ayush Jio"]),
        ("ayush jio", ["Ayush Jio"]),
        ("AYUSH  JIO", ["Ayush Jio"]),
        ("ayush-jio", ["Ayush Jio"]),
        ("Ayush Chandra", ["Ayush Chandra"]),
        ("geo3", ["Ayush Jio"]),
    ])
    def test_an_exact_reference_resolves(self, term, expected):
        matches = individual_report._exact_name_matches(term, BOTH)
        assert [m["employee_name"] for m in matches] == expected

    @pytest.mark.parametrize("term", ["ayush", "jio", "chandra", "ay", "", "   "])
    def test_a_partial_name_resolves_nothing(self, term):
        """"ayush" really is ambiguous between the two - that is what the
        selection card is for, and it must keep getting it."""
        assert individual_report._exact_name_matches(term, BOTH) == []

    def test_two_real_namesakes_stay_ambiguous(self):
        """Two people genuinely called Ayush Jio ARE ambiguous. Returning
        both keeps the card, rather than silently picking whichever row
        erp-api happened to sort first."""
        twins = [AYUSH_JIO, {**AYUSH_JIO, "employee_id": 9999,
                             "employee_number": "geo9"}]
        assert len(individual_report._exact_name_matches("Ayush Jio", twins)) == 2

    def test_no_candidates_is_not_a_match(self):
        assert individual_report._exact_name_matches("Ayush Jio", []) == []


# =============================================================================
# The reported turn
# =============================================================================

class TestTheSelectionCardIsSkippedForAnExactName:

    async def test_the_full_name_goes_straight_to_that_employee(self, monkeypatch):
        names_it(monkeypatch, "Ayush Jio")
        search_returns(monkeypatch, BOTH)

        writer = FakeWriter()
        result = await individual_report.individual_report_node(
            state("show ayush jio leave request"), writer)

        assert writer.of_type("employee_selection") == [], \
            "a name typed in full must not be offered back as a question"
        assert writer.of_type("individual_leave_request"), "the answer card is missing"
        assert "Ayush Jio" in result["response_text"]
        assert "Ayush Chandra" not in result["response_text"]

    async def test_the_record_is_fetched_by_the_resolved_id(self, monkeypatch):
        """Resolving must re-fetch by id, not answer from the shortlist row -
        the shortlist carries no leave data."""
        names_it(monkeypatch, "Ayush Jio")
        calls = search_returns(monkeypatch, BOTH)

        await individual_report.individual_report_node(
            state("show ayush jio leave request"), FakeWriter())

        assert calls[-1]["employee_id"] == 3735

    async def test_no_selection_state_is_left_behind(self, monkeypatch, _report_store):
        """A card that was never shown must not leave a shortlist waiting to
        capture the next turn."""
        names_it(monkeypatch, "Ayush Jio")
        search_returns(monkeypatch, BOTH)

        await individual_report.individual_report_node(
            state("show ayush jio leave request"), FakeWriter())

        pending = [v for v in _report_store.values()
                   if v and v.get("step") == "awaiting_employee_selection"]
        assert pending == []

    async def test_an_employee_number_also_skips_the_card(self, monkeypatch):
        names_it(monkeypatch, "geo3")
        search_returns(monkeypatch, BOTH)

        writer = FakeWriter()
        await individual_report.individual_report_node(
            state("show geo3 leave request"), writer)

        assert writer.of_type("employee_selection") == []
        assert writer.of_type("individual_leave_request")


class TestGenuineAmbiguityStillAsks:

    async def test_a_partial_name_still_offers_the_card(self, monkeypatch):
        names_it(monkeypatch, "Ayush")
        search_returns(monkeypatch, BOTH)

        writer = FakeWriter()
        result = await individual_report.individual_report_node(
            state("show ayush leave request"), writer)

        offered = writer.of_type("employee_selection")
        assert len(offered) == 1, "a partial name is exactly what the card is for"
        assert len(offered[0]["data"]["employees"]) == 2
        assert "which one" in result["response_text"].lower()

    async def test_two_namesakes_still_offer_the_card(self, monkeypatch):
        twins = [AYUSH_JIO, {**AYUSH_JIO, "employee_id": 9999,
                             "employee_number": "geo9"}]
        names_it(monkeypatch, "Ayush Jio")
        search_returns(monkeypatch, twins)

        writer = FakeWriter()
        await individual_report.individual_report_node(
            state("show ayush jio leave request"), writer)

        assert len(writer.of_type("employee_selection")) == 1

    async def test_a_single_fuzzy_hit_is_unchanged(self, monkeypatch):
        """The pre-existing shortcut for a one-person shortlist must keep
        working - this change only narrows shortlists of two or more."""
        names_it(monkeypatch, "Ayush")
        search_returns(monkeypatch, [AYUSH_JIO])

        writer = FakeWriter()
        await individual_report.individual_report_node(
            state("show ayush leave request"), writer)

        assert writer.of_type("employee_selection") == []
        assert writer.of_type("individual_leave_request")
