"""A date that can't exist is refused at the first step (2026-10-06).

QA: "Apply regularization for 31 Sep 2026" showed a "Regularization Request
Identified" card for 2026-09-31 - the gate's LLM date fallback returned an
impossible ISO date and the flow carried on with it. Acceptance: say the date
is invalid, ask for a valid one, make NO backend call, don't crash, and let the
user carry on with the regularization.
"""
from datetime import date
from unittest.mock import AsyncMock

import pytest

import services.regularisation_node as reg
from services import slot_store

COMPANY = "invalid-date-co"
TODAY = date(2026, 10, 6)


class TestDetection:
    @pytest.mark.parametrize("query,text,why", [
        ("Apply regularization for 31 Sep 2026", "31 Sep 2026", "September 2026 has only 30 days"),
        ("regularize 30 feb", "30 feb", "February 2026 has only 28 days"),
        ("regularize 31/04/2026", "31/04/2026", "April 2026 has only 30 days"),
        ("regularize 2026-02-30", "2026-02-30", "February 2026 has only 28 days"),
        ("regularize 29 feb 2027", "29 feb 2027", "February 2027 has only 28 days"),
        ("regularize 28 sept and 31 sept", "31 sept", "September 2026 has only 30 days"),
        ("regularize 13/13/2026", "13/13/2026", "there's no month 13"),
    ])
    def test_invalid(self, query, text, why):
        found = reg._invalid_date_mention(query, TODAY)
        assert found == text
        message = reg._invalid_date_message(found, TODAY)
        assert message.startswith(f"'{text}' isn't a valid date - {why}.")
        assert "Which date would you like to regularize?" in message

    @pytest.mark.parametrize("query", ["regularize 29 sept", "regularize 29 feb 2028",
                                       "regularize 30 Sep 2026", "9-6 forgot to punch out",
                                       "apply regularization"])
    def test_valid_or_no_date(self, query):
        assert reg._invalid_date_mention(query, TODAY) is None


@pytest.fixture
def no_backend(monkeypatch):
    calls = []

    def _spy(name):
        async def _call(*a, **k):
            calls.append(name)
            return {"outcome": reg.DUPLICATE_NONE, "message": None, "existing_request": None,
                    "rows": [], "available": True, "window_days": None, "limit": None, "cycle": None}
        return _call

    monkeypatch.setattr(reg.attendance_mod, "_today", lambda: TODAY)
    monkeypatch.setattr(reg, "_check_duplicate_date", _spy("duplicate"))
    monkeypatch.setattr(reg, "_get_regularization_settings", _spy("settings"))
    monkeypatch.setattr(reg, "_classify_and_check_eligibility", AsyncMock(return_value=None))
    monkeypatch.setattr(reg, "_resolve_direct_entry_date_llm_fallback",
                        AsyncMock(side_effect=AssertionError("no LLM date guess for an invalid date")))
    monkeypatch.setattr(reg, "_get_shift_details", AsyncMock(return_value=None))
    return calls


async def _gate(query, conv):
    events = []
    out = await reg.regularisation_eligibility_node(
        {"query": query, "company_id": COMPANY, "conversation_id": conv,
         "bearer_token": "t", "usage_events": []}, events.append)
    return out, [e for e in events if e.get("type") == "done"][-1]


class TestGate:
    async def test_says_invalid_asks_again_and_calls_nothing(self, no_backend):
        conv = "inv-1"
        slot_store.clear_slots("regularization", COMPANY, conv)
        out, done = await _gate("Apply regularization for 31 Sep 2026", conv)

        assert done["data"]["answer"].startswith(
            "'31 Sep 2026' isn't a valid date - September 2026 has only 30 days.")
        assert done["data"]["invalid_date"] == "31 Sep 2026"
        assert done["data"]["requires_date_input"] is True
        assert "date" not in done["data"], "no 2026-09-31 is ever put on a card"
        assert no_backend == [], "no backend validation call"
        assert out["regularisation_blocked"] is True

    async def test_the_user_can_carry_on_with_a_valid_date(self, no_backend):
        conv = "inv-2"
        slot_store.clear_slots("regularization", COMPANY, conv)
        await _gate("Apply regularization for 31 Sep 2026", conv)
        assert slot_store.get_slots("regularization", COMPANY, conv) == {"entries": []}

        _, done = await _gate("30 Sep 2026", conv)
        assert done["data"]["answer"].startswith("Good news — 30 Sep 2026 is eligible")
        assert no_backend == ["duplicate", "settings"]


class TestLlmFallbackRejectsImpossibleDates:
    async def test_2026_09_31_is_dropped(self, monkeypatch):
        monkeypatch.setattr(reg, "_call_llm", AsyncMock(return_value={
            "choices": [{"message": {"content": '{"date": "2026-09-31"}'}}]}))
        assert await reg._resolve_direct_entry_date_llm_fallback("31 septmber", TODAY, []) is None

    async def test_a_real_date_is_kept(self, monkeypatch):
        monkeypatch.setattr(reg, "_call_llm", AsyncMock(return_value={
            "choices": [{"message": {"content": '{"date": "2026-09-30"}'}}]}))
        assert await reg._resolve_direct_entry_date_llm_fallback("30 septmber", TODAY, []) == "2026-09-30"
