"""Regression tests for services/slot_flow.py's _run_multi_entry_flow —
specifically, correcting a field (reason, start_time, end_time) on an entry
that's already COMPLETE and awaiting confirmation, without repeating the
date.

Confirmed live/reported: with exactly one regularisation entry already
fully filled in (awaiting confirmation), "actually change the reason to
traffic delay" (no date mentioned — the natural way to correct something
you're already looking at) came back "I couldn't tell which date that's
for — could you tell me the date as well?" and the correction was silently
dropped. `resolvable_existing` — the list of entries a date-less update can
attach to — only ever included entries that were still INCOMPLETE or
`_failed`, so a single already-complete entry was invisible to it even
though there was no actual ambiguity (there was only ONE entry, period).
Fixed by including ALL existing entries in `resolvable_existing` whenever
there's exactly one overall, regardless of completeness — the multi-entry
ambiguity check (2+ entries) is unaffected.
"""
import json
from unittest.mock import AsyncMock, patch

import pytest

import services.slot_flow as slot_flow
from services.regularisation_node import REGULARIZATION_CONFIG
from services import slot_store

COMPANY_ID = "test-co"


def _llm_response(action: str, entries: list[dict]):
    content = json.dumps({"action": action, "entries": entries, "employee_name": None})
    return {"choices": [{"message": {"content": content}}]}


async def _run_turn(conversation_id: str, query: str, action: str, entries: list[dict]):
    state = {
        "query": query, "company_id": COMPANY_ID, "conversation_id": conversation_id,
        "bearer_token": "fake", "usage_events": [],
    }
    with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=_llm_response(action, entries))):
        return await slot_flow.run_slot_flow(REGULARIZATION_CONFIG, state, lambda evt: None)


@pytest.fixture
def conversation_id(request):
    conv_id = f"slot-flow-correction-tests-{request.node.name}"
    slot_store.clear_slots("regularization", COMPANY_ID, conv_id)
    yield conv_id
    slot_store.clear_slots("regularization", COMPANY_ID, conv_id)


class TestCorrectingAnAlreadyCompleteEntry:

    def _seed_complete_entry(self, conversation_id):
        slot_store.set_slots("regularization", COMPANY_ID, conversation_id, {
            "entries": [{
                "date": "2026-08-15", "start_time": "09:00",
                "end_time": "18:00", "reason": "forgot to punch out",
            }],
            "employee_name": None,
        })

    @pytest.mark.asyncio
    async def test_correcting_reason_with_no_date_repeated_updates_the_entry(self, conversation_id):
        self._seed_complete_entry(conversation_id)

        result = await _run_turn(
            conversation_id, "actually change the reason to traffic delay",
            "provide_info",
            [{"date": None, "start_time": None, "end_time": None, "reason": "traffic delay"}],
        )

        assert "which date" not in result["response_text"]
        stored = slot_store.get_slots("regularization", COMPANY_ID, conversation_id)
        assert stored["entries"] == [{
            "date": "2026-08-15", "start_time": "09:00",
            "end_time": "18:00", "reason": "traffic delay",
        }]

    @pytest.mark.asyncio
    async def test_correcting_the_same_field_multiple_times_in_a_row(self, conversation_id):
        self._seed_complete_entry(conversation_id)

        await _run_turn(
            conversation_id, "actually change the reason to traffic delay",
            "provide_info",
            [{"date": None, "start_time": None, "end_time": None, "reason": "traffic delay"}],
        )
        await _run_turn(
            conversation_id, "no wait, make it personal work instead",
            "provide_info",
            [{"date": None, "start_time": None, "end_time": None, "reason": "personal work"}],
        )
        result = await _run_turn(
            conversation_id, "change start time to 10am and end time to 7pm",
            "provide_info",
            [{"date": None, "start_time": "10:00", "end_time": "19:00", "reason": None}],
        )

        assert "which date" not in result["response_text"]
        stored = slot_store.get_slots("regularization", COMPANY_ID, conversation_id)
        assert stored["entries"] == [{
            "date": "2026-08-15", "start_time": "10:00",
            "end_time": "19:00", "reason": "personal work",
        }]

    @pytest.mark.asyncio
    async def test_correcting_an_incomplete_entry_still_works_unchanged(self, conversation_id):
        # Same fix path, but the entry is still missing a reason — this
        # already worked before the fix and must keep working.
        slot_store.set_slots("regularization", COMPANY_ID, conversation_id, {
            "entries": [{
                "date": "2026-08-15", "start_time": "09:00",
                "end_time": "18:00", "reason": None,
            }],
            "employee_name": None,
        })

        result = await _run_turn(
            conversation_id, "forgot to punch out",
            "provide_info",
            [{"date": None, "start_time": None, "end_time": None, "reason": "forgot to punch out"}],
        )

        assert "which date" not in result["response_text"]
        stored = slot_store.get_slots("regularization", COMPANY_ID, conversation_id)
        assert stored["entries"][0]["reason"] == "forgot to punch out"

    @pytest.mark.asyncio
    async def test_ambiguity_between_two_incomplete_entries_is_still_caught(self, conversation_id):
        # Two entries BOTH still incomplete — a date-less update is
        # genuinely ambiguous here (which one's reason?) and must still ask
        # which date it applies to, unaffected by the single-entry fix
        # (this pre-existing behavior only changes when there's exactly ONE
        # entry overall).
        slot_store.set_slots("regularization", COMPANY_ID, conversation_id, {
            "entries": [
                {"date": "2026-08-15", "start_time": "09:00", "end_time": "18:00", "reason": None},
                {"date": "2026-08-16", "start_time": "09:00", "end_time": "18:00", "reason": None},
            ],
            "employee_name": None,
        })

        result = await _run_turn(
            conversation_id, "change the reason to sick leave",
            "provide_info",
            [{"date": None, "start_time": None, "end_time": None, "reason": "sick leave"}],
        )

        assert "which date" in result["response_text"]
        stored = slot_store.get_slots("regularization", COMPANY_ID, conversation_id)
        # Neither entry was touched — the update was correctly held back
        # rather than guessed onto the wrong one.
        assert stored["entries"][0]["reason"] is None
        assert stored["entries"][1]["reason"] is None
