"""Confirming the card, by button or by typing.

Reported: "yes approve 265" raised the confirmation card for request 265, and
confirming it showed the SAME card again instead of approving. Repeatedly.

Cause: _is_affirmative refuses any message that names a target, so that
"yes, approve Priya's instead" is read as a re-aim rather than as a yes. That
is right in general and must stay - but it could not tell a re-aim from a
manager restating the request they are already looking at. "yes approve 265",
against a card proposing to approve 265, named a target and so was never a
confirmation; it fell through to be re-read as a fresh instruction, which
built the same card again.

The manager can also just press the card's Approve button, which arrives as
its label ("Approve" / "Approve Request") - the same path, and equally not a
re-aim.

What must NOT change: a genuine re-aim at another request, a decline, and a
question all still refuse to execute. Those are pinned below alongside the
confirmations, because the whole risk of widening "what counts as yes" is
approving something the manager did not mean.
"""

import pytest

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


CARD_ROW = {
    "id": 265, "employee_id": 3735, "employee_name": "Ayush Jio",
    "employee_number": "geo3", "employee_designation": "IT",
    "leave_type": "Casual Leave", "leave_type_slug": "casual_leave",
    "session_type": "Full Day", "from_date": "2026-09-19",
    "to_date": "2026-09-19", "leave_count": "1", "status_name": "pending",
    "reason": "going out", "applied_date": "2026-09-08",
}

PENDING = {
    "step": "awaiting_confirmation",
    "action": "approve",
    "leave_request_id": 265,
    "card": {"employee_name": "Ayush Jio", "employee_number": "geo3",
             "leave_request_id": 265, "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))
    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 _audit(monkeypatch):
    import services.audit_log_service as audit_log_service
    monkeypatch.setattr(audit_log_service, "_write", lambda **fields: None)


@pytest.fixture(autouse=True)
def _no_live_extraction(monkeypatch):
    """A reply that is NOT a confirmation falls through to be re-read as a
    fresh instruction, which calls the LLM extractor. Stubbed to nothing so
    these tests never touch the network - and so "approved nothing" is proved
    by the approval path, not by an API call happening to fail."""
    async def _extract(query, today):
        return {"action": None, "leave_request_id": None, "employee_id": None,
                "employee_name": None, "uses_pronoun": False,
                "targets_multiple": False}, None
    monkeypatch.setattr(leave_approval.ai_service,
                        "extract_leave_approval_fields", _extract)


@pytest.fixture
def approved(monkeypatch):
    """Records every erp-api approval actually executed."""
    calls = []

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

    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": 3735, "employee_name": "Ayush Jio"},
            "total_pending_leaves": 1, "leaves": [CARD_ROW]}}}

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


@pytest.fixture
def armed(action_store):
    """The card from the report, already on screen and awaiting a yes."""
    action_store[("1", "conv-1")] = dict(PENDING, kind=leave_approval.CARD_KIND)
    return action_store


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


# =============================================================================
# Confirmations - typed and clicked
# =============================================================================

CONFIRMING = [
    # the forms that already worked
    "yes", "Yes", "ok", "confirm", "yes please", "yes, approve it",
    # the card's own button label, however the client spells it
    "Approve", "approve", "Approve Request", "APPROVE",
    # typed instructions that restate the card
    "yes approve", "yes approve 265", "approve 265", "approve request 265",
    "approve this request", "approve it",
    # the card's own employee, by name and by code
    "approve Ayush Jio", "approve geo3", "approve Ayush Jio's request",
]


