"""Every reason a regularization can't go ahead is said at the FIRST step,
before any start/end time or reason is asked for (2026-10-05).

Two gaps closed:
  * Several dates in one message ("28 sept and 29 sept"): date_query_resolver
    keeps only the first, so only 28 Sep was checked - an already-applied
    29 Sep surfaced after its details had been collected.
  * "apply regularization" with no date while this payroll cycle's quota is
    already used: the employee was asked for a date first and only then told.
"""
from datetime import date
from unittest.mock import AsyncMock

import pytest

import services.payroll_cycle as payroll_cycle
import services.regularisation_node as reg
from services import slot_store

TODAY = date(2026, 10, 5)
COMPANY = "first-step-co"
CYCLE = payroll_cycle.PayrollCycle("custom", date(2026, 9, 21), date(2026, 10, 20))


def _row(rid, day, status):
    return {"regularization_id": rid, "apply_date": day, "status_name": status}


def _settings(limit=3, window=20, cycle=CYCLE):
    return {"available": True, "window_days": window, "limit": limit, "cycle": cycle}


class TestSeveralDates:
    @pytest.mark.parametrize("query,expected", [
        ("apply regularization for 28 sept and 29 sept", ["2026-09-28", "2026-09-29"]),
        ("regularize 28, 29 and 30 sept", ["2026-09-28", "2026-09-29", "2026-09-30"]),
        ("regularize 28 sept to 30 sept", ["2026-09-28", "2026-09-29", "2026-09-30"]),
        ("regularize yesterday and today", ["2026-10-04", "2026-10-05"]),
    ])
    def test_every_date_is_read(self, query, expected):
        assert reg._resolve_direct_entry_dates(query, TODAY) == expected

    @pytest.mark.parametrize("query", [
        "regularize 29 sept", "i forgot to punch out on 29 sept, please regularize",
        "regularize Sep 29, 2026", "regularise 29 sept 9:30 to 18:30 forgot to punch out",
        "regularize 1 sept to 30 sept",   # a month-long span is not several entries
    ])
    def test_one_date_is_left_to_the_single_date_check(self, query):
        assert reg._resolve_direct_entry_dates(query, TODAY) == []


def _gate_mocks(monkeypatch, *, duplicates=None, eligibility=None, rows=(), settings=None):
    """duplicates: {date: message} blocked as already applied; eligibility:
    {date: reason} blocked by the window/attendance check."""
    duplicates, eligibility = duplicates or {}, eligibility or {}
    monkeypatch.setattr(reg.attendance_mod, "_today", lambda: TODAY)

    async def _dup(date_iso, **kw):
        if date_iso in duplicates:
            return {"outcome": reg.DUPLICATE_BLOCKED, "message": duplicates[date_iso],
                    "existing_request": None, "rows": list(rows)}
        return {"outcome": reg.DUPLICATE_NONE, "message": None, "existing_request": None,
                "rows": list(rows)}

    async def _elig(date_iso, **kw):
        return eligibility.get(date_iso)

    monkeypatch.setattr(reg, "_check_duplicate_date", _dup)
    monkeypatch.setattr(reg, "_classify_and_check_eligibility", _elig)
    monkeypatch.setattr(reg, "_get_regularization_settings",
                        AsyncMock(return_value=settings or _settings()))


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)
    done = [e for e in events if e.get("type") == "done"]
    return out, (done[-1] if done else None)


