"""The answer to "Before I move on — you have a leave application in progress
... Would you like to carry on with it, or discard it and I'll answer your
other question?" (2026-10-01, staging).

Live:
  * "discard" / "Discard it" (the chip) matched no discard wording, so
    fast_classify's cancel keyword sent it to the cancel_leave SEARCH flow,
    which listed the employee's pending leaves. The draft stayed open, so the
    very next question got the same "Before I move on" again — stuck.
  * once a bare "discard" fell to the chat model, which answered "I've
    cleared the pending short-leave request" without clearing anything.
  * the held-back question was never answered, though the prompt promises it.
"""
from unittest.mock import AsyncMock

import pytest

import services.classify_node as classify_node
import services.leave_action_service as las
from services import leave_slot_service, slot_store
from services.leave_action_service import is_draft_discard

COMPANY_ID = 4242
DRAFT = {"leave_type": "casual_leave"}


class TestDiscardWording:
    @pytest.mark.parametrize("reply", [
        "discard", "Discard it", "discard it", "DISCARD IT.", "yes, discard it",
        "discard the application", "discard it and answer my question", "please discard it",
        "scrap it", "delete my draft", "discard my leave application",
    ])
    def test_discards_the_draft(self, reply):
        assert is_draft_discard(reply) is True

    @pytest.mark.parametrize("reply", [
        "carry on with it", "Carry on with it", "cancel my leaves", "discard my leaves",
        "show my discarded leaves", "show my last 1 month attendance", "tomorrow",
    ])
    def test_is_not_a_discard(self, reply):
        assert is_draft_discard(reply) is False


@pytest.fixture
def llm_says(monkeypatch):
    def set_label(label):
        async def _no_shift(q):
            return None, 0.0, None

        async def _classify(prompt, labels, fallback_label="unknown"):
            return label, None, False

        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _classify)
    return set_label


@pytest.fixture
def draft(request):
    conv = f"draft-choice-{request.node.name}"
    leave_slot_service.set_slots(COMPANY_ID, conv, dict(DRAFT))
    slot_store.clear_slots(classify_node._HELD_QUESTION_NAMESPACE, COMPANY_ID, conv)
    yield conv
    leave_slot_service.clear_slots(COMPANY_ID, conv)
    slot_store.clear_slots(classify_node._HELD_QUESTION_NAMESPACE, COMPANY_ID, conv)


async def _turn(query, conv, last_intent="apply_leave"):
    return await classify_node.classify_node(
        {"query": query, "company_id": COMPANY_ID, "conversation_id": conv, "bearer_token": "t",
         "usage_events": [], "is_manager": False, "last_intent": last_intent}, lambda e: None)


def _held(conv):
    return slot_store.get_slots(classify_node._HELD_QUESTION_NAMESPACE, COMPANY_ID, conv)


class TestCarryOnWording:
    @pytest.mark.parametrize("reply", ["Carry on with it", "carry on", "continue", "yes, continue",
                                       "resume", "continue with the application", "proceed"])
    def test_carries_on(self, reply):
        assert classify_node._DRAFT_CARRY_ON_RE.match(reply)

    @pytest.mark.parametrize("reply", ["continue my attendance check", "Discard it",
                                       "show my last 1 month attendance"])
    def test_is_not_carry_on(self, reply):
        assert not classify_node._DRAFT_CARRY_ON_RE.match(reply)


class TestTheChoice:
    async def test_the_interrupting_question_is_held(self, llm_says, draft):
        llm_says("attendance")
        out = await _turn("show my last 1 month attendance", draft)

        assert out["intent"] == "clarify_needed"
        assert out["clarify_options"] == ["Carry on with it", "Discard it"]
        assert _held(draft)["query"] == "show my last 1 month attendance"

    @pytest.mark.parametrize("reply", ["discard", "Discard it", "discard it"])
    async def test_discard_clears_the_draft_and_answers_the_held_question(self, llm_says, draft, reply):
        llm_says("attendance")
        await _turn("show my last 1 month attendance", draft)

        out = await _turn(reply, draft, last_intent="clarify_needed")

        assert out["intent"] == "attendance", "not cancel_leave — no pending-leave list"
        assert out["query"] == "show my last 1 month attendance"
        assert leave_slot_service.get_slots(COMPANY_ID, draft) is None
        assert _held(draft) is None

    async def test_the_next_question_is_not_asked_about_the_draft_again(self, llm_says, draft):
        llm_says("attendance")
        await _turn("show my last 1 month attendance", draft)
        await _turn("discard", draft, last_intent="clarify_needed")

        out = await _turn("show me last 1 month attendance", draft, last_intent="attendance")

        assert out["intent"] == "attendance"

    async def test_carry_on_resumes_the_draft(self, llm_says, draft):
        llm_says("attendance")
        await _turn("show my last 1 month attendance", draft)

        out = await _turn("Carry on with it", draft, last_intent="clarify_needed")

        assert out["intent"] == "apply_leave"
        assert leave_slot_service.get_slots(COMPANY_ID, draft)["leave_type"] == "casual_leave"
        assert _held(draft) is None

    async def test_the_held_question_lasts_one_reply(self, llm_says, draft):
        """Answering the draft instead ("tomorrow") drops the held question, so a
        later "discard" discards — it doesn't answer a question from turns ago."""
        llm_says("attendance")
        await _turn("show my last 1 month attendance", draft)
        await _turn("tomorrow", draft, last_intent="clarify_needed")

        out = await _turn("discard", draft)

        assert out["intent"] == "apply_leave"
        assert out.get("query") is None


class TestTheApplyFlowDiscards:
    @pytest.mark.parametrize("reply", ["discard", "Discard it"])
    async def test_discarded_not_listed(self, monkeypatch, reply):
        conv = f"las-discard-{reply}"
        leave_slot_service.set_slots(COMPANY_ID, conv, dict(DRAFT))
        monkeypatch.setattr(las.erp_client, "get_leave_context", AsyncMock(return_value={
            "http_status": 200, "body": {"success": True, "data": {
                "name": "B Geo", "is_manager": False, "is_hr": False}}}))
        events = []
        out = await las.leave_action_node(
            {"query": reply, "intent": "apply_leave", "bearer_token": "t", "company_id": COMPANY_ID,
             "conversation_id": conv, "usage_events": [], "is_manager": False}, events.append)

        assert out["response_text"].startswith(
            "No problem — I've discarded the leave application we were filling in.")
        assert leave_slot_service.get_slots(COMPANY_ID, conv) is None
