"""HA-665 QA: at "Reply yes to keep it" the summary card read "Reason: YES".

The reply handler confirmed the reason as it stood AFTER this turn's
extraction had been merged - and extraction may file the reply itself ("YES",
"Yess", the garbled text) as the reason. A yes confirms the reason the
question SHOWED, stored with it as reason_confirm["offered"].
"""

import json
from datetime import date
from unittest.mock import AsyncMock, patch

import pytest

import services.leave_action_service as las


class _Writer:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)

    def of_type(self, t):
        return [e for e in self.events if e.get("type") == t]


OFFERED = "Medical emergency"

# The leave date below, and the "today" the flow is run on. The file was
# written with 2026-09-28 as both; from 2026-09-29 the real clock made that a
# PAST date, the back-date check answered "You can't apply for leave on a past
# date" before any card was built, and every test here failed for a reason
# that has nothing to do with the reason confirmation they test.
LEAVE_DAY = date(2026, 9, 28)


def _asking(offered_stored=True):
    pending = {"as_typed": "", "suggestion": ""}
    if offered_stored:
        pending["offered"] = OFFERED
    return {"step": "collecting", "leave_type": "casual_leave", "from_date": LEAVE_DAY.isoformat(),
            "to_date": LEAVE_DAY.isoformat(), "session_type_slug": "full_day", "reason": OFFERED,
            "reason_confirm": pending, "_leave_abbreviations": {}}


async def _reply(reply, extracted_reason, verdict="agree", offered_stored=True):
    """One turn at the reason question. Extraction files `extracted_reason`
    (the worst case is the reply itself); the confirmation model answers
    `verdict`."""
    ok = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "name": "Abcd Test", "is_manager": False,
        "leave_quota": {"casual_leave": {"total": 100, "remaining": 75}},
        "leave_settings": {"leave_type": [{"slug": "casual_leave", "name": "Casual Leave",
                                           "session_type_required": True}]},
        "leaves": []}}})
    # Stateful like Redis: the node re-reads its slots mid-turn.
    saved, writer = _asking(offered_stored), _Writer()

    def _set(c, cid, s):
        saved.clear()
        saved.update(s)

    llm_json = json.dumps({"reason": extracted_reason} if extracted_reason else {})
    confirm_model = AsyncMock(return_value=(verdict, None, None))
    with patch.object(las, "_today", lambda: LEAVE_DAY), \
            patch.object(las, "_today_in_app_timezone", lambda: LEAVE_DAY), \
            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, "_call_llm", AsyncMock(return_value={})), \
            patch.object(las, "_extract_text", lambda raw: llm_json), \
            patch.object(las, "classify_confirmation_reply", confirm_model), \
            patch.object(las.leave_slot_service, "get_slots", lambda *a, **k: dict(saved)), \
            patch.object(las.leave_slot_service, "set_slots", _set), \
            patch.object(las.leave_slot_service, "clear_slots", lambda *a, **k: True):
        out = await las.leave_action_node(
            {"query": reply, "intent": "apply_leave", "bearer_token": "t", "company_id": 1,
             "conversation_id": "rc", "usage_events": [], "is_manager": False}, writer)
    return out["response_text"], writer, saved, confirm_model


def _card_reason(writer):
    cards = writer.of_type("leave_confirmation")
    return cards[0]["data"]["reason"] if cards else None


@pytest.mark.parametrize("reply", ["YES", "yes", "Yes.", "ok", "y", "sure", "correct"])
async def test_yes_keeps_the_offered_reason_not_the_reply(reply):
    text, writer, saved, _ = await _reply(reply, extracted_reason=reply.capitalize())

    assert _card_reason(writer) == OFFERED
    assert f"Reason: {OFFERED}." in text
    assert saved["reason"] == OFFERED


@pytest.mark.parametrize("reply", ["yess", "YESSS", "okk", "yeahh", "yrs"])
async def test_a_misspelled_yes_is_still_a_yes(reply):
    """The model called "yess" a new reason; the card said "Reason: Yess"."""
    text, writer, saved, confirm_model = await _reply(
        reply, extracted_reason=reply.capitalize(), verdict="replace")

    assert _card_reason(writer) == OFFERED
    confirm_model.assert_not_awaited()


async def test_a_model_agree_keeps_the_offered_reason():
    text, writer, saved, _ = await _reply("go ahead with that", extracted_reason="Go ahead with that",
                                          verdict="agree")

    assert _card_reason(writer) == OFFERED


async def test_an_unreadable_reply_is_not_filed_or_approved():
    """It was shown back as both unreadable and "the reason I have so far",
    and already marked confirmed - so the next "ok" submitted it."""
    garbled = "FO R MEDICAL EMR GENC Y"
    text, writer, saved, _ = await _reply(garbled, extracted_reason=garbled, verdict="other")

    assert "still waiting on the reason" in text
    assert f'The reason I have so far is "{OFFERED}"' in text
    assert saved["reason"] == OFFERED
    assert not saved.get("reason_confirmed")
    assert saved["reason_confirm"]["offered"] == OFFERED
    assert _card_reason(writer) is None


async def test_a_new_reason_still_replaces_it():
    text, writer, saved, _ = await _reply("Kidney stone", extracted_reason="Kidney stone",
                                          verdict="replace")

    assert _card_reason(writer) == "Kidney stone"


async def test_slots_saved_before_the_fix_still_confirm_the_shown_reason():
    """A conversation mid-question across the deploy has no "offered"."""
    text, writer, saved, _ = await _reply("YES", extracted_reason="Yes", offered_stored=False)

    assert _card_reason(writer) == OFFERED


@pytest.mark.parametrize("reply", ["kidney stone", "yoga", "essay", "keys", "yes but change it"])
def test_a_real_reason_is_not_read_as_yes(reply):
    assert not las._is_spelling_confirm(reply)
