"""QA: "apply cl / need Sl / want EL" -> "I can process one leave request at a
time. Would you like to start with Casual Leave?" -> "not cl but start with el"
-> the SAME question again.

The question kept no record of what it had offered, so the reply - which
names two types, one of them refused - looked like another two-request
message and was refused the same way. The offer now lives on the draft
(_type_choice) and the reply is read against it; the types not chosen are
offered again once the first request is submitted.
"""

from unittest.mock import AsyncMock, patch

import pytest

import services.classify_node as classify_node
import services.leave_action_service as las

OFFERED = ["casual_leave", "sick_leave", "earned_leave"]


@pytest.mark.parametrize("reply,chosen,still_open", [
    ("not cl but start with el", "earned_leave", None),   # the reported reply
    ("not casual, earned please", "earned_leave", None),
    ("el", "earned_leave", None),
    ("sick leave first", "sick_leave", None),
    ("go with SL", "sick_leave", None),
    ("yes", "casual_leave", None),                          # takes the offer
    ("ok", "casual_leave", None),
    ("no", None, ["sick_leave", "earned_leave"]),          # the offer refused
    ("cl and el", None, ["casual_leave", "earned_leave"]), # still two
    ("maybe", None, OFFERED),
])
def test_the_reply_is_read_against_the_offer(reply, chosen, still_open):
    assert las._resolve_type_choice(reply, OFFERED) == (chosen, still_open)


def test_no_with_two_offered_takes_the_other_one():
    assert las._resolve_type_choice("no", ["casual_leave", "earned_leave"]) == ("earned_leave", None)


# =============================================================================
# The conversation, turn by turn
# =============================================================================

_ERP = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
    "name": "Abcd Test", "is_manager": False,
    "leave_quota": {k: {"total": 20, "remaining": 11} for k in OFFERED},
    "leave_settings": {"leave_type": [{"slug": s, "name": s.replace("_", " ").title(),
                                       "session_type_required": False} for s in OFFERED]},
    "leaves": [], "abbreviations": []}}})


@pytest.fixture
def conversation(monkeypatch):
    store = {}

    def _get(*a, **k):
        return dict(store["s"]) if store.get("s") else None

    def _set(company_id, conversation_id, slots):
        store["s"] = dict(slots)
        return True

    def _clear(*a, **k):
        store.pop("s", None)
        return True

    async def _no_shift(query):
        return None, 0.0, None

    async def _llm_small_talk(prompt, labels, fallback_label="unknown"):
        return "small_talk", None, False   # what the fallback guessed for "no"

    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _llm_small_talk)
    monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda *a, **k: None)
    monkeypatch.setattr(classify_node.leave_cancel_state, "get_state", lambda *a, **k: None)
    monkeypatch.setattr(classify_node.leave_slot_service, "get_slots", _get)
    for name, fn in (("get_slots", _get), ("set_slots", _set), ("clear_slots", _clear)):
        monkeypatch.setattr(las.leave_slot_service, name, fn)
    monkeypatch.setattr(las, "_call_llm", AsyncMock(side_effect=RuntimeError("no LLM in tests")))

    async def turn(query):
        routed = await classify_node.classify_node(
            {"query": query, "context": [], "usage_events": [], "bearer_token": "t",
             "company_id": 1, "conversation_id": "m", "is_manager": False,
             "last_intent": "apply_leave", "has_date_expression": False}, lambda e: None)
        with patch.object(las.erp_client, "get_leave_context", _ERP), \
                patch.object(las.erp_client, "get_leave_balance", _ERP), \
                patch.object(las.erp_client, "get_applied_leaves", _ERP):
            out = await las.leave_action_node(
                {"query": query, "intent": routed["intent"], "bearer_token": "t", "company_id": 1,
                 "conversation_id": "m", "usage_events": [], "is_manager": False}, lambda e: None)
        return routed["intent"], out["response_text"], store.get("s") or {}

    return turn


async def test_not_cl_but_start_with_el_starts_earned_leave(conversation):
    _, first, slots = await conversation("apply cl / need Sl / want EL")
    assert first == "I can process one leave request at a time. Would you like to start with Casual Leave?"
    assert slots["_type_choice"] == OFFERED

    intent, text, slots = await conversation("not cl but start with el")

    assert intent == "apply_leave"
    assert "one leave request at a time" not in text
    assert slots["leave_type"] == "earned_leave"
    assert "_type_choice" not in slots
    assert slots["_queued_types"] == ["casual_leave", "sick_leave"]


async def test_no_asks_between_the_remaining_two_then_takes_the_named_one(conversation):
    await conversation("apply cl / need Sl / want EL")

    intent, text, _ = await conversation("no")
    assert intent == "apply_leave"
    assert text == "Sure — which one would you like to start with: Sick Leave or Earned Leave?"

    _, _, slots = await conversation("el")
    assert slots["leave_type"] == "earned_leave"


async def test_yes_takes_the_offered_type(conversation):
    await conversation("apply cl / need Sl / want EL")

    _, _, slots = await conversation("yes")

    assert slots["leave_type"] == "casual_leave"
