"""HA-697 AC-05 — the regularization quota, step 3 of Duplicate > Eligibility >
Quota, measured over the company's payroll cycle from /api/v1/ai/leave/balance:

    "payroll_cycle": {"type": "monthly", "start_date": "2026-09-01", "end_date": "2026-09-30"}

Limit = the regularization policy's max_apply_in_month. Used = the caller's
own Pending + Approved requests dated inside the cycle of the date being
requested (product decision), counted from the rows the duplicate-date check
already fetched.
"""
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

COMPANY_ID = "quota-co"
TODAY = date(2026, 9, 28)
SEP = payroll_cycle.PayrollCycle("monthly", date(2026, 9, 1), date(2026, 9, 30))
CYCLE_21 = payroll_cycle.PayrollCycle("monthly", date(2026, 9, 21), date(2026, 10, 20))


def _row(reg_id, apply_date, status_name):
    return {"regularization_id": reg_id, "apply_date": apply_date, "status_name": status_name}


def _settings(limit=2, cycle=SEP, available=True):
    return {"available": available, "window_days": 20, "limit": limit, "cycle": cycle}


# -- services/payroll_cycle.py ------------------------------------------------

class TestPayrollCycle:
    def test_parsed_from_the_balance_data(self):
        cycle = payroll_cycle.from_balance_data({"payroll_cycle": {
            "type": "monthly", "start_date": "2026-09-01", "end_date": "2026-09-30"}})
        assert cycle == SEP

    def test_also_read_from_inside_leave_settings(self):
        cycle = payroll_cycle.from_balance_data({"leave_settings": {"payroll_cycle": {
            "type": "monthly", "start_date": "2026-09-01", "end_date": "2026-09-30"}}})
        assert cycle == SEP

    @pytest.mark.parametrize("raw", [
        None, {}, {"start_date": "2026-09-01"}, {"start_date": "bad", "end_date": "2026-09-30"},
        {"type": "monthly", "start_date": "2026-09-30", "end_date": "2026-09-01"},
    ])
    def test_missing_or_malformed_is_none(self, raw):
        assert payroll_cycle.from_balance_data({"payroll_cycle": raw}) is None

    @pytest.mark.parametrize("day,start,end", [
        (date(2026, 9, 21), date(2026, 9, 21), date(2026, 10, 20)),   # current
        (date(2026, 9, 20), date(2026, 8, 21), date(2026, 9, 20)),    # previous — a back-dated request
        (date(2026, 8, 21), date(2026, 8, 21), date(2026, 9, 20)),
        (date(2026, 7, 25), date(2026, 7, 21), date(2026, 8, 20)),
        (date(2026, 10, 21), date(2026, 10, 21), date(2026, 11, 20)),  # next
    ])
    def test_a_monthly_cycle_steps_by_whole_months_keeping_its_start_day(self, day, start, end):
        cycle = payroll_cycle.cycle_for(CYCLE_21, day)
        assert (cycle.start, cycle.end) == (start, end)

    def test_a_custom_cycle_is_parsed_and_steps_the_same_way(self):
        """type "custom" = a day of one month to the day before it in the next
        (this tenant's 21st to the 20th). A back-dated request in the
        previous cycle must still find it."""
        custom = payroll_cycle.from_balance_data({"payroll_cycle": {
            "type": "custom", "start_date": "2026-09-21", "end_date": "2026-10-20"}})
        assert custom.type == "custom"
        previous = payroll_cycle.cycle_for(custom, date(2026, 9, 8))
        assert (previous.start, previous.end) == (date(2026, 8, 21), date(2026, 9, 20))
        assert previous.label() == "21 Aug – 20 Sep 2026"

    def test_calendar_month_cycles_step_to_calendar_months(self):
        cycle = payroll_cycle.cycle_for(SEP, date(2026, 2, 10))
        assert (cycle.start, cycle.end) == (date(2026, 2, 1), date(2026, 2, 28))

    def test_an_unknown_cycle_type_is_never_guessed_outside_itself(self):
        weekly = payroll_cycle.PayrollCycle("weekly", date(2026, 9, 21), date(2026, 9, 27))
        assert payroll_cycle.cycle_for(weekly, date(2026, 9, 23)) == weekly
        assert payroll_cycle.cycle_for(weekly, date(2026, 9, 1)) is None

    def test_labels(self):
        assert SEP.label() == "Sep 2026"
        assert CYCLE_21.label() == "21 Sep – 20 Oct 2026"
        assert payroll_cycle.PayrollCycle(
            "monthly", date(2026, 12, 21), date(2027, 1, 20)).label() == "21 Dec 2026 – 20 Jan 2027"