class TestConfirmingTheCard:

    @pytest.mark.parametrize("reply", CONFIRMING)
    async def test_it_executes_the_approval(self, armed, approved, reply):
        writer = FakeWriter()
        await leave_approval_node(state(reply), writer)

        assert approved == [265], f"{reply!r} should have approved request 265"

    @pytest.mark.parametrize("reply", CONFIRMING)
    async def test_the_card_is_not_shown_again(self, armed, approved, reply):
        """The reported symptom, stated directly."""
        writer = FakeWriter()
        result = await leave_approval_node(state(reply), writer)

        assert "Please confirm this action" not in result["response_text"]

    async def test_the_reported_turn_exactly(self, armed, approved):
        """'yes approve 265' against the card raised by 'yes approve 265'."""
        writer = FakeWriter()
        result = await leave_approval_node(state("yes approve 265"), writer)

        assert approved == [265]
        assert len(writer.of_type("leave_approval_success")) == 1
        assert "Please confirm this action" not in result["response_text"]

    async def test_the_pending_card_is_cleared_after_executing(self, armed, approved):
        await leave_approval_node(state("Approve"), FakeWriter())

        assert armed.get(("1", "conv-1")) is None, \
            "a confirmed card must not stay armed for the next message"


# =============================================================================
# What must still NOT execute
# =============================================================================

class TestNothingElseExecutes:

    @pytest.mark.parametrize("reply", [
        "no", "No", "nope", "cancel", "don't approve", "not yet", "hold off",
    ])
    async def test_declines_leave_it_pending(self, armed, approved, reply):
        writer = FakeWriter()
        result = await leave_approval_node(state(reply), writer)

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

    @pytest.mark.parametrize("reply", [
        "did you approve it?", "what happens if I approve?",
        "can you approve this?", "how do I approve?",
    ])
    async def test_questions_never_execute(self, armed, approved, reply):
        """A question about approving is not an instruction to approve."""
        await leave_approval_node(state(reply), FakeWriter())

        assert approved == []

    @pytest.mark.parametrize("reply,pending_id", [
        ("approve 261", 261),
        ("approve request 99", 99),
    ])
    def test_another_request_id_is_a_re_aim_not_a_confirmation(self, reply, pending_id):
        """Confirming must never be inferred for a request the card is not
        about - that is the whole reason _is_affirmative refuses targets."""
        assert leave_approval._identifies_another_request(reply, PENDING) is True
        assert leave_approval._confirms_the_card_on_screen(reply, PENDING) is False

    @pytest.mark.parametrize("reply", [
        "approve Priya's instead", "approve Ayush Chandra", "approve Rahul",
    ])
    def test_another_person_is_a_re_aim(self, reply):
        """'Ayush Chandra' against a card for 'Ayush Jio' is somebody else -
        a shared first name is not a match."""
        assert leave_approval._identifies_another_request(reply, PENDING) is True
        assert leave_approval._confirms_the_card_on_screen(reply, PENDING) is False

    @pytest.mark.parametrize("reply", ["reject", "reject it", "deny this"])
    def test_the_opposite_verb_is_not_a_confirmation(self, reply):
        """Saying "reject" to an APPROVE card must not approve it."""
        assert leave_approval._confirms_the_card_on_screen(reply, PENDING) is False

    async def test_the_opposite_verb_approves_nothing(self, armed, approved):
        await leave_approval_node(state("reject"), FakeWriter())
        assert approved == []


# =============================================================================
# The pieces, directly
# =============================================================================

class TestIdentifiesAnotherRequest:

    @pytest.mark.parametrize("reply", [
        "approve", "Approve Request", "approve it", "approve this request",
        "approve 265", "approve request 265", "yes approve 265",
        "approve Ayush Jio", "approve geo3",
    ])
    def test_these_all_mean_the_card_on_screen(self, reply):
        assert leave_approval._identifies_another_request(reply, PENDING) is False

    def test_a_digit_inside_an_employee_code_is_not_a_request_id(self):
        """'geo3' contains a 3. Reading it as request 3 sent the turn looking
        for a different request instead of confirming the card."""
        assert leave_approval._identifies_another_request("approve geo3", PENDING) is False

    def test_a_standalone_number_still_counts(self):
        assert leave_approval._identifies_another_request("approve 3", PENDING) is True
