"""Fixes from the HA-697 QA run of 2026-10-06 (test-case sheet, Run 1).

  TC-002c "List my attendance correction requests"  -> went to attendance
  TC-002d "mere regularization dikhao"               -> "unclear", no answer
  TC-025  earlier Rejected request                   -> rejection reason not shown
  TC-053  out time before in time                    -> dead-end "not submitted";
                                                        now only the times are asked again
  TC-056  reason over 500 characters                 -> the model SHORTENED the reason and
                                                        it was submitted; now sent exactly as
                                                        typed, and erp-api's length rule asks
                                                        for the reason only
"""
import json
from unittest.mock import AsyncMock, patch

import pytest

import services.classify_node as classify_node
import services.regularisation_node as reg
from services import slot_store


class TestSynonymsAndHinglish:
    @pytest.mark.parametrize("raw,folded", [
        ("list my attendance correction requests", "list my regularization requests"),
        ("show my attendance corrections", "show my regularizations"),
        ("mere regularization dikhao", "show my regularization"),
        ("meri pending regularization dikhao", "show my pending regularization"),
        ("apni regularization batao", "show my regularization"),
    ])
    def test_fold(self, raw, folded):
        assert classify_node._fold_regularisation_synonyms(raw) == folded

    @pytest.mark.parametrize("raw", ["show my attendance for 29 sept", "mere leave dikhao"])
    def test_unrelated_text_is_untouched(self, raw):
        assert classify_node._fold_regularisation_synonyms(raw) == raw

    @pytest.mark.parametrize("llm_label", ["attendance", "unclear"])
    @pytest.mark.parametrize("query", ["List my attendance correction requests",
                                       "mere regularization dikhao"])
    async def test_routes_to_the_view_whatever_the_llm_says(self, monkeypatch, llm_label, query):
        async def _no_shift(q):
            return None, 0.0, None

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

        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _classify)
        out = await classify_node.classify_node(
            {"query": query, "company_id": 1, "conversation_id": f"syn-{llm_label}-{len(query)}",
             "bearer_token": "t", "usage_events": [], "is_manager": False, "last_intent": None},
            lambda e: None)
        assert out["intent"] == "my_regularisation_view"


class TestEarlierRejectionReason:
    async def test_shown_in_the_notice_and_on_the_card(self, monkeypatch):
        rows = [{"regularization_id": 138, "apply_date": "2026-09-22", "status_name": "rejected",
                 "reason": "client visit", "rejection_reason": "No gate-pass entry for the client visit"}]

        async def mine(token, **kw):
            return {"http_status": 200, "body": {"success": True, "data": {"regularizations": rows}}}

        monkeypatch.setattr(reg.attendance_client, "get_my_regularizations", mine)
        result = await reg._check_duplicate_date("2026-09-22", bearer_token="t", company_id=1,
                                                 conversation_id="c")
        assert result["message"] == (
            "Your earlier request for 22-Sep-2026 (Ref: REG-138) was Rejected (reason: No gate-pass "
            "entry for the client visit), so a new request is allowed.")
        card = reg._duplicate_check_data(result)["existing_request_card"]
        assert card["rejection_reason"] == "No gate-pass entry for the client visit"


class TestFormCorrections:
    @pytest.mark.parametrize("error,fields", [
        ("The to time must be a time after from time.", ["start_time", "end_time"]),
        ("The from time must be before to time", ["start_time", "end_time"]),
        ("The reason may not be greater than 500 characters.", ["reason"]),
        ("No sessions configured for the assigned split shift.", ["start_time", "end_time"]),
    ])
    def test_correctable(self, error, fields):
        assert reg._form_correction(error, None)["fields"] == fields

    @pytest.mark.parametrize("error", ["Regularization period has expired",
                                       "Attendance is locked for this date. Contact HR."])
    def test_not_correctable(self, error):
        assert reg._form_correction(error, None) is None