# -- regularisation_node._check_quota -------------------------------------------

class TestCheckQuota:
    def test_available_with_the_designs_summary(self):
        quota = reg._check_quota("2026-09-18", [_row(1, "2026-09-03", "approved")], _settings())
        assert quota["outcome"] == reg.QUOTA_OK
        assert quota["message"] == "Quota available: 1 of 2 used for Sep 2026."
        assert quota["used"] == 1 and quota["limit"] == 2

    def test_exhausted_stops(self):
        rows = [_row(1, "2026-09-03", "approved"), _row(2, "2026-09-14", "pending")]
        quota = reg._check_quota("2026-09-18", rows, _settings())
        assert quota["outcome"] == reg.QUOTA_EXHAUSTED
        assert quota["message"].startswith(
            "Your regularization quota for Sep 2026 has been used (2 of 2)")

    def test_only_pending_and_approved_count(self):
        rows = [_row(i, "2026-09-0%d" % i, s) for i, s in
                enumerate(["cancelled", "rejected", "withdrawn", "approved"], start=1)]
        quota = reg._check_quota("2026-09-18", rows, _settings())
        assert quota["used"] == 1

    def test_counted_in_the_cycle_of_the_requested_date(self):
        """A back-dated request counts against ITS cycle, not the current one."""
        rows = [_row(1, "2026-09-10", "approved"), _row(2, "2026-09-15", "pending"),  # 21 Aug–20 Sep
                _row(3, "2026-09-25", "pending")]                                    # 21 Sep–20 Oct
        previous = reg._check_quota("2026-09-18", rows, _settings(cycle=CYCLE_21))
        current = reg._check_quota("2026-09-22", rows, _settings(cycle=CYCLE_21))

        assert previous["outcome"] == reg.QUOTA_EXHAUSTED
        assert previous["cycle"]["start_date"] == "2026-08-21"
        assert current["outcome"] == reg.QUOTA_OK
        assert current["used"] == 1

    def test_a_custom_cycle_counts_a_back_dated_request_against_its_own_cycle(self):
        custom = payroll_cycle.PayrollCycle("custom", date(2026, 9, 21), date(2026, 10, 20))
        rows = [_row(1, "2026-08-25", "approved"), _row(2, "2026-09-10", "pending"),  # 21 Aug–20 Sep
                _row(3, "2026-09-22", "pending")]                                    # current
        quota = reg._check_quota("2026-09-08", rows, _settings(cycle=custom))
        assert quota["outcome"] == reg.QUOTA_EXHAUSTED
        assert quota["message"].startswith(
            "Your regularization quota for 21 Aug – 20 Sep 2026 has been used (2 of 2)")

    def test_a_failed_settings_lookup_fails_closed(self):
        quota = reg._check_quota("2026-09-18", [], _settings(available=False))
        assert quota["outcome"] == reg.QUOTA_UNAVAILABLE
        assert "try again" in quota["message"] and "regularization form" in quota["message"]
        assert reg._quota_check_data(quota)["retry_available"] is True

    def test_no_request_list_fails_closed(self):
        assert reg._check_quota("2026-09-18", None, _settings())["outcome"] == reg.QUOTA_UNAVAILABLE

    @pytest.mark.parametrize("settings", [_settings(limit=None), _settings(cycle=None)])
    def test_nothing_configured_is_not_enforced(self, settings):
        """No limit, or no payroll_cycle to measure it over: nothing to
        enforce here — erp-api's submission still revalidates (AC-09)."""
        assert reg._check_quota("2026-09-18", [], settings)["outcome"] == reg.QUOTA_NOT_ENFORCED


# -- _get_regularization_settings ----------------------------------------------

