"""Answering "which of these requests?" - by ID, date, leave type or position.

Reported (conversation 7d43426b):

    manager:  show my team pending leave request   -> the team card, 3 rows
    manager:  approve a khan                       -> A Khan Test has TWO
              pending, so the table is shown: #308 Casual 01-02 Sep, #310
              Short 16 Sep
    manager:  310                                  -> intent general_hr,
              answer "Approve request 310."

310 is that request's own ID, printed in the table's first column. Nothing
was approved; the chat model simply restated the message, because showing the
table stored NO state - so the reply arrived with no record that a question
had been asked and went to generic classification.

Third instance of the same root cause in this node: a question that does not
write the state its answer resolves against. The other two are covered in
test_leave_approval_target_prompt.py ("which request?") and
test_leave_approval_confirmation_forms.py (confirming the card).

The matcher is deliberately tiered and refuses to guess - a tier matching two
rows resolves nothing and the table is re-offered, because the cost of
guessing is approving the wrong person's leave.
"""

import pytest

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


CASUAL_308 = {
    "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",
}
SHORT_310 = {
    "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": "", "from_date": "2026-09-16",
    "to_date": "2026-09-16", "leave_count": "1", "status_name": "pending",
    "reason": "work", "applied_date": "2026-09-17",
}
BOTH = [CASUAL_308, SHORT_310]


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(autouse=True)
def erp(monkeypatch):
    """A Khan Test's two pending requests, and a recorder for approvals."""
    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": 692, "employee_name": "A Khan Test"},
            "total_pending_leaves": 2, "leaves": list(BOTH)}}}

    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


