"""A time that isn't a time of day never reaches the summary (negative run,
28 Oct 2026, #25).

"in 25:00 out 18:30" was shown as "Here's the regularization request I'll
submit: 20 Oct 2026: 25:00–18:30 ... Shall I go ahead and submit this?" -
time_24h hands unparseable input back unchanged, and the pre-submit check
only ran at the "yes". Now the check runs before the summary too, and knows
an impossible time.
"""
import json
from unittest.mock import AsyncMock, patch

import pytest

import services.regularisation_node as reg
from services import slot_store

COMPANY_ID = "invalid-time-co"
SHIFT_BODY = {"http_status": 200, "body": {"success": True, "data": {"shift": {
    "shift_name": "General Shift", "start_time": "09:30:00", "end_time": "18:30:00"}}}}
NEEDS_TIMES = {"date": "2026-10-20", "reason": "forgot to punch",
               "_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 posts(monkeypatch):
    sent = []

    async def fake_post(token, payload, company_id=None, conversation_id=None):
        sent.append(dict(payload))
        return {"http_status": 200, "body": {"success": True, "data": {"regularization_id": 1}}}

    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 sent


@pytest.fixture
def conversation(request):
    cid = f"invalid-time-{request.node.name}"
    slot_store.set_slots("regularization", COMPANY_ID, cid,
                         {"entries": [dict(NEEDS_TIMES)], "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]


class TestTheRule:
    @pytest.mark.parametrize("start,end,fields", [
        ("25:00", "18:30", ["start_time"]),
        ("09:30", "24:30", ["end_time"]),
        ("9:61", "18:00", ["start_time"]),
        ("banana", "noonish", ["start_time", "end_time"]),
    ])
    def test_an_impossible_time_is_named(self, start, end, fields):
        problem = reg._invalid_time_problem({"start_time": start, "end_time": end})
        assert problem["fields"] == fields
        assert "isn't a valid time of day" in problem["message"]

    @pytest.mark.parametrize("start,end", [
        ("09:30", "18:30"), ("9:30 am", "6:30 pm"), ("10", "23"), ("2300", "23:30"),
        ("noon", "18:00"),
        # Overnight is a separate, undecided question (#24) - not this rule's.
        ("21:00", "08:00"),
    ])
    def test_every_real_way_of_writing_a_time_passes(self, start, end):
        assert reg._invalid_time_problem({"start_time": start, "end_time": end}) is None

    def test_missing_times_are_left_to_the_missing_field_prompt(self):
        assert reg._invalid_time_problem({"start_time": None, "end_time": ""}) is None


class TestTheFlow:
    async def test_the_summary_is_never_offered_with_an_impossible_time(self, posts, conversation):
        done = await _turn(conversation, "in 25:00 out 18:30", "provide_info",
                           [{"date": "2026-10-20", "start_time": "25:00", "end_time": "18:30"}])
        assert done["intent"] == "regularization_correction_required", done["data"]["answer"]
        assert "Shall I go ahead" not in done["data"]["answer"]
        assert "isn't a valid time of day" in done["data"]["answer"]
        assert done["data"]["fields_to_correct"] == ["start_time"]
        assert posts == []

    async def test_a_valid_time_still_reaches_the_summary(self, posts, conversation):
        done = await _turn(conversation, "in 09:30 out 18:30", "provide_info",
                           [{"date": "2026-10-20", "start_time": "09:30", "end_time": "18:30"}])
        assert done["intent"] == "regularization_awaiting_confirmation", done["data"]["answer"]
        assert posts == []
