"""The "which request?" question has to be answerable.

Reported: a manager asked to approve a leave request, was asked which one,
typed the team member's name -- and got the identical question back. Three
times, verbatim:

    manager:  a khan test
    Helix AI: Which request would you like me to approve? Tell me the team
              member's name, or the request ID.
    manager:  A khan Test
    Helix AI: Which request would you like me to approve? ...
    manager:  A Khan Test
    Helix AI: Which request would you like me to approve? ...

Two independent causes, both of which had to be fixed for the reply to land:

1. ASKING STORED NOTHING. Every other question this node asks writes a
   manager-action state first (awaiting_confirmation, awaiting_rejection_
   reason, awaiting_employee_selection). This one did not, so the next turn
   arrived with no record that anything had been asked.

2. THE ANSWER WENT BACK THROUGH THE LLM EXTRACTOR.
   extract_leave_approval_fields only ever sees the message text, never the
   question it answers, and is asked for "the team member whose request is
   being acted on". A bare "A Khan Test" has no action verb and no target
   wording, so it came back employee_name=None -> no target -> ask again.

   That extractor also returns its EMPTY field set on any exception, so
   while the LLM was rate-limited the question could not be answered by
   anyone. The answer turn is now read deterministically and never consults
   it -- which is what the no-LLM tests below pin.
"""

import pytest

import services.leave_approval as leave_approval
from services.leave_approval import leave_approval_node, resolve_pending_approval_intent


PENDING_ROW = {
    "id": 61, "employee_id": 4101, "employee_name": "A Khan Test",
    "employee_designation": "IT", "leave_type": "Casual Leave",
    "leave_type_slug": "casual_leave", "from_date": "2026-09-20",
    "to_date": "2026-09-20", "leave_count": "1", "status_name": "pending",
    "reason": "personal", "applied_date": "2026-09-10",
}

THE_QUESTION = ("Which request would you like me to approve? Tell me the team "
                "member's name, or the request ID.")


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 extractor(monkeypatch):
    """The LLM field extractor. Defaults to returning NOTHING -- what it did
    live for a bare name, and what it returns for every failure."""
    calls = []

    async def _extract(query, today):
        calls.append(query)
        return dict(_extract.fields), None

    _extract.fields = {"action": None, "leave_request_id": None, "employee_id": None,
                       "employee_name": None, "uses_pronoun": False,
                       "targets_multiple": False}
    monkeypatch.setattr(leave_approval.ai_service, "extract_leave_approval_fields", _extract)
    _extract.calls = calls
    return _extract


@pytest.fixture
def erp(monkeypatch):
    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": 4101, "employee_name": "A Khan Test"},
            "total_pending_leaves": 1, "leaves": [PENDING_ROW]}}}

    approved = []

    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 state(query):
    return {"query": query, "intent": "leave_approval", "usage_events": [],
            "bearer_token": "t", "company_id": 1, "conversation_id": "conv-1",
            "is_manager": True}


async def ask_which_request(extractor, action="approve"):
    """Turn 1: an approve/reject instruction that names no target."""
    extractor.fields = {**extractor.fields, "action": action}
    writer = FakeWriter()
    result = await leave_approval_node(state(f"{action} leave"), writer)
    extractor.calls.clear()
    return result


# =============================================================================
# 1 - Asking records that it asked
# =============================================================================