class TestSettings:
    async def test_one_balance_call_gives_window_limit_and_cycle(self, monkeypatch):
        async def fake_balance(*args, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "payroll_cycle": {"type": "monthly", "start_date": "2026-09-01", "end_date": "2026-09-30"},
                "leave_settings": {"regularization_policy": {
                    "max_apply_in_month": 10, "regularization_allowed_days": 20}}}}}

        monkeypatch.setattr(reg.attendance_client, "get_leave_balance", fake_balance)
        settings = await reg._get_regularization_settings(
            bearer_token="t", company_id=1, conversation_id="c")
        assert settings == {"available": True, "window_days": 20, "limit": 10, "cycle": SEP}

    async def test_unreachable_is_unavailable(self, monkeypatch):
        async def down(*args, **kwargs):
            raise reg.attendance_client.ErpApiUnavailable("down")

        monkeypatch.setattr(reg.attendance_client, "get_leave_balance", down)
        settings = await reg._get_regularization_settings(
            bearer_token="t", company_id=1, conversation_id="c")
        assert settings["available"] is False


# -- the classify gate: Duplicate > Eligibility > Quota -------------------------

async def _classify(monkeypatch, query, rows, settings, conversation_id):
    monkeypatch.setattr(reg.attendance_mod, "_today", lambda: TODAY)
    monkeypatch.setattr(reg, "_check_duplicate_date", AsyncMock(return_value={
        "outcome": reg.DUPLICATE_NONE, "message": None, "existing_request": None, "rows": rows}))
    monkeypatch.setattr(reg, "_get_regularization_settings", AsyncMock(return_value=settings))
    monkeypatch.setattr(reg, "_classify_and_check_eligibility", AsyncMock(return_value=None))
    slot_store.clear_slots("regularization", COMPANY_ID, conversation_id)
    events = []
    result = await reg.regularisation_eligibility_node(
        {"query": query, "company_id": COMPANY_ID, "conversation_id": conversation_id,
         "bearer_token": "t", "usage_events": []}, events.append)
    return result, [e for e in events if e.get("type") == "done"][-1]


class TestClassifyGateQuota:
    async def test_all_checks_passed_names_the_quota(self, monkeypatch):
        result, done = await _classify(monkeypatch, "regularize 18 sept 2026",
                                       [_row(1, "2026-09-03", "approved")], _settings(), "q-1")

        assert done["data"]["regularisation_classification_status"] is True
        assert "Quota available: 1 of 2 used for Sep 2026." in done["data"]["answer"]
        assert "apply now" in done["data"]["answer"]
        assert done["data"]["quota_check"]["outcome"] == "ok"
        stored = slot_store.get_slots("regularization", COMPANY_ID, "q-1")
        assert stored[reg._PENDING_CLASSIFICATION_KEY] is True

    async def test_exhausted_stops_before_any_detail_is_asked(self, monkeypatch):
        rows = [_row(1, "2026-09-03", "approved"), _row(2, "2026-09-14", "pending")]
        result, done = await _classify(monkeypatch, "regularize 18 sept 2026", rows, _settings(), "q-2")

        assert result["regularisation_blocked"] is True
        assert done["data"]["regularisation_classification_status"] is False
        assert "has been used (2 of 2)" in done["data"]["answer"]
        assert done["data"]["quota_check"] == {
            "outcome": "exhausted", "used": 2, "limit": 2,
            "cycle": {"type": "monthly", "start_date": "2026-09-01",
                      "end_date": "2026-09-30", "label": "Sep 2026"}}
        assert not (slot_store.get_slots("regularization", COMPANY_ID, "q-2") or {}).get(
            reg._PENDING_CLASSIFICATION_KEY)

    async def test_unavailable_stops_and_offers_retry_and_form(self, monkeypatch):
        result, done = await _classify(monkeypatch, "regularize 18 sept 2026", [],
                                       _settings(available=False), "q-3")

        assert result["regularisation_blocked"] is True
        assert done["data"]["check_unavailable"] is True
        assert done["data"]["form_fallback"] is True

    async def test_not_enforced_passes_without_a_quota_line(self, monkeypatch):
        result, done = await _classify(monkeypatch, "regularize 18 sept 2026", [],
                                       _settings(cycle=None), "q-4")

        assert done["data"]["regularisation_classification_status"] is True
        assert "Quota available" not in done["data"]["answer"]


# -- the back-date window (regularization_allowed_days) ---------------------------

