"""An apply-leave draft survives a Redis error, and a "yes" whose draft is
gone says so (negative run, 28 Oct 2026, #63a / #33).

With Redis erroring at the "Shall I submit this request?" step, the "yes"
found no draft and started a new application ("What type of leave would you
like to apply for?"). leave_slot_service had no in-process fallback, unlike
slot_store - the regularization draft survived the same outage.
"""
from unittest.mock import AsyncMock, patch

import pytest

import services.leave_action_service as las
from services import leave_slot_service

DRAFT = {"step": "awaiting_confirmation", "leave_type": "casual_leave",
         "from_date": "2026-11-05", "to_date": "2026-11-05"}
ASKED = "To confirm: 1.0 day(s) of casual leave from 2026-11-05 to 2026-11-05. Shall I submit this request?"


class _DownRedis:
    def __getattr__(self, name):
        def _down(*a, **k):
            raise ConnectionError("Redis down")
        return _down


class TestTheInProcessCopy:
    def test_a_draft_written_before_redis_failed_is_still_read(self, monkeypatch):
        leave_slot_service.set_slots(1, "c", DRAFT)
        monkeypatch.setattr(leave_slot_service, "_get_redis", lambda: _DownRedis())
        assert leave_slot_service.get_slots(1, "c") == DRAFT

    def test_with_no_redis_at_all_the_draft_still_round_trips(self, monkeypatch):
        monkeypatch.setattr(leave_slot_service, "_get_redis", lambda: None)
        assert leave_slot_service.set_slots(1, "c", DRAFT) is False   # Redis did not confirm
        assert leave_slot_service.get_slots(1, "c") == DRAFT

    def test_a_clear_removes_the_copy_too(self, monkeypatch):
        leave_slot_service.set_slots(1, "c", DRAFT)
        leave_slot_service.clear_slots(1, "c")
        monkeypatch.setattr(leave_slot_service, "_get_redis", lambda: _DownRedis())
        assert leave_slot_service.get_slots(1, "c") is None

    def test_redis_answering_none_is_believed_over_the_copy(self, fake_redis):
        """A reachable Redis that has no key (expired, or cleared by another
        worker) is the truth - the copy is only for when Redis can't answer."""
        leave_slot_service.set_slots(1, "c", DRAFT)
        fake_redis.delete(leave_slot_service._key("1", "c"))
        assert leave_slot_service.get_slots(1, "c") is None


async def _yes_with_no_draft(context):
    apply_leave = AsyncMock(side_effect=AssertionError("submitted with no draft"))
    with patch.object(las.erp_client, "apply_leave", apply_leave), \
            patch.object(las.erp_client, "get_leave_context", AsyncMock(return_value={
                "http_status": 200, "body": {"success": True, "data": {"leave_quota": {},
                                                                        "leave_settings": {}}}})), \
            patch.object(las, "_call_llm", AsyncMock(side_effect=RuntimeError("no LLM"))):
        out = await las.leave_action_node(
            {"query": "yes", "intent": "apply_leave", "bearer_token": "t", "company_id": 1,
             "conversation_id": "gone", "usage_events": [], "is_manager": False,
             "context": context}, lambda ev: None)
    return out["response_text"]


class TestAYesWhoseDraftIsGone:
    @pytest.mark.parametrize("asked", [
        ASKED,
        "Before I can help with anything else, this leave request needs closing — casual leave "
        "on Thu, 05 Nov 2026, waiting for your confirmation. Reply **yes** to submit it or **no** "
        "to discard it.",
    ])
    async def test_it_says_nothing_is_waiting_and_submits_nothing(self, asked):
        text = await _yes_with_no_draft([{"role": "user", "content": "apply casual leave"},
                                         {"role": "assistant", "content": asked}])
        assert "no leave request waiting for confirmation" in text
        assert "What type of leave" not in text

    async def test_a_yes_to_anything_else_is_left_alone(self):
        text = await _yes_with_no_draft([{"role": "assistant", "content": "Here's your leave balance."}])
        assert "no leave request waiting for confirmation" not in text
