"""HA-697 — duplicate-date check and the reshaped /api/v1/ai/regularizations.

  - erp_client.get_my_regularizations: GET /api/v1/ai/regularizations, no
    type param (the caller's own requests), optional ?status= filter.
  - regularisation_node._check_duplicate_date: AC-03 outcomes by the existing
    request's status, and AC-12 fail-closed when the lookup can't complete.
  - regularisation_eligibility_node: the check runs FIRST (AC-02) and a
    blocked/unavailable result stops before any eligibility check.
  - regularisation_node's mid-flow date change (_fetch_prefill): same check,
    before any punch fetch (AC-08).
  - my_regularisation_view_node: status filter and erp-api's counts (AC-01).
"""
import json
from datetime import date
from unittest.mock import AsyncMock, patch

import pytest

import services.erp_client as erp_client
import services.regularisation_node as reg
from services import slot_store
from services.my_regularisation_view import my_regularisation_view_node, _requested_status_filter

COMPANY_ID = "dup-co"
TODAY = date(2026, 9, 28)


def _row(reg_id, apply_date, status_name, status=None):
    return {
        "regularization_id": reg_id, "employee_id": 3735, "employee_number": "geo3",
        "employee_name": "Ayush Jio", "apply_date": apply_date,
        "from_time": "10:00:00", "to_time": "19:00:00", "reason": "Testing",
        "status": status, "status_name": status_name,
    }


def _list_response(rows, **counts):
    return {"http_status": 200, "body": {"success": True, "message": "success", "data": {
        "total_regularizations": len(rows), **counts, "regularizations": rows,
    }}}


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

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

    @property
    def done(self):
        return next(e for e in reversed(self.events) if e.get("type") == "done")


async def _check(monkeypatch, response=None, exc=None, date_iso="2026-09-14"):
    async def fake(token, company_id=None, conversation_id=None, status=None):
        if exc:
            raise exc
        return response

    monkeypatch.setattr(erp_client, "get_my_regularizations", fake)
    return await reg._check_duplicate_date(
        date_iso, bearer_token="tok", company_id=COMPANY_ID, conversation_id="c1",
    )


# -- erp_client contract -----------------------------------------------------

class TestErpClientContract:
    async def _capture(self, monkeypatch, **kwargs):
        seen = {}

        async def fake_request(method, path, token, **kw):
            seen.update({"method": method, "path": path, **kw})
            return {"http_status": 200, "body": {"success": True, "data": {}}}

        monkeypatch.setattr(erp_client, "_request", fake_request)
        await erp_client.get_my_regularizations("tok", company_id=26, **kwargs)
        return seen

    async def test_own_requests_ask_for_status_all_and_no_type(self, monkeypatch):
        seen = await self._capture(monkeypatch)
        assert seen["method"] == "GET"
        assert seen["path"] == "/api/v1/ai/regularizations"
        # status=all explicitly; and no type=all, which is the manager's team switch.
        assert seen["params"] == {"status": "all"}

    @pytest.mark.parametrize("status", ["pending", "approved", "rejected", "cancelled", "Approved"])
    async def test_status_filter_values(self, monkeypatch, status):
        seen = await self._capture(monkeypatch, status=status)
        assert seen["params"] == {"status": status.lower()}

    @pytest.mark.parametrize("status", ["everything", "", None, "all", "ALL"])
    async def test_unknown_or_missing_status_becomes_all(self, monkeypatch, status):
        seen = await self._capture(monkeypatch, status=status)
        assert seen["params"] == {"status": "all"}


# -- _check_duplicate_date ---------------------------------------------------

