"""A date or a leave type typed at the confirmation card.

Reported: an approve card was on screen for Rudraveer and the manager typed
"21 Sept 2026". The reply came back as a grey bubble with no intent behind
it:

    For Rudraveer, the leave request on 21 Sept 2026 is Casual Leave, not
    Sick Leave. Please confirm the action: ... Shall I approve this Casual
    Leave request? Reply "yes" to approve, or "no" to leave it pending.

The chat model had written a confirmation card in PROSE. No card event, no
intent, nothing armed, nothing fetched - a "yes" after it would have found no
pending action at all. The date named no request directly, so it was not
recognised as a re-aim and fell through to general classification.

A date, a leave type, a day count and an ordinal now all resolve the same way
they do when answering the "which of these?" table - by SEARCHING the pending
requests. The card's own employee is searched first (an identical date on
somebody else's request must not make the obvious reading ambiguous), then
the wider team.

Nothing is ever picked out of ambiguity: two matches re-offer the table.
"""

import pytest
from unittest.mock import AsyncMock

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


RUD_SICK = {
    "id": 500, "employee_id": 900, "employee_number": "r1",
    "employee_name": "Rudraveer", "employee_designation": "IT",
    "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
    "session_type": "Full Day", "from_date": "2026-09-18",
    "to_date": "2026-09-18", "leave_count": "1", "status_name": "pending",
    "reason": "unwell", "applied_date": "2026-09-10",
}
RUD_CASUAL = {**RUD_SICK, "id": 501, "leave_type": "Casual Leave",
              "leave_type_slug": "casual_leave", "from_date": "2026-09-21",
              "to_date": "2026-09-21", "reason": "family"}
KHAN_SHORT = {**RUD_SICK, "id": 600, "employee_id": 692, "employee_number": "em6",
              "employee_name": "A Khan Test", "leave_type": "Short Leave",
              "leave_type_slug": "short_leave", "from_date": "2026-09-16",
              "to_date": "2026-09-16"}

#: The card on screen: Rudraveer's SICK leave.
CARD = {
    "kind": leave_approval.CARD_KIND, "step": "awaiting_confirmation",
    "action": "approve", "leave_request_id": 500,
    "card": {"employee_name": "Rudraveer", "employee_number": "r1",
             "employee_id": 900, "leave_request_id": 500, "action": "approve"},
}


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))
    monkeypatch.setattr(leave_approval.leave_slot_service, "get_report_state",
                        lambda c, k: None)
    monkeypatch.setattr(leave_approval.leave_slot_service, "set_report_state",
                        lambda c, k, v: True)
    return store