class TestTheAskIsRemembered:

    async def test_the_question_is_still_asked(self, extractor, erp):
        result = await ask_which_request(extractor)
        assert result["response_text"] == THE_QUESTION

    async def test_a_pending_target_state_is_written(self, extractor, erp, action_store):
        await ask_which_request(extractor)

        pending = action_store[("1", "conv-1")]
        assert pending["step"] == "awaiting_approval_target"
        assert pending["kind"] == leave_approval.CARD_KIND
        assert pending["action"] == "approve"

    async def test_a_reject_instruction_remembers_reject(
            self, extractor, erp, action_store, monkeypatch):
        """The action must survive the question - the manager said "reject"
        on the turn that raised it and must not have to say it again.

        Rejection is gated OFF by default (LEAVE_REJECTION_ENABLED), so it is
        enabled here exactly as the other reject tests do: with the flag off,
        a reject instruction is answered with REJECTION_UNAVAILABLE_MESSAGE
        before it ever reaches the question this class is about.
        """
        monkeypatch.setattr(leave_approval, "LEAVE_REJECTION_ENABLED", True)
        await ask_which_request(extractor, action="reject")

        assert action_store[("1", "conv-1")]["action"] == "reject"

    async def test_reject_stays_unavailable_while_the_flag_is_off(self, extractor, erp):
        """The default. Asking to reject names where it can be done rather
        than opening a flow the product has switched off."""
        writer = FakeWriter()
        extractor.fields = {**extractor.fields, "action": "reject"}
        result = await leave_approval_node(state("reject leave"), writer)

        assert result["response_text"] == leave_approval.REJECTION_UNAVAILABLE_MESSAGE

    async def test_the_next_turn_routes_back_to_this_node(self, extractor, erp):
        await ask_which_request(extractor)

        assert resolve_pending_approval_intent(1, "conv-1", "A Khan Test") == \
            leave_approval.APPROVAL_INTENT

    async def test_a_question_of_their_own_does_not_hijack_the_turn(self, extractor, erp):
        """"what happens if I reject?" gets a normal answer; the ask stands."""
        await ask_which_request(extractor)

        assert resolve_pending_approval_intent(
            1, "conv-1", "what happens if I reject?") is None

    async def test_an_empty_reply_is_not_an_answer(self, extractor, erp):
        await ask_which_request(extractor)

        assert resolve_pending_approval_intent(1, "conv-1", "   ") is None


# =============================================================================
# 2 - The reported loop
# =============================================================================

class TestTheNameReplyIsAccepted:

    async def test_the_same_question_does_not_come_back(self, extractor, erp):
        """The bug, stated directly."""
        first = await ask_which_request(extractor)

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

        assert second["response_text"] != first["response_text"]
        assert THE_QUESTION not in second["response_text"]

    async def test_the_reply_produces_the_confirmation_card(self, extractor, erp):
        await ask_which_request(extractor)

        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"]

    @pytest.mark.parametrize("reply", ["A Khan Test", "a khan test", "A khan Test"])
    async def test_every_casing_the_manager_tried_works(self, extractor, erp, reply):
        """All three of the screenshot's attempts."""
        await ask_which_request(extractor)

        writer = FakeWriter()
        await leave_approval_node(state(reply), writer)

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

    @pytest.mark.parametrize("reply,expected_id", [
        ("61", 61), ("#61", 61), ("request 61", 61), ("LR-61", 61),
    ])
    def test_a_request_id_reply_is_read_as_an_id_not_a_name(self, reply, expected_id):
        fields = leave_approval._fields_from_target_reply(reply, {"action": "approve"})
        assert fields["leave_request_id"] == expected_id
        assert fields["employee_name"] is None

    def test_a_name_reply_is_read_as_a_name(self):
        fields = leave_approval._fields_from_target_reply(
            "A Khan Test", {"action": "approve"})
        assert fields["employee_name"] == "A Khan Test"
        assert fields["leave_request_id"] is None

    def test_the_remembered_action_is_carried_not_re_read(self):
        """The reply says nothing about approving or rejecting - the stored
        action is the only source."""
        fields = leave_approval._fields_from_target_reply(
            "A Khan Test", {"action": "reject"})
        assert fields["action"] == "reject"


# =============================================================================
# 3 - The answer turn must not depend on the LLM
# =============================================================================

class TestTheAnswerTurnNeedsNoLlm:

    async def test_the_extractor_is_not_consulted_for_the_answer(self, extractor, erp):
        """It returns nothing for a bare name, and returns nothing for every
        failure too - so the turn that must work cannot depend on it."""
        await ask_which_request(extractor)

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

        assert extractor.calls == []

    async def test_it_still_works_when_the_extractor_raises(self, extractor, erp, monkeypatch):
        await ask_which_request(extractor)

        async def _boom(query, today):
            raise RuntimeError("429 Too Many Requests")
        monkeypatch.setattr(leave_approval.ai_service,
                            "extract_leave_approval_fields", _boom)

        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"]


# =============================================================================
# 4 - Nothing is approved without the confirmation step
# =============================================================================

class TestStillNoSilentExecution:

    async def test_answering_the_question_approves_nothing_yet(self, extractor, erp):
        """Naming the person only builds the card - AC3 still stands."""
        await ask_which_request(extractor)

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

        assert erp == [], "no approval may be executed before the manager confirms"

    async def test_the_card_is_what_arms_the_confirmation(self, extractor, erp, action_store):
        await ask_which_request(extractor)
        await leave_approval_node(state("A Khan Test"), FakeWriter())

        pending = action_store[("1", "conv-1")]
        assert pending["step"] == "awaiting_confirmation"
