"""A regularization the backend REFUSED is not resubmitted unchanged.

Reported live: erp-api answered Confirm & Submit with "Regularization has
already been applied for the selected date". The entry was kept for a retry,
and every later "yes" / "submit" / Confirm & Submit posted the identical
request and got the identical refusal — the employee was stuck in a loop.

Now a refusal (a 4xx with erp-api's reason) is remembered with exactly what
was refused. Confirming that same request again explains why it can't be sent
as it is, without posting it. Changing a detail sends it again, cancel ends
the flow, and a timeout or outage (not a refusal) still retries as before.
"""
import json
from unittest.mock import AsyncMock, patch

import pytest

import services.regularisation_node as reg
from services import slot_store

COMPANY_ID = "refused-co"
ALREADY_APPLIED = "Regularization has already been applied for the selected date"
ENTRY = {"date": "2026-09-12", "start_time": "10:00", "end_time": "19:00",
         "reason": "Demo testing", "_prefill_fetched": True, "_prevalidated": True}


def _llm(action, entries=None):
    return {"choices": [{"message": {"content": json.dumps(
        {"action": action, "entries": entries or [], "employee_name": None})}}]}


@pytest.fixture
def erp(monkeypatch):
    state = {"posts": [], "answer": {"http_status": 400,
                                     "body": {"success": False, "message": ALREADY_APPLIED}}}

    async def fake_post(token, payload, company_id=None, conversation_id=None):
        state["posts"].append(dict(payload))
        answer = state["answer"]
        if isinstance(answer, Exception):
            raise answer
        return answer

    monkeypatch.setattr(reg.attendance_client, "post_regularization", fake_post)

    # A changed date re-runs the HA-697 duplicate-date and quota checks, which
    # call erp-api; here there is no existing request and no quota to enforce.
    # (Guarded: a branch without those checks has neither function.)
    if hasattr(reg, "_check_duplicate_date"):
        monkeypatch.setattr(reg, "_check_duplicate_date", AsyncMock(return_value={
            "outcome": "none", "message": None, "existing_request": None, "rows": []}))
    if hasattr(reg, "_get_regularization_settings"):
        monkeypatch.setattr(reg, "_get_regularization_settings", AsyncMock(return_value={
            "available": True, "window_days": None, "limit": None, "cycle": None}))
    return state


@pytest.fixture
def conversation(request):
    cid = f"refused-{request.node.name}"
    slot_store.set_slots("regularization", COMPANY_ID, cid,
                         {"entries": [dict(ENTRY)], "employee_name": None})
    yield cid
    slot_store.clear_slots("regularization", COMPANY_ID, cid)


async def _turn(conversation_id, query, action, entries=None):
    events = []
    with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=_llm(action, entries))), \
         patch("services.regularisation_node._get_attendance_prefill",
               new=AsyncMock(return_value={"slot_prefill": {}, "preview": {}})):
        await reg.regularisation_node(
            {"query": query, "company_id": COMPANY_ID, "conversation_id": conversation_id,
             "bearer_token": "t", "usage_events": []}, events.append)
    return [e for e in events if e.get("type") == "done"][-1]


CONFIRM_BUTTON = json.dumps({"action": "confirm", "date": "2026-09-12"})


class TestNoLoop:
    async def test_the_first_confirm_submits_and_shows_erp_apis_reason(self, erp, conversation):
        done = await _turn(conversation, CONFIRM_BUTTON, "confirm")

        assert len(erp["posts"]) == 1
        assert ALREADY_APPLIED in done["data"]["answer"]

    @pytest.mark.parametrize("reply", ["yes", "submit", "confirm and submit", CONFIRM_BUTTON])
    async def test_confirming_the_refused_request_again_does_not_resend_it(self, erp, conversation, reply):
        await _turn(conversation, CONFIRM_BUTTON, "confirm")
        done = await _turn(conversation, reply, "confirm")

        assert len(erp["posts"]) == 1, "the identical refused request was posted again"
        answer = done["data"]["answer"]
        assert ALREADY_APPLIED in answer
        assert "Change the date" in answer and "cancel" in answer
        assert done["data"]["resubmit_blocked"] is True
        # Still there, so a correction can be made to it.
        stored = slot_store.get_slots("regularization", COMPANY_ID, conversation)
        assert stored["entries"][0]["date"] == "2026-09-12"

    async def test_many_confirms_still_post_once(self, erp, conversation):
        for reply in (CONFIRM_BUTTON, "yes", "submit", CONFIRM_BUTTON, "yes"):
            await _turn(conversation, reply, "confirm")
        assert len(erp["posts"]) == 1


class TestTheWaysOut:
    async def test_a_different_date_is_submitted(self, erp, conversation):
        await _turn(conversation, CONFIRM_BUTTON, "confirm")
        erp["answer"] = {"http_status": 200, "body": {"success": True, "data": {}}}
        # The old date's times are not carried to a new date (slot_flow's own
        # rule), so the correction names them; the reason is carried.
        done = await _turn(conversation, "change the date to 11 sept, 10am to 7pm, and submit", "confirm",
                           [{"date": "2026-09-11", "start_time": "10:00", "end_time": "19:00", "reason": None}])

        assert [p["apply_date"] for p in erp["posts"]] == ["2026-09-12", "2026-09-11"]
        assert done["intent"] == "regularization_submitted"

    async def test_a_changed_time_on_the_same_date_is_submitted(self, erp, conversation):
        await _turn(conversation, CONFIRM_BUTTON, "confirm")
        await _turn(conversation, "make the out time 18:30", "provide_info",
                    [{"date": "2026-09-12", "start_time": None, "end_time": "18:30", "reason": None}])
        await _turn(conversation, "yes", "confirm")

        assert [p["to_time"] for p in erp["posts"]] == ["19:00", "18:30"]

    async def test_cancel_ends_the_flow(self, erp, conversation):
        await _turn(conversation, CONFIRM_BUTTON, "confirm")
        done = await _turn(conversation, "cancel", "cancel")

        assert done["intent"] == "regularization_cancelled"
        assert not (slot_store.get_slots("regularization", COMPANY_ID, conversation) or {}).get("entries")

    async def test_a_timeout_is_not_a_refusal_and_still_retries(self, erp, conversation):
        erp["answer"] = reg.attendance_client.ErpApiTimeout("slow")
        await _turn(conversation, CONFIRM_BUTTON, "confirm")
        erp["answer"] = {"http_status": 200, "body": {"success": True, "data": {}}}
        done = await _turn(conversation, "yes", "confirm")

        assert len(erp["posts"]) == 2
        assert done["intent"] == "regularization_submitted"

    async def test_a_server_error_is_not_a_refusal_either(self, erp, conversation):
        erp["answer"] = {"http_status": 500, "body": {"success": False, "message": "Server Error"}}
        await _turn(conversation, CONFIRM_BUTTON, "confirm")
        await _turn(conversation, "yes", "confirm")

        assert len(erp["posts"]) == 2