class TestDuplicateOutcomes:
    async def test_no_request_on_the_date(self, monkeypatch):
        result = await _check(monkeypatch, _list_response([_row(90, "2026-09-07", "pending")]))
        assert result["outcome"] == reg.DUPLICATE_NONE
        assert result["message"] is None

    async def test_pending_blocks_with_its_reference(self, monkeypatch):
        result = await _check(monkeypatch, _list_response([_row(92, "2026-09-14", "pending", 0)]))
        assert result["outcome"] == reg.DUPLICATE_BLOCKED
        assert "Pending approval" in result["message"]
        assert "Ref: REG-92" in result["message"]
        existing = result["existing_request"]
        assert existing["regularization_id"] == 92
        # The existing-request card's fields (AC-03 / Figma).
        assert existing["reference_id"] == "REG-92"
        assert existing["card_status_label"] == "Pending approval"
        assert existing["apply_date_display"] == "14-Sep-2026"

    async def test_the_reply_matches_the_figma_notice(self, monkeypatch):
        """Figma: one sentence, date as 14-Sep-2026; the reason, type and
        applied-on are on the existing-request card, not in the sentence."""
        row = {**_row(92, "2026-09-14", "pending", 0), "reason": "forgot to punch out"}
        result = await _check(monkeypatch, _list_response([row]))
        assert result["message"] == (
            "You've already applied for regularization on 14-Sep-2026, currently "
            "Pending approval (Ref: REG-92)."
        )
        assert result["existing_request"]["reason"] == "forgot to punch out"

    async def test_the_existing_request_card(self, monkeypatch):
        row = {**_row(92, "2026-09-14", "pending", 0), "reason": "forgot to punch out",
               "created_at": "2026-09-10 08:00:00"}
        data = reg._duplicate_check_data(await _check(monkeypatch, _list_response([row])))
        assert data["title"] == "You already have a request for this date"
        assert data["existing_request_card"] == {
            "title": "Existing request REG-92", "reference_id": "REG-92", "date": "14-Sep-2026",
            "regularization_type": "Missed punch-out", "status": "Pending approval",
            "status_key": "pending", "applied_on": "10-Sep-2026", "reason": "forgot to punch out",
            "rejection_reason": None, "cancel_reason": None}
        assert data["actions"] == [{"label": "View in Requests", "action": "view_requests"}]

    async def test_a_prior_request_is_a_notice_with_its_card(self, monkeypatch):
        row = {**_row(60, "2026-09-14", "cancelled"), "reason": "meeting"}
        result = await _check(monkeypatch, _list_response([row]))
        assert result["message"] == ("Your earlier request for 14-Sep-2026 (Ref: REG-60) was "
                                     "Cancelled, so a new request is allowed.")
        data = reg._duplicate_check_data(result)
        assert data["title"] == "You have an earlier request for this date"
        assert data["existing_request_card"]["reason"] == "meeting"

    async def test_no_reason_sentence_when_erp_sent_none(self, monkeypatch):
        row = {**_row(92, "2026-09-14", "pending", 0), "reason": None}
        result = await _check(monkeypatch, _list_response([row]))
        assert "Reason:" not in result["message"]

    async def test_approved_blocks(self, monkeypatch):
        result = await _check(monkeypatch, _list_response([_row(78, "2026-09-14", "approved", 1)]))
        assert result["outcome"] == reg.DUPLICATE_BLOCKED
        assert "already Approved" in result["message"]
        assert "Ref: REG-78" in result["message"]

    @pytest.mark.parametrize("status_name,label", [
        ("cancelled", "Cancelled"), ("canceled", "Cancelled"),
        ("rejected", "Rejected"), ("withdrawn", "Withdrawn"),
    ])
    async def test_ended_request_lets_a_new_one_through(self, monkeypatch, status_name, label):
        result = await _check(monkeypatch, _list_response([_row(60, "2026-09-14", status_name)]))
        assert result["outcome"] == reg.DUPLICATE_PRIOR
        assert f"was {label}" in result["message"]
        assert "new request is allowed" in result["message"]

    async def test_a_live_request_wins_over_a_cancelled_one_on_the_same_date(self, monkeypatch):
        rows = [_row(95, "2026-09-14", "cancelled"), _row(96, "2026-09-14", "pending")]
        result = await _check(monkeypatch, _list_response(rows))
        assert result["outcome"] == reg.DUPLICATE_BLOCKED
        assert result["existing_request"]["regularization_id"] == 96

    async def test_status_code_is_the_fallback_for_a_missing_name(self, monkeypatch):
        result = await _check(monkeypatch, _list_response([_row(92, "2026-09-14", None, 0)]))
        assert result["outcome"] == reg.DUPLICATE_BLOCKED

    async def test_an_unknown_status_blocks_rather_than_guessing(self, monkeypatch):
        result = await _check(monkeypatch, _list_response([_row(92, "2026-09-14", "on_hold")]))
        assert result["outcome"] == reg.DUPLICATE_BLOCKED
        assert "On Hold" in result["message"]

    async def test_apply_date_with_a_time_part_still_matches(self, monkeypatch):
        result = await _check(monkeypatch, _list_response([_row(92, "2026-09-14 00:00:00", "pending")]))
        assert result["outcome"] == reg.DUPLICATE_BLOCKED