@pytest.fixture
def names_a_khan(monkeypatch):
    async def _extract(query, today):
        return {"action": "approve", "leave_request_id": None, "employee_id": None,
                "employee_name": "A Khan", "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}


@pytest.fixture
async def table_shown(names_a_khan, action_store):
    """Turn 2 of the report: 'approve a khan' -> the two-row table."""
    writer = FakeWriter()
    result = await leave_approval_node(state("approve a khan"), writer)
    return result, action_store


# =============================================================================
# 1 - Showing the table remembers it
# =============================================================================

class TestTheTableIsRemembered:

    async def test_the_table_is_still_shown(self, table_shown):
        result, _ = table_shown
        assert "Which one should I approve" in result["response_text"]
        assert "#308" in result["response_text"]
        assert "#310" in result["response_text"]

    async def test_the_offered_rows_are_stored(self, table_shown):
        _, store = table_shown
        pending = store[("1", "conv-1")]

        assert pending["step"] == "awaiting_leave_choice"
        assert pending["kind"] == leave_approval.CARD_KIND
        assert [lv["id"] for lv in pending["leaves"]] == [308, 310]

    async def test_the_action_survives_the_question(self, table_shown):
        _, store = table_shown
        assert store[("1", "conv-1")]["action"] == "approve"

    async def test_the_structured_rows_still_ride_along(self, table_shown):
        """The client can draw its own table; that payload is unchanged."""
        result, _ = table_shown
        assert "Which one should I approve" in result["response_text"]


# =============================================================================
# 2 - The reply is understood, however it is phrased
# =============================================================================

class TestTheReplyResolves:

    @pytest.mark.parametrize("reply,expected", [
        # the reported turn - the ID straight out of the table
        ("310", 310),
        ("308", 308),
        ("#310", 310),
        ("request 310", 310),
        ("approve request 308", 308),
        # by date
        ("16 sep", 310),
        ("2026-09-16", 310),
        ("16/09", 310),
        ("1 sep", 308),
        ("2026-09-02", 308),
        # by leave type
        ("short leave", 310),
        ("short", 310),
        ("casual leave", 308),
        ("casual", 308),
        # by day count
        ("2 days", 308),
        # by position
        ("the second one", 310),
        ("first one", 308),
    ])
    def test_the_matcher_picks_the_right_row(self, reply, expected):
        chosen = leave_approval._match_leave_choice(reply, BOTH)
        assert chosen is not None, f"{reply!r} resolved nothing"
        assert chosen["id"] == expected

    @pytest.mark.parametrize("reply,expected", [
        ("310", 310), ("16 sep", 310), ("casual", 308), ("the second one", 310),
    ])
    async def test_it_builds_the_confirmation_card(self, table_shown, reply, expected, action_store):
        writer = FakeWriter()
        result = await leave_approval_node(state(reply), writer)

        assert "Please confirm this action" in result["response_text"]
        assert action_store[("1", "conv-1")]["leave_request_id"] == expected
        assert len(writer.of_type("leave_approval_confirmation")) == 1

    async def test_the_reported_turn_exactly(self, table_shown, action_store):
        """'310' after the table - the turn that answered "Approve request
        310." and did nothing."""
        writer = FakeWriter()
        result = await leave_approval_node(state("310"), writer)

        assert action_store[("1", "conv-1")]["leave_request_id"] == 310
        assert "Short Leave" in result["response_text"]
        assert "Please confirm this action" in result["response_text"]

    async def test_the_reply_routes_back_to_this_node(self, table_shown):
        assert leave_approval.resolve_pending_approval_intent(1, "conv-1", "310") == \
            leave_approval.APPROVAL_INTENT

    async def test_choosing_then_confirming_approves_it(self, table_shown, erp):
        """End to end: table -> pick 310 -> yes -> approved."""
        await leave_approval_node(state("310"), FakeWriter())
        await leave_approval_node(state("yes"), FakeWriter())

        assert erp == [310]

    async def test_picking_alone_approves_nothing(self, table_shown, erp):
        """Choosing a row only builds the card - AC3 still stands."""
        await leave_approval_node(state("310"), FakeWriter())

        assert erp == []


# =============================================================================
# 3 - It never guesses
# =============================================================================

class TestARequestNumberThatIsNotOnTheTable:
    """Reported: the table offered #326 and #324, the manager typed "2222",
    and the reply came back as a grey bubble with no intent -

        I couldn't find pending request #2222 for Rudraveer.
        Available pending requests are: ...

    That sentence is nowhere in this codebase. The chat model wrote it,
    because an unmatched reply fell through to general classification - so a
    perfectly reasonable answer arrived with no card behind it and no state
    left to answer against.
    """

    async def test_it_is_answered_by_this_node(self, table_shown):
        assert leave_approval.resolve_pending_approval_intent(
            1, "conv-1", "2222") == leave_approval.APPROVAL_INTENT

    async def test_it_says_which_number_was_not_found(self, table_shown):
        writer = FakeWriter()
        result = await leave_approval_node(state("2222"), writer)

        assert "#2222" in result["response_text"]
        assert "isn't one of" in result["response_text"]

    async def test_the_table_is_shown_again(self, table_shown):
        writer = FakeWriter()
        result = await leave_approval_node(state("2222"), writer)

        assert "Which one should I approve" in result["response_text"]
        assert "#308" in result["response_text"] and "#310" in result["response_text"]

    async def test_the_shortlist_stays_armed_so_a_retry_lands(self, table_shown, action_store):
        """The point of re-offering: the next reply has to resolve."""
        await leave_approval_node(state("2222"), FakeWriter())
        assert action_store[("1", "conv-1")]["step"] == "awaiting_leave_choice"

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

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

    async def test_nothing_is_approved(self, table_shown, erp):
        await leave_approval_node(state("2222"), FakeWriter())
        assert erp == []

    async def test_a_name_is_still_a_re_aim_not_a_retry(self):
        """At this table a NAME means "show me that person instead", so it
        must not be captured as a failed pick."""
        assert leave_approval.resolve_pending_approval_intent(
            1, "conv-1", "what is my leave balance") is None


class TestAmbiguityIsRefused:

    @pytest.mark.parametrize("reply", [
        "999",              # no such request
        "sick leave",       # no such type here
        "31 dec",           # no such date
        "",
        "   ",
    ])
    def test_nothing_matching_resolves_nothing(self, reply):
        assert leave_approval._match_leave_choice(reply, BOTH) is None

    def test_a_type_shared_by_two_rows_resolves_nothing(self):
        """Two casual requests and a reply of "casual" is exactly the
        ambiguity the table exists to clear - it must not be guessed at."""
        twins = [CASUAL_308, {**CASUAL_308, "id": 309, "from_date": "2026-09-10",
                              "to_date": "2026-09-10", "leave_count": "1"}]
        assert leave_approval._match_leave_choice("casual", twins) is None

    def test_a_date_shared_by_two_rows_resolves_nothing(self):
        overlapping = [CASUAL_308, {**SHORT_310, "from_date": "2026-09-01",
                                    "to_date": "2026-09-01"}]
        assert leave_approval._match_leave_choice("1 sep", overlapping) is None

    async def test_an_unmatched_reply_does_not_hijack_the_turn(self, table_shown):
        """A manager who changes the subject gets a normal answer - the
        shortlist simply expires with its TTL."""
        assert leave_approval.resolve_pending_approval_intent(
            1, "conv-1", "what is my leave balance") is None

    def test_a_request_id_beats_a_coincidental_date(self):
        """An explicit ID is the least ambiguous thing a manager can say, so
        it is checked first."""
        chosen = leave_approval._match_leave_choice("308", BOTH)
        assert chosen["id"] == 308

    def test_a_bare_digit_is_never_read_as_a_row_number(self):
        """The table prints request IDs, not positions. Reading "2" as "the
        second row" would approve a request the manager never named."""
        assert leave_approval._match_leave_choice("2", BOTH) is None