class TestVerbatimReason:
    @pytest.mark.parametrize("query,reason", [
        ("In time 9:30 AM, out time 6:30 PM, reason: Forgot to punch out because of a long meeting.",
         "Forgot to punch out because of a long meeting"),
        ('reason is "missed punch"', "missed punch"),
        ("reason - client visit at the Pune office", "client visit at the Pune office"),
    ])
    def test_explicit_reason_is_taken_as_typed(self, query, reason):
        assert reg._verbatim_reason(query) == {"reason": reason}

    @pytest.mark.parametrize("query", ["Reason: '   '", "change the reason to fever",
                                       "the reason for this is traffic", "9 to 6 forgot to punch out"])
    def test_not_explicit_or_blank(self, query):
        assert reg._verbatim_reason(query) is None

    async def test_a_long_reason_is_submitted_unshortened_then_asked_again(self, monkeypatch):
        """The model returns a SHORT reason; what is stored and posted is the
        employee's full text, and erp-api's length rule brings back the form
        with only the reason to fix."""
        long_reason = "Forgot to punch out because " + "the client meeting ran late " * 30
        posts = []

        async def post(token, payload, company_id=None, conversation_id=None):
            posts.append(dict(payload))
            if len(payload["reason"]) > 500:
                return {"http_status": 422, "body": {"success": False,
                        "message": "The reason may not be greater than 500 characters."}}
            return {"http_status": 200, "body": {"success": True, "data": {}}}

        monkeypatch.setattr(reg.attendance_client, "post_regularization", post)
        monkeypatch.setattr(reg.attendance_client, "get_active_shift", AsyncMock(side_effect=Exception("x")))
        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}))
        conv = "verbatim-1"
        slot_store.set_slots("regularization", "vb-co", conv, {
            "entries": [{"date": "2026-09-30", "_prefill_fetched": True, "_prevalidated": True}]})

        def _llm(action, entries):
            return {"choices": [{"message": {"content": json.dumps(
                {"action": action, "entries": entries, "employee_name": None})}}]}

        async def turn(query, llm):
            events = []
            with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=llm)), \
                 patch("services.regularisation_node._get_attendance_prefill",
                       new=AsyncMock(return_value={"slot_prefill": {}, "preview": {}})):
                await reg.regularisation_node(
                    {"query": query, "company_id": "vb-co", "conversation_id": conv,
                     "bearer_token": "t", "usage_events": []}, events.append)
            return [e for e in events if e.get("type") == "done"][-1]

        await turn(f"In time 9:30 AM, out time 6:30 PM, reason: {long_reason}", _llm("provide_info", [
            {"date": "2026-09-30", "start_time": "09:30", "end_time": "18:30",
             "reason": "forgot to punch out, meeting ran late"}]))
        stored = slot_store.get_slots("regularization", "vb-co", conv)["entries"][0]
        assert stored["reason"] == long_reason.strip(), "the employee's words, not the model's summary"

        done = await turn("yes", _llm("confirm", []))
        # Over erp-api's 500-character limit: stopped BEFORE sending now
        # (regularisation_node._pre_submit_problem), with only the reason to fix.
        assert posts == []
        assert done["intent"] == "regularization_correction_required"
        assert done["data"]["fields_to_correct"] == ["reason"]
        assert "the limit is 500" in done["data"]["answer"]
        slot_store.clear_slots("regularization", "vb-co", conv)


# QA TC-055 (Oct 14): "Reason: '   '" - _verbatim_reason read it as no reason,
# but the LLM extraction kept the quotes and the summary offered to submit them.
@pytest.mark.parametrize("value", ["'   '", "\"\"", "...", " - ", "   "])
def test_a_reason_with_no_words_is_blank(value):
    import services.regularisation_node as reg_node
    assert reg_node._clean_entry_field("reason", value) is None


@pytest.mark.parametrize("value", ["forgot to punch out", "ok", "N/A", "late - traffic"])
def test_a_real_reason_is_kept(value):
    import services.regularisation_node as reg_node
    assert reg_node._clean_entry_field("reason", value) == value