class TestDuplicateFailsClosed:
    @pytest.mark.parametrize("exc", [
        erp_client.ErpApiTimeout("slow"), erp_client.ErpApiUnavailable("down"), RuntimeError("boom"),
    ])
    async def test_lookup_failure_is_unavailable(self, monkeypatch, exc):
        result = await _check(monkeypatch, exc=exc)
        assert result["outcome"] == reg.DUPLICATE_UNAVAILABLE
        assert "try again" in result["message"]
        assert "regularization form" in result["message"]

    async def test_expired_session_says_so(self, monkeypatch):
        result = await _check(monkeypatch, exc=erp_client.ErpApiUnauthorized("401"))
        assert result["outcome"] == reg.DUPLICATE_UNAVAILABLE
        assert "session has expired" in result["message"]

    @pytest.mark.parametrize("response", [
        {"http_status": 200, "body": {"success": False, "message": "nope"}},
        {"http_status": 422, "body": {"message": "bad"}},
        {"http_status": 200, "body": {"success": True, "data": {}}},
        {"http_status": 200, "body": None},
    ])
    async def test_an_unusable_answer_is_unavailable_not_no_duplicate(self, monkeypatch, response):
        result = await _check(monkeypatch, response)
        assert result["outcome"] == reg.DUPLICATE_UNAVAILABLE


# -- regularisation_eligibility_node -----------------------------------------

@pytest.fixture
def fixed_today(monkeypatch):
    monkeypatch.setattr(reg.attendance_mod, "_today", lambda: TODAY)


async def _classify(monkeypatch, query, duplicate, conversation_id, eligibility_reason=None):
    eligibility = AsyncMock(return_value=eligibility_reason)
    monkeypatch.setattr(reg, "_check_duplicate_date", AsyncMock(return_value={"rows": [], **duplicate}))
    # Quota (step 3) has its own tests; here it is configured with no limit.
    monkeypatch.setattr(reg, "_get_regularization_settings", AsyncMock(return_value={
        "available": True, "window_days": None, "limit": None, "cycle": None}))
    monkeypatch.setattr(reg, "_classify_and_check_eligibility", eligibility)
    slot_store.clear_slots("regularization", COMPANY_ID, conversation_id)
    writer = Writer()
    state = {"query": query, "company_id": COMPANY_ID, "conversation_id": conversation_id,
             "bearer_token": "tok", "usage_events": []}
    result = await reg.regularisation_eligibility_node(state, writer)
    return result, writer, eligibility


class TestClassifyGateRunsDuplicateFirst:
    async def test_pending_duplicate_stops_before_eligibility(self, monkeypatch, fixed_today):
        existing = _row(92, "2026-09-14", "pending")
        duplicate = {"outcome": reg.DUPLICATE_BLOCKED, "existing_request": existing,
                     "message": "You've already applied ... (Ref: 92)."}
        result, writer, eligibility = await _classify(
            monkeypatch, "regularize 14 sept 2026", duplicate, "dup-1")

        assert result["regularisation_blocked"] is True
        eligibility.assert_not_awaited()
        data = writer.done["data"]
        assert data["regularisation_classification_status"] is False
        assert data["duplicate_check"]["outcome"] == "blocked"
        assert data["duplicate_check"]["existing_request"] == existing
        assert not (slot_store.get_slots("regularization", COMPANY_ID, "dup-1") or {}).get(
            reg._PENDING_CLASSIFICATION_KEY)

    async def test_unavailable_stops_and_offers_retry_and_form(self, monkeypatch, fixed_today):
        duplicate = {"outcome": reg.DUPLICATE_UNAVAILABLE, "existing_request": None,
                     "message": "I couldn't check ..."}
        result, writer, eligibility = await _classify(
            monkeypatch, "regularize 20 sept 2026", duplicate, "dup-2")

        eligibility.assert_not_awaited()
        data = writer.done["data"]
        assert data["check_unavailable"] is True
        assert data["retry_available"] is True
        assert data["form_fallback"] is True

    async def test_cancelled_duplicate_notice_leads_the_eligible_reply(self, monkeypatch, fixed_today):
        duplicate = {"outcome": reg.DUPLICATE_PRIOR, "existing_request": _row(1, "2026-09-18", "cancelled"),
                     "message": "Your earlier request for 18 Sep 2026 (Ref: 1) was Cancelled, so a new request is allowed."}
        result, writer, eligibility = await _classify(
            monkeypatch, "regularize 18 sept 2026", duplicate, "dup-3")

        eligibility.assert_awaited_once()
        answer = writer.done["data"]["answer"]
        assert answer.startswith("Your earlier request for 18 Sep 2026")
        assert "eligible" in answer
        assert writer.done["data"]["regularisation_classification_status"] is True

    async def test_cancelled_duplicate_notice_leads_an_ineligible_reply(self, monkeypatch, fixed_today):
        duplicate = {"outcome": reg.DUPLICATE_PRIOR, "existing_request": _row(1, "2026-08-02", "cancelled"),
                     "message": "Your earlier request ... was Cancelled, so a new request is allowed."}
        result, writer, _ = await _classify(
            monkeypatch, "regularize 2 aug 2026", duplicate, "dup-4",
            eligibility_reason="I can't regularize 02 Aug 2026 — outside the window.")

        answer = writer.done["data"]["answer"]
        assert answer.index("was Cancelled") < answer.index("outside the window")
        assert writer.done["data"]["regularisation_classification_status"] is False

    async def test_no_date_never_calls_the_duplicate_check(self, monkeypatch, fixed_today):
        check = AsyncMock()
        monkeypatch.setattr(reg, "_check_duplicate_date", check)
        monkeypatch.setattr(reg, "_resolve_direct_entry_date_llm_fallback", AsyncMock(return_value=None))
        writer = Writer()
        await reg.regularisation_eligibility_node(
            {"query": "apply for regularization", "company_id": COMPANY_ID,
             "conversation_id": "dup-5", "bearer_token": "tok", "usage_events": []}, writer)
        check.assert_not_awaited()