class TestBackDateWindow:
    """regularization_allowed_days decides how far back a date may be — for
    EVERY path, including an attendance / attendance_explain hand-off, whose
    "_prevalidated" flag used to skip the window along with the status check."""

    async def _reason(self, monkeypatch, entry, status_code="P"):
        monkeypatch.setattr(reg.attendance_mod, "_today", lambda: TODAY)
        return await reg._regularization_eligibility_block_reason(
            entry, status_code, False, bearer_token="t", company_id=1, conversation_id="c",
            attendance_known=True, settings=_settings())   # window_days = 20

    # erp-api's count: exactly 20 days back is already EXPIRED. The portal
    # answered "Regularization period has expired" for 9 Sep asked on 29 Sep
    # with regularization_allowed_days 20.
    @pytest.mark.parametrize("day,allowed", [
        ("2026-09-09", True),    # 19 days back
        ("2026-09-08", False),   # exactly 20 days back
        ("2026-09-07", False),   # 21 days back
    ])
    async def test_the_boundary(self, monkeypatch, day, allowed):
        reason = await self._reason(monkeypatch, {"date": day}, status_code="A")
        assert (reason is None) is allowed
        if not allowed:
            assert reason.startswith("Regularization period has expired for")
            assert "within the last 20 days" in reason

    async def test_a_handoff_outside_the_window_is_refused(self, monkeypatch):
        reason = await self._reason(monkeypatch, {"date": "2026-08-01", "_prevalidated": True})
        assert reason.startswith("Regularization period has expired for 01 Aug 2026")

    async def test_a_handoff_inside_the_window_still_skips_the_status_check(self, monkeypatch):
        """Attendance already confirmed Absent/Half Day Absent — a "P" read
        here must not re-refuse it."""
        assert await self._reason(monkeypatch, {"date": "2026-09-20", "_prevalidated": True}) is None


# -- erp-api's own refusal at submission (AC-09) ----------------------------------

EXPIRED = "Regularization period has expired"


class TestSubmitRefusal:
    """When erp-api itself refuses a back-dated request, ITS sentence reaches the
    employee. Before, a refusal on a status other than 400 raised
    ErpApiUnavailable and was reported as "I'm unable to reach the HR system"."""

    def test_an_exception_carrying_erp_apis_message_shows_that_message(self):
        exc = reg.attendance_client.ErpApiUnavailable(
            "erp-api returned 409", status_code=409, body={"success": False, "message": EXPIRED})
        assert reg._map_exception(exc) == EXPIRED

    def test_a_real_outage_still_says_so(self):
        exc = reg.attendance_client.ErpApiUnavailable("connection refused")
        assert "unable to reach the HR system" in reg._map_exception(exc)

    @pytest.mark.parametrize("http_status", [400, 422])
    async def test_the_refusal_through_the_real_client_and_the_confirm_flow(self, monkeypatch, http_status):
        import json
        import httpx
        from unittest.mock import patch

        conversation_id = f"submit-expired-{http_status}"
        slot_store.set_slots("regularization", COMPANY_ID, conversation_id, {
            "entries": [{"date": "2026-09-18", "start_time": "09:15", "end_time": "19:00",
                         "reason": "forgot to punch out", "_prefill_fetched": True}],
            "employee_name": None,
        })
        sent = []

        async def fake_http(method, url, **kwargs):
            sent.append((method, url))
            return httpx.Response(http_status, json={"success": False, "message": EXPIRED},
                                  request=httpx.Request(method, url))

        monkeypatch.setattr(reg.attendance_client._http, "request", fake_http)
        monkeypatch.setattr(reg.attendance_client, "_log_call_background", lambda **kwargs: None)
        confirm = {"choices": [{"message": {"content": json.dumps(
            {"action": "confirm", "entries": [], "employee_name": None})}}]}
        events = []
        with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=confirm)):
            await reg.regularisation_node(
                {"query": "yes submit it", "company_id": COMPANY_ID,
                 "conversation_id": conversation_id, "bearer_token": "t", "usage_events": []},
                events.append)

        # One submit; the only other call is the shift lookup the apply flow
        # shows the employee (GET /shift-details).
        assert [m for m, _ in sent if m == "POST"] == ["POST"]
        assert all(m == "POST" or "/shift-details" in u for m, u in sent)
        done = [e for e in events if e.get("type") == "done"][-1]
        assert done["intent"] == "regularization_partial"
        assert EXPIRED in done["data"]["answer"]
        assert "unable to reach" not in done["data"]["answer"]
        assert done["data"]["results"][0]["ok"] is False
