"""08-Oct live reports: a future date answered with the previous request's form
("stuck in the same loop"), "my regularization" answered with a menu, and
"apply for 10 oct" after a regularization reply opening the LEAVE form."""
import pytest

import services.classify_node as cn
import services.slot_flow as sf
from services import slot_store


@pytest.fixture
def llm(monkeypatch):
    def _install(label):
        async def _no_shift(q):
            return None, 0.0, None

        async def _classify(prompt, labels, fallback_label="unknown"):
            return label, None, False

        monkeypatch.setattr(cn.ai_service, "classify_shift_intent", _no_shift)
        monkeypatch.setattr(cn, "classify_intent_structured", _classify)
    return _install


async def _route(query, last_intent=None, conv="oct08", slots=None):
    if slots is not None:
        slot_store.set_slots("regularization", 1, conv, slots)
    out = await cn.classify_node(
        {"query": query, "company_id": 1, "conversation_id": conv, "bearer_token": "t",
         "usage_events": [], "is_manager": False, "last_intent": last_intent},
        lambda e: None)
    return out["intent"]


class TestMyRegularization:
    @pytest.mark.parametrize("query", ["my regularization", "my regularizations", "my regulrizations"])
    async def test_is_the_list(self, llm, query):
        llm("regularisation")
        assert await _route(query) == "my_regularisation_view"

    async def test_even_while_a_request_is_in_progress(self, llm):
        llm("regularisation")
        slots = {"entries": [{"date": "2026-10-08", "start_time": "15:00", "end_time": "20:00",
                              "reason": "Missed punch-in"}], "employee_name": None}
        assert await _route("my regularization", conv="oct08-mid", slots=slots) == "my_regularisation_view"

    def test_bare_regularization_still_gets_the_menu(self):
        from services.bare_verb_config import detect_bare_verb_query
        assert detect_bare_verb_query("regularization") == "regularisation"
        assert detect_bare_verb_query("my regularization") is None


class TestApplyForADateAfterARegularizationReply:
    @pytest.mark.parametrize("query", ["apply for 10 oct", "apply 6 oct", "apply on 2nd october"])
    async def test_continues_the_regularization(self, llm, query):
        llm("apply_leave")
        assert await _route(query, last_intent="regularisation_classify") == "regularisation"

    async def test_after_a_leave_reply_it_is_still_leave(self, llm):
        llm("apply_leave")
        assert await _route("apply for 10 oct", last_intent="leave_balance") == "apply_leave"

    @pytest.mark.parametrize("query", ["apply leave for 10 oct", "apply sick leave tomorrow"])
    def test_a_named_leave_is_not_bare(self, query):
        assert not cn._BARE_APPLY_FOR_DATE_RE.match(query)


FORM_TEXT = ("Date: 04 Oct 2026\nFrom Time: 3:00 PM\nTo Time: 8:00 PM\n"
             "Shift Timing: QA Team - QA 2nd \u00b7 3:00 PM \u00b7 8:00 PM\n"
             "Reason / Comment: Missed punch-in\nmore of the reason")


class TestTheFormsLabelledText:
    """Live: the form submitted "Date: / From Time: / To Time: / Shift Timing:
    / Reason / Comment:" as text, the model read nothing from it, and the
    reply was "I still need the start time, end time and reason"."""

    def test_read_as_the_form_entry(self):
        from datetime import date
        import services.regularisation_node as reg
        assert reg._labelled_form_entry(FORM_TEXT, date(2026, 10, 8)) == {
            "date": "2026-10-04", "start_time": "15:00", "end_time": "20:00",
            "reason": "Missed punch-in more of the reason"}

    @pytest.mark.parametrize("query", ["apply for 10 oct", "date: tomorrow", "Reason: forgot"])
    def test_not_the_form(self, query):
        from datetime import date
        import services.regularisation_node as reg
        assert reg._labelled_form_entry(query, date(2026, 10, 8)) is None

    async def test_routed_to_regularization_with_nothing_stored(self, llm):
        llm("attendance")
        assert await _route(FORM_TEXT, conv="oct08-form") == "regularisation"

    def test_a_reason_over_500_characters_is_stopped_before_sending(self):
        import services.regularisation_node as reg
        fix = reg._pre_submit_problem({"date": "2026-10-04", "start_time": "15:00",
                                       "end_time": "20:00", "reason": "x" * 639})
        assert fix["fields"] == ["reason"] and "639 characters" in fix["message"]
