"""Regression tests for services/regularisation_node.py's explicit
new-request reset — _is_explicit_new_request and the reset block in
regularisation_node() that clears stale slot state before the turn is
processed.

Confirmed live/reported: with a regularisation entry already sitting in
slot_store from an earlier turn (complete and awaiting confirmation, or
just incomplete/stale), "I want to apply for a new regularization" (or the
user's own literal wording, "I want to apply new regularisation") — no
date/time/reason mentioned — had the LLM correctly extract nothing new
(there genuinely isn't anything to extract from that sentence), so the flow
just re-displayed the OLD entry unchanged ("Shall I go ahead and submit
this?" for a request the employee never meant to resume) instead of
resetting and asking "which date(s) would you like to regularize?" the way
a first-ever regularisation message would.
"""
import json
from unittest.mock import AsyncMock, patch

import pytest

from services.regularisation_node import (
    regularisation_node, _is_explicit_new_request, _PUNCH_PREVIEW_NAMESPACE,
)
from services import slot_store

COMPANY_ID = "test-co"


class TestIsExplicitNewRequestDetection:

    @pytest.mark.parametrize("query", [
        "I want to apply for a new regularization",
        "I want to apply new regularisation",
        "start a new regularization request",
        "another regularization request",
        "can I raise a fresh regularization request",
        "let's start over",
        "start over",
        "start again",
    ])
    def test_recognizes_new_request_phrasing(self, query):
        assert _is_explicit_new_request(query) is True

    @pytest.mark.parametrize("query", [
        # Ordinary corrections to the entry already in progress must NOT
        # trigger a reset — these are exactly what _build_prompt's own
        # entry-update rules already handle.
        "actually change the reason to traffic delay",
        "change the date to 20th",
        "10am to 7pm",
        "forgot to punch out",
        "yes submit it",
        "cancel",
        "17 sep",
    ])
    def test_ordinary_replies_are_not_treated_as_new_request(self, query):
        assert _is_explicit_new_request(query) is False


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


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


class TestNewRequestResetsStaleState:

    @pytest.mark.asyncio
    async def test_bare_new_request_resets_a_complete_pending_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,
        })

        state = {
            "query": "I want to apply new regularisation",
            "company_id": COMPANY_ID, "conversation_id": conversation_id,
            "bearer_token": "fake", "usage_events": [],
        }
        fake_response = _llm_response("provide_info", [])

        with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=fake_response)):
            result = await regularisation_node(state, lambda evt: None)

        assert "which date" in result["response_text"]
        assert "2026-08-15" not in result["response_text"]
        stored = slot_store.get_slots("regularization", COMPANY_ID, conversation_id)
        assert stored["entries"] == []

    @pytest.mark.asyncio
    async def test_bare_new_request_resets_an_incomplete_pending_entry(self, conversation_id):
        slot_store.set_slots("regularization", COMPANY_ID, conversation_id, {
            "entries": [{
                "date": "2026-08-15", "start_time": None,
                "end_time": None, "reason": None,
            }],
            "employee_name": None,
        })

        state = {
            "query": "start a new regularization request",
            "company_id": COMPANY_ID, "conversation_id": conversation_id,
            "bearer_token": "fake", "usage_events": [],
        }
        fake_response = _llm_response("provide_info", [])

        with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=fake_response)):
            result = await regularisation_node(state, lambda evt: None)

        assert "which date" in result["response_text"]
        stored = slot_store.get_slots("regularization", COMPANY_ID, conversation_id)
        assert stored["entries"] == []

    @pytest.mark.asyncio
    async def test_new_request_with_no_pending_state_behaves_normally(self, conversation_id):
        # Nothing to reset — must not error or change behavior for a
        # genuinely first-ever "new regularization" message.
        state = {
            "query": "I want to apply for a new regularization",
            "company_id": COMPANY_ID, "conversation_id": conversation_id,
            "bearer_token": "fake", "usage_events": [],
        }
        fake_response = _llm_response("provide_info", [])

        with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=fake_response)):
            result = await regularisation_node(state, lambda evt: None)

        assert "which date" in result["response_text"]

    @pytest.mark.asyncio
    async def test_ordinary_correction_does_not_trigger_a_reset(self, conversation_id):
        # Control: an ordinary correction to the SAME pending entry must
        # keep working exactly as before — no reset, no "which date?".
        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,
        })

        state = {
            "query": "actually change the reason to traffic delay",
            "company_id": COMPANY_ID, "conversation_id": conversation_id,
            "bearer_token": "fake", "usage_events": [],
        }
        fake_response = _llm_response(
            "provide_info",
            [{"date": None, "start_time": None, "end_time": None, "reason": "traffic delay"}],
        )

        with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=fake_response)), \
             patch("services.regularisation_node._get_attendance_prefill",
                   new=AsyncMock(return_value={"slot_prefill": {}, "preview": {}})), \
             patch("services.regularisation_node._check_duplicate_date",
                   new=AsyncMock(return_value={"outcome": "none", "message": None,
                                               "existing_request": None, "rows": []})), \
             patch("services.regularisation_node._get_regularization_settings",
                   new=AsyncMock(return_value={"available": True, "window_days": None,
                                               "limit": None, "cycle": None})):
            result = await regularisation_node(state, lambda evt: None)

        assert "which date" not in result["response_text"]
        stored = slot_store.get_slots("regularization", COMPANY_ID, conversation_id)
        assert stored["entries"][0]["reason"] == "traffic delay"
        assert stored["entries"][0]["date"] == "2026-08-15"
