"""A change typed at the apply-leave confirmation card is offered, then applied
(negative run, 28 Oct 2026, #30).

"yes but make it 6 nov" at the card for 5 Nov was answered "Before I can help
with anything else, this leave request needs closing ... or tell me what
you'd like to change about it" - the change it had just been told was
dropped. 9165feb had removed the "replace" branch, the only writer of
_pending_amendment, leaving the amend/keep/discard handler with no way in.
"""
import json
from datetime import date
from unittest.mock import AsyncMock, patch

import pytest

import services.leave_action_service as las

pytestmark = pytest.mark.asyncio

CARD = {
    "step": "awaiting_confirmation", "leave_type": "casual_leave",
    "from_date": "2026-11-05", "to_date": "2026-11-05",
    "session_type_slug": "full_day", "reason": "Personal work", "reason_confirmed": True,
}
_CONTEXT = {"http_status": 200, "body": {"success": True, "data": {
    "name": "T", "is_manager": False,
    "leave_quota": {"casual_leave": {"total": 12, "remaining": 8}},
    "leave_settings": {"leave_type": [{"slug": "casual_leave", "name": "Casual Leave",
                                       "session_type_required": False}]},
    "leaves": []}}}


def _llm(payload: dict) -> dict:
    return {"choices": [{"message": {"content": json.dumps(payload)}}]}


class _Store:
    def __init__(self, slots):
        self.slots = dict(slots)

    def get(self, *a, **k):
        return dict(self.slots) if self.slots else None

    def set(self, _company, _conv, slots):
        self.slots = dict(slots)
        return True

    def clear(self, *a, **k):
        self.slots = {}
        return True


async def _turn(store, reply, *, extraction, verdict=("other", None), choice="unclear", submitted=None):
    async def _apply(token, leave_type, frm, to, *a, **k):
        if submitted is None:
            raise AssertionError(f"submitted {frm}..{to} without being asked")
        submitted.append((frm, to))
        return {"http_status": 200, "body": {"success": True, "data": [{"id": 77, "from_date": frm}]}}

    ok = AsyncMock(return_value=_CONTEXT)
    with patch.object(las.erp_client, "get_leave_context", ok), \
            patch.object(las.erp_client, "get_leave_balance", ok), \
            patch.object(las.erp_client, "get_applied_leaves", ok), \
            patch.object(las.erp_client, "apply_leave", _apply), \
            patch.object(las, "_today", lambda: date(2026, 10, 28)), \
            patch.object(las, "_call_llm", AsyncMock(return_value=_llm(extraction))), \
            patch.object(las, "classify_confirmation_reply", AsyncMock(return_value=(*verdict, None))), \
            patch.object(las, "classify_choice", AsyncMock(return_value=(choice, None))), \
            patch.object(las.leave_slot_service, "get_slots", store.get), \
            patch.object(las.leave_slot_service, "set_slots", store.set), \
            patch.object(las.leave_slot_service, "clear_slots", store.clear):
        out = await las.leave_action_node(
            {"query": reply, "intent": "apply_leave", "bearer_token": "t", "company_id": 1,
             "conversation_id": "amend", "usage_events": [], "is_manager": False},
            lambda ev: None)
    return out["response_text"]


async def test_a_changed_date_at_the_card_is_offered_as_an_amendment():
    store = _Store(CARD)
    text = await _turn(store, "yes but make it 6 nov",
                       extraction={"from_date": "2026-11-06", "to_date": "2026-11-06",
                                   "is_affirmative": True},
                       verdict=("replace", "6 nov"))
    assert "amend" in text.lower() and "needs closing" not in text
    assert store.slots["_pending_amendment"] == {"from_date": "2026-11-06", "to_date": "2026-11-06"}
    assert store.slots["from_date"] == "2026-11-05", "changed before the employee chose amend"


async def test_amend_shows_the_changed_card_and_yes_then_submits_the_new_date():
    store = _Store(CARD)
    await _turn(store, "yes but make it 6 nov",
                extraction={"from_date": "2026-11-06", "to_date": "2026-11-06"},
                verdict=("replace", "6 nov"))

    text = await _turn(store, "amend", extraction={}, choice="amend")
    assert "2026-11-06" in text or "06 Nov" in text, text
    assert store.slots.get("step") == "awaiting_confirmation"

    submitted = []
    await _turn(store, "yes", extraction={"is_affirmative": True}, submitted=submitted)
    assert submitted == [("2026-11-06", "2026-11-06")]


async def test_keep_leaves_the_original_on_the_card():
    store = _Store(CARD)
    await _turn(store, "yes but make it 6 nov",
                extraction={"from_date": "2026-11-06", "to_date": "2026-11-06"},
                verdict=("replace", "6 nov"))
    text = await _turn(store, "keep it", extraction={}, choice="keep")
    assert "Keeping the original" in text
    assert store.slots["from_date"] == "2026-11-05"


@pytest.mark.parametrize("reply,expect", [("amend", "2026-11-06"), ("Keep it", "Keeping the original"),
                                          ("discard", None)])
async def test_the_offered_answers_work_without_the_model(reply, expect):
    """classify_choice is unreachable (it answers "unclear" here): the
    question's own words must still resolve it - and none of them submits."""
    store = _Store(CARD)
    await _turn(store, "yes but make it 6 nov",
                extraction={"from_date": "2026-11-06", "to_date": "2026-11-06"},
                verdict=("replace", "6 nov"))
    text = await _turn(store, reply, extraction={}, choice="unclear")
    assert "can't move on" not in text, f"{reply!r} needed the model"
    assert "_pending_amendment" not in store.slots
    if expect:
        assert expect in text or expect.replace("2026-11-06", "06 Nov") in text, text


async def test_a_replace_with_nothing_extracted_asks_again_and_changes_nothing():
    store = _Store(CARD)
    text = await _turn(store, "change it", extraction={}, verdict=("replace", None))
    assert "needs closing" in text
    assert "_pending_amendment" not in store.slots
