"""A submit refused because of the SHIFT brings the form back (2026-10-06).

QA: Confirm & Submit -> "Regularization not submitted. Sorry, I wasn't able to
submit your regularization request. - No sessions configured for the assigned
split shift." The times entered didn't fit the employee's shift, and the
reply was a dead end. Now a shift/timing refusal returns the FORM (status
"correction_required", start/end time to correct) with the employee's shift
from /shift-details, and erp-api's own reason. An unchanged confirm is not
re-sent; corrected times are. Refusals the form can't fix keep the old reply.
"""
import json
from unittest.mock import AsyncMock, patch

import pytest

import services.regularisation_node as reg
from services import slot_store

COMPANY_ID = "shift-refusal-co"
SPLIT_SHIFT = "No sessions configured for the assigned split shift."
# Times OUTSIDE the General-Shift below (09:00-18:30 would contain 10:14-15:14,
# so these were moved out): a shift refusal the employee can genuinely fix in
# the form, which is what this file is about. A shift refusal whose times
# already FIT the shift is the opposite case - nothing to correct - and is
# covered by test_regularisation_split_shift.py.
ENTRY = {"date": "2026-10-01", "start_time": "06:14", "end_time": "08:14",
         "reason": "client visit", "_prefill_fetched": True, "_prevalidated": True}
SHIFT_BODY = {"http_status": 200, "body": {"success": True, "data": {"shift": {
    "shift_name": "General-Shift", "start_time": "09:00:00", "end_time": "18:30:00"}}}}


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": 422,
                                     "body": {"success": False, "message": SPLIT_SHIFT}}}

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

    monkeypatch.setattr(reg.attendance_client, "post_regularization", fake_post)
    monkeypatch.setattr(reg.attendance_client, "get_active_shift", AsyncMock(return_value=SHIFT_BODY))
    monkeypatch.setattr(reg, "_check_duplicate_date", AsyncMock(return_value={
        "outcome": "none", "message": None, "existing_request": None, "rows": []}))
    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"shiftref-{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)
    done = [e for e in events if e.get("type") == "done"][-1]
    cards = [e for e in events if e.get("type") == "regularization_card"]
    return done, (cards[-1]["data"] if cards else None)


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


class TestShiftRefusalBringsTheFormBack:
    async def test_the_form_comes_back_with_what_to_correct(self, erp, conversation):
        done, card = await _turn(conversation, CONFIRM_BUTTON, "confirm")

        assert len(erp["posts"]) == 1
        assert done["intent"] == "regularization_correction_required"
        answer = done["data"]["answer"]
        assert answer.startswith(SPLIT_SHIFT)
        assert "(your shift: General-Shift, 9:00 AM to 6:30 PM)" in answer
        assert "correct the start (in) time and end (out) time in the form below" in answer
        assert "wasn't able to submit" not in answer
        assert done["data"]["fields_to_correct"] == ["end_time", "start_time"]

        assert card["status"] == "correction_required"
        assert card["actions"] == ["edit", "confirm", "cancel"]
        row = card["entries"][0]
        assert row["editable"] is True and row["fields_to_correct"] == ["start_time", "end_time"]
        assert (row["start_time"], row["end_time"]) == ("06:14", "08:14"), "kept for editing"

    async def test_confirming_the_same_times_again_sends_nothing(self, erp, conversation):
        await _turn(conversation, CONFIRM_BUTTON, "confirm")
        done, card = await _turn(conversation, "yes", "confirm")

        assert len(erp["posts"]) == 1
        assert done["intent"] == "regularization_correction_required"
        assert card["status"] == "correction_required"

    async def test_corrected_times_are_submitted(self, erp, conversation):
        await _turn(conversation, CONFIRM_BUTTON, "confirm")
        erp["answer"] = {"http_status": 200, "body": {"success": True, "data": {}}}
        await _turn(conversation, "make it 9:00 to 18:30", "provide_info",
                    [{"date": "2026-10-01", "start_time": "09:00", "end_time": "18:30", "reason": None}])
        done, _ = await _turn(conversation, "yes", "confirm")

        assert [(p["from_time"], p["to_time"]) for p in erp["posts"]] == [
            ("06:14", "08:14"), ("09:00", "18:30")]
        assert done["intent"] == "regularization_submitted"


class TestOtherRefusalsAreUnchanged:
    @pytest.mark.parametrize("message", ["Regularization period has expired",
                                         "Attendance is locked for this date. Contact HR."])
    async def test_not_a_form_correction(self, erp, conversation, message):
        erp["answer"] = {"http_status": 422, "body": {"success": False, "message": message}}
        done, card = await _turn(conversation, CONFIRM_BUTTON, "confirm")

        assert done["intent"] == "regularization_partial"
        assert message in done["data"]["answer"]
        assert card["status"] == "partial"


class TestClassifier:
    @pytest.mark.parametrize("error", [SPLIT_SHIFT, "Punch out time must be within working hours",
                                       "The selected time is outside your shift"])
    def test_shift_and_timing_refusals(self, error):
        fix = reg._shift_correction(error, None)
        assert fix["fields"] == ["start_time", "end_time"]

    @pytest.mark.parametrize("error", ["Regularization period has expired",
                                       "Regularization has already been applied for the selected date",
                                       "Attendance is locked for this date. Contact HR."])
    def test_other_refusals(self, error):
        assert reg._shift_correction(error, None) is None