@pytest.fixture(autouse=True)
def erp(monkeypatch):
    """erp-api narrows by employee_id when given one, exactly as live."""
    approved = []

    async def _pending(token, company_id=None, conversation_id=None,
                       employee_id=None, employee_name=None):
        everyone = [RUD_SICK, RUD_CASUAL, KHAN_SHORT]
        rows = ([r for r in everyone if r["employee_id"] == employee_id]
                if employee_id is not None else everyone)
        return {"http_status": 200, "body": {"success": True, "data": {
            "employee": {"employee_id": 900, "employee_name": "Rudraveer"},
            "total_pending_leaves": len(rows), "leaves": 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)
    monkeypatch.setattr(leave_approval.ai_service, "extract_leave_approval_fields",
                        AsyncMock(return_value=(
                            {"action": None, "leave_request_id": None,
                             "employee_id": None, "employee_name": None,
                             "uses_pronoun": False, "targets_multiple": False}, None)))
    return approved


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
def armed(action_store):
    action_store[("1", "conv-1")] = dict(CARD)
    return action_store


# =============================================================================
# The detector
# =============================================================================

class TestWhatCountsAsASearchReply:

    @pytest.mark.parametrize("reply", [
        "21 Sept 2026", "21 sep", "2026-09-21", "16/09",
        "casual leave", "sick leave", "short leave", "casual",
    ])
    def test_dates_and_leave_types_are_search_replies(self, reply):
        assert leave_approval._looks_like_a_search_reply(reply) is True

    @pytest.mark.parametrize("reply", [
        "yes", "no", "cancel", "ok", "what happens if I approve?",
        "did you approve it?", "", "   ",
    ])
    def test_answers_to_the_card_are_not_search_replies(self, reply):
        """A yes, a no and a question keep their own handling."""
        assert leave_approval._looks_like_a_search_reply(reply) is False


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

class TestADateReAimsTheCard:

    @pytest.mark.parametrize("reply", ["21 Sept 2026", "21 sep", "2026-09-21"])
    async def test_the_date_finds_that_days_request(self, armed, reply):
        """The card was Rudraveer's SICK leave on the 18th; the 21st is his
        CASUAL leave. The date has to move the card."""
        writer = FakeWriter()
        result = await leave_approval_node(state(reply), writer)

        assert len(writer.of_type("leave_approval_confirmation")) == 1
        assert armed[("1", "conv-1")]["leave_request_id"] == 501
        assert "Casual Leave" in result["response_text"]

    async def test_a_real_card_event_is_emitted_not_prose(self, armed):
        """The bug was an answer that LOOKED like a card. A card event and an
        armed action are what make it real."""
        writer = FakeWriter()
        await leave_approval_node(state("21 Sept 2026"), writer)

        assert writer.of_type("leave_approval_confirmation"), "no card event"
        assert armed[("1", "conv-1")]["step"] == "awaiting_confirmation"

    async def test_the_turn_routes_back_to_approval(self, armed):
        assert leave_approval.resolve_pending_approval_intent(
            1, "conv-1", "21 Sept 2026") == leave_approval.APPROVAL_INTENT

    async def test_then_yes_approves_the_request_that_was_shown(self, armed, erp):
        """End to end - and proof the card was real: the yes lands on 501,
        not on the 500 that was showing before."""
        await leave_approval_node(state("21 Sept 2026"), FakeWriter())
        await leave_approval_node(state("yes"), FakeWriter())

        assert erp == [501]

    async def test_searching_alone_approves_nothing(self, armed, erp):
        await leave_approval_node(state("21 Sept 2026"), FakeWriter())
        assert erp == []


class TestALeaveTypeReAimsTheCard:

    async def test_a_type_this_employee_has(self, armed):
        writer = FakeWriter()
        await leave_approval_node(state("casual leave"), writer)

        assert armed[("1", "conv-1")]["leave_request_id"] == 501

    async def test_the_cards_own_type_keeps_the_card(self, armed):
        writer = FakeWriter()
        await leave_approval_node(state("sick leave"), writer)

        assert armed[("1", "conv-1")]["leave_request_id"] == 500

    async def test_a_type_only_someone_else_has_widens_to_the_team(self, armed):
        """Rudraveer has no short leave; A Khan Test does. Scoping to the
        card's employee first must not stop the search there."""
        writer = FakeWriter()
        result = await leave_approval_node(state("short leave"), writer)

        assert armed[("1", "conv-1")]["leave_request_id"] == 600
        assert "A Khan Test" in result["response_text"]


class TestAmbiguityIsNeverGuessed:

    async def test_a_date_matching_nothing_re_offers_the_list(self, armed, erp):
        writer = FakeWriter()
        result = await leave_approval_node(state("31 dec 2026"), writer)

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

    async def test_a_type_shared_by_two_requests_re_offers_the_list(
            self, armed, monkeypatch, erp):
        twin = {**RUD_CASUAL, "id": 502, "from_date": "2026-09-29",
                "to_date": "2026-09-29"}

        async def _pending(token, company_id=None, conversation_id=None,
                           employee_id=None, employee_name=None):
            rows = [RUD_CASUAL, twin]
            return {"http_status": 200, "body": {"success": True, "data": {
                "employee": {"employee_id": 900, "employee_name": "Rudraveer"},
                "total_pending_leaves": len(rows), "leaves": rows}}}
        monkeypatch.setattr(leave_approval.erp_client, "get_team_pending_leaves", _pending)

        result = await leave_approval_node(state("casual leave"), FakeWriter())

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

    async def test_yes_and_no_are_untouched_by_all_of_this(self, armed, erp):
        """The card's own answers must still mean what they always meant."""
        await leave_approval_node(state("yes"), FakeWriter())
        assert erp == [500]

    async def test_no_still_leaves_it_pending(self, armed, erp):
        result = await leave_approval_node(state("no"), FakeWriter())

        assert erp == []
        assert "Nothing has been changed" in result["response_text"]