# -- mid-flow date change (_fetch_prefill) -----------------------------------

class TestMidFlowDateChange:
    async def test_changing_to_a_pending_date_stops_without_fetching_punches(self, monkeypatch, fixed_today):
        conversation_id = "dup-mid-1"
        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,
        })
        llm = {"choices": [{"message": {"content": json.dumps({
            "action": "provide_info",
            "entries": [{"date": "2026-09-14", "start_time": None, "end_time": None, "reason": None}],
            "employee_name": None,
        })}}]}
        existing = _row(92, "2026-09-14", "pending")
        duplicate = {"outcome": reg.DUPLICATE_BLOCKED, "existing_request": existing,
                     "message": "You've already applied for regularization on 14 Sep 2026 (Ref: 92)."}
        punches = AsyncMock()
        writer = Writer()
        with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=llm)), \
\
             patch("services.regularisation_node._check_duplicate_date", new=AsyncMock(return_value=duplicate)), \
             patch("services.regularisation_node._get_attendance_prefill", new=punches):
            await reg.regularisation_node(
                {"query": "change the date to 14 sept 2026", "company_id": COMPANY_ID,
                 "conversation_id": conversation_id, "bearer_token": "tok", "usage_events": []},
                writer,
            )

        punches.assert_not_awaited()
        done = writer.done
        assert done["intent"] == "regularisation_classify"
        assert "Ref: 92" in done["data"]["answer"]
        assert done["data"]["duplicate_check"]["existing_request"] == existing


# -- my_regularisation_view_node ---------------------------------------------