class TestSeveralDatesGate:
    async def test_a_duplicate_among_them_is_said_now(self, monkeypatch):
        conv = "sev-1"
        slot_store.clear_slots("regularization", COMPANY, conv)
        _gate_mocks(monkeypatch, duplicates={"2026-09-29": "You've already applied ... 29 Sep (REG-125)."})
        out, done = await _gate("apply regularization for 28 sept and 29 sept", conv)

        answer = done["data"]["answer"]
        assert "Not possible:\n- You've already applied ... 29 Sep (REG-125)." in answer
        assert "Good news — 28 Sep 2026 is eligible" in answer
        assert done["data"]["eligible_dates"] == ["2026-09-28"]
        assert out["regularisation_blocked"] is True, "nothing is collected on this turn"
        stored = slot_store.get_slots("regularization", COMPANY, conv)
        assert stored[reg._CLASSIFIED_DATES_KEY] == ["2026-09-28"]

    async def test_all_blocked_stops(self, monkeypatch):
        conv = "sev-2"
        slot_store.clear_slots("regularization", COMPANY, conv)
        _gate_mocks(monkeypatch, duplicates={"2026-09-28": "A.", "2026-09-29": "B."})
        _, done = await _gate("regularize 28 sept and 29 sept", conv)

        assert done["data"]["answer"] == ("I can't take a regularization request for any of "
                                          "these dates:\n- A.\n- B.")
        assert done["data"]["regularisation_classification_status"] is False
        assert slot_store.get_slots("regularization", COMPANY, conv) is None

    async def test_the_quota_counts_the_other_dates_of_the_same_message(self, monkeypatch):
        conv = "sev-3"
        slot_store.clear_slots("regularization", COMPANY, conv)
        _gate_mocks(monkeypatch, rows=[_row(1, "2026-09-22", "approved"), _row(2, "2026-09-23", "pending")])
        _, done = await _gate("regularize 29 sept and 30 sept", conv)

        answer = done["data"]["answer"]
        assert "has been used (3 of 3), so I can't take a new request for 30 Sep 2026" in answer
        assert done["data"]["eligible_dates"] == ["2026-09-29"]
        assert "you'll have used 3 of 3" in answer

    async def test_an_eligibility_reason_is_said_now(self, monkeypatch):
        conv = "sev-4"
        slot_store.clear_slots("regularization", COMPANY, conv)
        _gate_mocks(monkeypatch, eligibility={"2026-09-27": "I can't regularize 27 Sep 2026 — Week Off."})
        _, done = await _gate("regularize 27 sept and 29 sept", conv)

        assert "- I can't regularize 27 Sep 2026 — Week Off." in done["data"]["answer"]
        assert done["data"]["eligible_dates"] == ["2026-09-29"]

    async def test_apply_now_carries_every_eligible_date(self, monkeypatch):
        conv = "sev-5"
        slot_store.set_slots("regularization", COMPANY, conv, {
            "entries": [], reg._PENDING_CLASSIFICATION_KEY: True,
            reg._CLASSIFIED_DATE_KEY: "2026-09-28",
            reg._CLASSIFIED_DATES_KEY: ["2026-09-28", "2026-09-30"]})
        _gate_mocks(monkeypatch)
        await _gate("apply now", conv)

        entries = slot_store.get_slots("regularization", COMPANY, conv)["entries"]
        assert [e["date"] for e in entries] == ["2026-09-28", "2026-09-30"]
        assert all(e["_prevalidated"] for e in entries)


class TestNoDateYet:
    def _mock(self, monkeypatch, rows, settings=None, raises=None):
        monkeypatch.setattr(reg.attendance_mod, "_today", lambda: TODAY)
        monkeypatch.setattr(reg, "_get_regularization_settings",
                            AsyncMock(return_value=settings or _settings()))

        async def _mine(token, **kw):
            if raises:
                raise raises
            return {"http_status": 200, "body": {"success": True, "data": {"regularizations": rows}}}

        monkeypatch.setattr(reg.attendance_client, "get_my_regularizations", _mine)

    FULL = [_row(1, "2026-09-22", "approved"), _row(2, "2026-09-23", "pending"),
            _row(3, "2026-09-24", "approved")]

    async def test_used_up_says_so_and_offers_the_previous_cycle(self, monkeypatch):
        conv = "nd-1"
        slot_store.clear_slots("regularization", COMPANY, conv)
        self._mock(monkeypatch, self.FULL)
        out, done = await _gate("apply regularization", conv)

        assert done["data"]["answer"] == (
            "Your regularization quota for 21 Sep – 20 Oct 2026 has already been used (3 of 3), "
            "so dates from 21 Sep 2026 onwards can't be regularized. You can still regularize a "
            "date from 16 Sep 2026 to 20 Sep 2026 (the previous cycle) - which date would you "
            "like to regularize?")
        assert done["data"]["regularisation_classification_status"] is True
        # Held open so the date reply stays with the regularization flow.
        assert slot_store.get_slots("regularization", COMPANY, conv) == {"entries": []}

    async def test_used_up_with_no_earlier_date_in_the_window_stops(self, monkeypatch):
        conv = "nd-2"
        slot_store.clear_slots("regularization", COMPANY, conv)
        self._mock(monkeypatch, self.FULL, settings=_settings(window=5))
        _, done = await _gate("apply regularization", conv)

        assert done["data"]["answer"].endswith("I can't take a new regularization request right now.")
        assert done["data"]["regularisation_classification_status"] is False
        assert slot_store.get_slots("regularization", COMPANY, conv) is None

    async def test_quota_left_asks_for_the_date_as_before(self, monkeypatch):
        conv = "nd-3"
        self._mock(monkeypatch, self.FULL[:2])
        out, done = await _gate("apply regularization", conv)
        assert done is None and "regularisation_blocked" not in out

    async def test_a_failed_lookup_does_not_block(self, monkeypatch):
        conv = "nd-4"
        self._mock(monkeypatch, [], raises=RuntimeError("down"))
        out, done = await _gate("apply regularization", conv)
        assert done is None and "regularisation_blocked" not in out