class TestHistoryView:
    @pytest.mark.parametrize("query,expected", [
        ("my pending regularisation requests", "pending"),
        ("show approved regularizations", "approved"),
        ("show my canceled regularization requests", "cancelled"),
        ("Show my regularization requests", None),
        # A status QUESTION is not a filter: filtering it to approved would
        # answer "none" for a request that is still pending.
        ("Has my regularization request been approved?", None),
        ("are my regularizations approved?", None),
        # Reported live: listed every status.
        ("show my pending reqgulariztion", "pending"),
        # Status-word typos, and the word anywhere in the message.
        ("show my pendng regularizations", "pending"),
        ("show my aproved regularization", "approved"),
        ("my cancled regularizations", "cancelled"),
        ("show rejectd regularisation requests", "rejected"),
        ("my regularizations that are pending", "pending"),
        ("list my regularization requests which got cancelled", "cancelled"),
        ("what are my pending regularizations", "pending"),
        # "pending approval" is one status; two statuses at once list everything.
        ("show my pending approval regularizations", "pending"),
        ("show pending and approved regularizations", None),
        ("show all my regularizations", None),
    ])
    def test_status_filter_detection(self, query, expected):
        assert _requested_status_filter(query) == expected

    async def _run(self, monkeypatch, query, response):
        seen = {}

        async def fake(token, company_id=None, conversation_id=None, status=None):
            seen["status"] = status
            return response

        monkeypatch.setattr(erp_client, "get_my_regularizations", fake)
        writer = Writer()
        await my_regularisation_view_node(
            {"query": query, "company_id": COMPANY_ID, "conversation_id": "hist",
             "bearer_token": "tok", "usage_events": []}, writer)
        return seen, writer.done["data"]

    async def test_all_counts_pass_through_and_rows_are_most_recently_applied_first(self, monkeypatch):
        # Shape of the live payload (HA-697): created_at is the applied-on
        # date, and erp-api orders by it — NOT by apply_date (id 14, for
        # 18 Aug, was applied before id 15, for 31 Jul, so comes after it).
        def live(reg_id, apply_date, created_at, status_name, status):
            return {**_row(reg_id, apply_date, status_name, status),
                    "applied_to": "ABC Testing", "action_by": None, "created_at": created_at}

        rows = [live(1, "2026-07-01", "2026-07-22", "approved", 1),
                live(14, "2026-08-18", "2026-08-19", "pending", 0),
                live(22, "2026-08-15", "2026-08-31", "pending", 0),
                live(15, "2026-07-31", "2026-08-19", "pending", 0)]
        response = _list_response(rows, total_pending_regularizations=3,
                                  total_approved_regularizations=1,
                                  total_cancelled_regularizations=0,
                                  total_rejected_regularizations=0)
        seen, data = await self._run(monkeypatch, "Show my regularization requests", response)

        assert seen["status"] is None
        assert [r["regularization_id"] for r in data["regularizations"]] == [22, 15, 14, 1]
        assert data["total_regularizations"] == 4
        assert data["total_approved_regularizations"] == 1
        assert data["total_cancelled_regularizations"] == 0
        assert "(Ref: REG-22, applied 31-Aug-2026)" in data["answer"]
        first = data["regularizations"][0]
        # Every field erp-api sent is kept, for the UI's table ...
        assert first["applied_to"] == "ABC Testing"
        assert first["regularization_id"] == 22
        # ... plus the design's columns.
        assert first["reference_id"] == "REG-22"
        assert first["applied_by"] == "Ayush Jio (geo3)"
        assert first["applied_on"] == "2026-08-31"
        assert first["applied_on_display"] == "31-Aug-2026"
        assert first["apply_date_display"] == "15-Aug-2026"
        assert first["status_label"] == "Pending"

    async def test_the_reported_query_asks_erp_api_for_pending_only(self, monkeypatch):
        rows = [_row(131, "2026-09-18", "pending"), _row(130, "2026-09-10", "pending")]
        seen, data = await self._run(monkeypatch, "show my pending reqgulariztion",
                                     _list_response(rows, total_pending_regularizations=2))
        assert seen["status"] == "pending"
        assert data["status_filter"] == "pending"
        assert data["answer"].startswith("Here are your 2 pending regularization requests:")

    async def test_rows_of_another_status_are_never_listed_under_a_filter(self, monkeypatch):
        """Even if a deployment ignored ?status=, a pending list shows only pending."""
        rows = [_row(131, "2026-09-18", "pending"), _row(92, "2026-09-14", "cancelled")]
        _, data = await self._run(monkeypatch, "show my pending regularizations", _list_response(rows))
        assert [r["regularization_id"] for r in data["regularizations"]] == [131]
        assert "REG-92" not in data["answer"]

    async def test_a_refused_status_value_falls_back_to_all_and_filters_here(self, monkeypatch):
        """Live: status=cancelled answered "The selected status is invalid." and
        that sentence was the reply to "show my cancelled reqgulariztion"."""
        rows = [_row(131, "2026-09-18", "pending"), _row(92, "2026-09-14", "cancelled"),
                _row(90, "2026-09-07", "cancelled")]
        calls = []

        async def fake(token, company_id=None, conversation_id=None, status=None):
            calls.append(status)
            if status == "cancelled":
                return {"http_status": 422, "body": {"success": False,
                                                     "message": "The selected status is invalid."}}
            return _list_response(rows, total_pending_regularizations=1,
                                  total_cancelled_regularizations=2)

        monkeypatch.setattr(erp_client, "get_my_regularizations", fake)
        writer = Writer()
        await my_regularisation_view_node(
            {"query": "show my cancelled reqgulariztion", "company_id": COMPANY_ID,
             "conversation_id": "hist", "bearer_token": "tok", "usage_events": []}, writer)
        data = writer.done["data"]

        assert calls == ["cancelled", None]
        assert "invalid" not in data["answer"].lower()
        assert data["answer"].startswith("Here are your 2 cancelled regularization requests:")
        assert [r["regularization_id"] for r in data["regularizations"]] == [92, 90]
        assert data["total_regularizations"] == 2
        assert data["total_cancelled_regularizations"] == 2

    async def test_filtered_empty_state_names_the_status(self, monkeypatch):
        seen, data = await self._run(monkeypatch, "show my rejected regularization requests",
                                     _list_response([]))
        assert seen["status"] == "rejected"
        assert data["answer"] == "You don't have any rejected regularization requests."
        assert data["status_filter"] == "rejected"
        assert data["found"] is False
