"""Confirm & Submit on the regularization confirmation card must submit.

Reported live: "Confirm & Submit" answered "Here's the regularization request
I'll submit ... Shall I go ahead and submit this?" and the "yes" after it
answered with an empty "Review Before Submitting" form — "I don't have any
regularization details to submit yet". Nothing was ever submitted.

Two causes, both reproduced:
  * the card can post its fields back as the FORM payload (no "action"),
    which was handled as a save and re-showed the summary — every time;
  * the stored entry was lost between turns: on that server Redis was not
    reachable, and slot_store turned every get/set into a silent no-op, so
    the "yes" had nothing to submit.

Now: the card re-posting the stored entry unchanged is a confirm; a confirm
that carries the fields submits them even when nothing is stored; and
slot_store keeps an in-process copy that a read falls back to when Redis is
unreachable.
"""
import json
from unittest.mock import AsyncMock, patch

import pytest

import services.regularisation_node as reg
import services.slot_store as slot_store

COMPANY_ID = "confirm-co"
FIELDS = {"date": "2026-09-09", "start_time": "10:00", "end_time": "19:00", "reason": "Testing demo"}


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


@pytest.fixture
def erp(monkeypatch):
    posts = []

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

    monkeypatch.setattr(reg.attendance_client, "post_regularization", fake_post)
    # A date that is re-checked on the way (see the lost-state case) needs
    # no real erp-api call here.
    monkeypatch.setattr(reg, "_get_attendance_prefill",
                        AsyncMock(return_value={"slot_prefill": {}, "preview": {}}))
    if hasattr(reg, "_check_duplicate_date"):
        monkeypatch.setattr(reg, "_check_duplicate_date", AsyncMock(return_value={
            "outcome": "none", "message": None, "existing_request": None, "rows": []}))
    if hasattr(reg, "_get_regularization_settings"):
        monkeypatch.setattr(reg, "_get_regularization_settings", AsyncMock(return_value={
            "available": True, "window_days": None, "limit": None, "cycle": None}))
    return posts


async def _turn(conversation_id, query, action="confirm"):
    events = []
    with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=_llm(action))):
        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]


def _store_complete_entry(conversation_id):
    slot_store.set_slots("regularization", COMPANY_ID, conversation_id,
                         {"entries": [{**FIELDS, "_prefill_fetched": True}], "employee_name": None})


class TestTheCardSubmits:
    async def test_the_card_reposting_the_stored_entry_is_a_confirm(self, erp):
        cid = "card-repost"
        _store_complete_entry(cid)
        done = await _turn(cid, json.dumps(FIELDS))       # no "action" — the form payload

        assert done["intent"] == "regularization_submitted"
        assert [p["apply_date"] for p in erp] == ["2026-09-09"]

    async def test_a_changed_field_is_still_a_save_not_a_submit(self, erp):
        cid = "card-edit"
        _store_complete_entry(cid)
        done = await _turn(cid, json.dumps({**FIELDS, "end_time": "18:30"}))

        assert done["intent"] == "regularization_awaiting_confirmation"
        assert erp == []
        stored = slot_store.get_slots("regularization", COMPANY_ID, cid)
        assert stored["entries"][0]["end_time"] == "18:30"

    async def test_confirm_with_the_forms_fields_submits_them_over_a_partial_entry(self, erp):
        """Live: only the date was stored ("apply regularization for 2 oct",
        "apply now"); the form's Confirm & Submit carried the times and the
        reason, was reduced to a bare "confirm", and the answer was "I still
        need the start time, end time and reason" every time."""
        cid = "card-partial"
        slot_store.set_slots("regularization", COMPANY_ID, cid,
                             {"entries": [{"date": FIELDS["date"], "_prefill_fetched": True}],
                              "employee_name": None})
        done = await _turn(cid, json.dumps({"action": "confirm", **FIELDS}))

        assert done["intent"] == "regularization_submitted"
        assert erp == [{"apply_date": "2026-09-09", "from_time": "10:00",
                        "to_time": "19:00", "reason": "Testing demo"}]

    async def test_confirm_with_the_fields_submits_even_when_nothing_is_stored(self, erp):
        cid = "card-state-lost"
        slot_store.clear_slots("regularization", COMPANY_ID, cid)
        done = await _turn(cid, json.dumps({"action": "confirm", **FIELDS}))

        assert done["intent"] == "regularization_submitted"
        assert erp == [{"apply_date": "2026-09-09", "from_time": "10:00",
                        "to_time": "19:00", "reason": "Testing demo"}]

    async def test_confirm_with_nothing_stored_and_no_fields_still_asks(self, erp):
        cid = "card-nothing"
        slot_store.clear_slots("regularization", COMPANY_ID, cid)
        done = await _turn(cid, json.dumps({"action": "confirm"}))

        assert done["intent"] == "regularization_incomplete"
        assert erp == []

    async def test_yes_after_the_summary_submits(self, erp):
        cid = "yes-after-summary"
        _store_complete_entry(cid)
        done = await _turn(cid, "yes")
        assert done["intent"] == "regularization_submitted"


class TestSlotStoreFallback:
    """slot_store with Redis unreachable: every call used to be a no-op."""

    @pytest.fixture
    def redis_down(self, monkeypatch):
        monkeypatch.setattr(slot_store, "_get_redis", lambda: None)

    def test_a_write_is_read_back_without_redis(self, redis_down):
        slot_store.set_slots("regularization", COMPANY_ID, "no-redis", {"entries": [FIELDS]})
        assert slot_store.get_slots("regularization", COMPANY_ID, "no-redis") == {"entries": [FIELDS]}

    def test_clear_clears_the_copy(self, redis_down):
        slot_store.set_slots("regularization", COMPANY_ID, "no-redis-clear", {"entries": [FIELDS]})
        slot_store.clear_slots("regularization", COMPANY_ID, "no-redis-clear")
        assert slot_store.get_slots("regularization", COMPANY_ID, "no-redis-clear") is None

    def test_namespaces_stay_apart(self, redis_down):
        slot_store.set_slots("regularization", COMPANY_ID, "ns", {"a": 1})
        slot_store.set_slots("regularization_punch_preview", COMPANY_ID, "ns", {"b": 2})
        assert slot_store.get_slots("regularization", COMPANY_ID, "ns") == {"a": 1}

    def test_the_copy_expires_with_the_redis_ttl(self, redis_down, monkeypatch):
        clock = [1000.0]
        monkeypatch.setattr(slot_store.time, "monotonic", lambda: clock[0])
        slot_store.set_slots("regularization", COMPANY_ID, "ttl", {"a": 1})
        clock[0] += slot_store.SLOT_TTL + 1
        assert slot_store.get_slots("regularization", COMPANY_ID, "ttl") is None

    def test_a_redis_error_on_read_falls_back_to_the_copy(self, monkeypatch):
        class Broken:
            def get(self, key):
                raise ConnectionError("redis gone")

            def set(self, key, value, ex=None):
                raise ConnectionError("redis gone")

        monkeypatch.setattr(slot_store, "_get_redis", lambda: Broken())
        slot_store.set_slots("regularization", COMPANY_ID, "flaky", {"a": 1})
        assert slot_store.get_slots("regularization", COMPANY_ID, "flaky") == {"a": 1}

    async def test_the_confirm_flow_survives_redis_being_down(self, erp, redis_down):
        cid = "flow-no-redis"
        _store_complete_entry(cid)
        done = await _turn(cid, "yes")
        assert done["intent"] == "regularization_submitted"
        assert len(erp) == 1


# -- "apply" as the answer to "Reply apply now" --------------------------------

class TestApplyIsTheAnswerToApplyNow:
    """Live: "apply regularize for 9 sept" -> "... is eligible. Reply apply now
    ..." -> "apply" was asked "what would you like to apply for? Leave or
    Regularization" instead of continuing the request just started."""

    def _awaiting_apply_now(self, conversation_id):
        slot_store.set_slots("regularization", COMPANY_ID, conversation_id, {
            "entries": [], reg._PENDING_CLASSIFICATION_KEY: True,
            reg._CLASSIFIED_DATE_KEY: "2026-09-09"})

    @pytest.fixture
    def no_llm(self, monkeypatch):
        import services.classify_node as classify_node

        async def _no_shift(q):
            return None, 0.0, None

        async def _unsure(prompt, labels, fallback_label="unknown"):
            return fallback_label, None, True

        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _unsure)
        return classify_node

    @pytest.mark.parametrize("reply", ["apply", "Apply", "aply", "apply it", "continue", "fix it now",
                                       "apply now", "yes"])
    async def test_routed_back_to_the_regularization_flow(self, no_llm, reply):
        cid = f"apply-now-{reply}"
        self._awaiting_apply_now(cid)
        out = await no_llm.classify_node(
            {"query": reply, "company_id": COMPANY_ID, "conversation_id": cid, "bearer_token": "t",
             "usage_events": [], "is_manager": False}, lambda e: None)
        assert out["intent"] == "regularisation", f"{reply!r} -> {out['intent']}"

    async def test_the_eligibility_gate_takes_it_and_seeds_the_date(self):
        cid = "apply-now-seed"
        self._awaiting_apply_now(cid)
        out = await reg.regularisation_eligibility_node(
            {"query": "apply", "company_id": COMPANY_ID, "conversation_id": cid,
             "bearer_token": "t", "usage_events": []}, lambda e: None)

        assert not out.get("regularisation_blocked")          # passes on to collect details
        stored = slot_store.get_slots("regularization", COMPANY_ID, cid)
        assert stored["entries"][0]["date"] == "2026-09-09"

    async def test_a_bare_apply_with_nothing_pending_still_asks_which(self, no_llm):
        cid = "apply-nothing-pending"
        slot_store.clear_slots("regularization", COMPANY_ID, cid)
        out = await no_llm.classify_node(
            {"query": "apply", "company_id": COMPANY_ID, "conversation_id": cid, "bearer_token": "t",
             "usage_events": [], "is_manager": False}, lambda e: None)
        assert out["intent"] == "clarify_needed"

    @pytest.mark.parametrize("reply", ["apply leave", "i want to apply for sick leave"])
    def test_a_sentence_is_not_the_confirmation(self, reply):
        assert reg._is_apply_now_confirmation(reply) is False


# -- one go-ahead vocabulary for the whole flow --------------------------------

GO_AHEAD = ["yes", "yess", "Yes please", "ok", "okk", "sure", "proceed", "go ahead", "continue",
            "confirm", "approve", "apply", "apply now", "submit", "submit it", "do it",
            "looks good", "confirm & submit", "yes, confirm and submit", "ok submit it"]


class TestGoAheadAtTheSubmitStep:
    """"Shall I go ahead and submit this?" — a go-ahead confirms WITHOUT the
    LLM. Live, it depended on the extraction call reading it as confirm."""

    @pytest.mark.parametrize("reply", GO_AHEAD)
    async def test_submits_without_asking_the_llm(self, erp, reply):
        cid = f"go-ahead-{reply}"
        _store_complete_entry(cid)

        async def must_not_be_called(*args, **kwargs):
            raise AssertionError("a bare go-ahead must not need the LLM")

        events = []
        with patch("services.slot_flow._call_llm", new=must_not_be_called):
            await reg.regularisation_node(
                {"query": reply, "company_id": COMPANY_ID, "conversation_id": cid,
                 "bearer_token": "t", "usage_events": []}, events.append)
        done = [e for e in events if e.get("type") == "done"][-1]

        assert done["intent"] == "regularization_submitted", f"{reply!r} -> {done['intent']}"
        assert len(erp) == 1

    async def test_a_go_ahead_with_a_change_still_goes_to_the_llm(self, erp):
        cid = "go-ahead-with-change"
        _store_complete_entry(cid)
        calls = []

        async def llm(*args, **kwargs):
            calls.append(1)
            return _llm("provide_info")

        with patch("services.slot_flow._call_llm", new=llm):
            await reg.regularisation_node(
                {"query": "yes but change the out time to 6pm", "company_id": COMPANY_ID,
                 "conversation_id": cid, "bearer_token": "t", "usage_events": []}, lambda e: None)
        assert calls == [1]
        assert erp == []


class TestGoAheadRouting:
    @pytest.fixture
    def no_llm(self, monkeypatch):
        import services.classify_node as classify_node

        async def _no_shift(q):
            return None, 0.0, None

        async def _unsure(prompt, labels, fallback_label="unknown"):
            return fallback_label, None, True

        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _unsure)
        return classify_node

    @pytest.mark.parametrize("reply", GO_AHEAD)
    async def test_reaches_the_flow_while_it_waits_to_submit(self, no_llm, reply):
        cid = f"route-submit-{reply}"
        _store_complete_entry(cid)
        out = await no_llm.classify_node(
            {"query": reply, "company_id": COMPANY_ID, "conversation_id": cid, "bearer_token": "t",
             "usage_events": [], "is_manager": True}, lambda e: None)
        assert out["intent"] == "regularisation", f"{reply!r} -> {out['intent']}"

    @pytest.mark.parametrize("reply", ["approve", "proceed", "yess", "ok submit it", "looks good"])
    async def test_reaches_the_flow_at_the_apply_now_prompt(self, no_llm, reply):
        cid = f"route-apply-now-{reply}"
        slot_store.set_slots("regularization", COMPANY_ID, cid, {
            "entries": [], reg._PENDING_CLASSIFICATION_KEY: True,
            reg._CLASSIFIED_DATE_KEY: "2026-09-09"})
        out = await no_llm.classify_node(
            {"query": reply, "company_id": COMPANY_ID, "conversation_id": cid, "bearer_token": "t",
             "usage_events": [], "is_manager": False}, lambda e: None)
        assert out["intent"] == "regularisation", f"{reply!r} -> {out['intent']}"


class TestAffirmativeDetector:
    @pytest.mark.parametrize("reply", GO_AHEAD + ["y", "yeah", "yep", "lgtm", "fix it now",
                                                  "please proceed", "alright", "correct"])
    def test_go_aheads(self, reply):
        from services.regularisation_guards import is_affirmative_reply
        assert is_affirmative_reply(reply) is True

    @pytest.mark.parametrize("reply", [
        "no", "cancel", "yes but change the time to 6pm", "apply leave",
        "approve abc testing leave", "i want to apply for sick leave",
        "ok what is my leave balance", "is it approved?", "submit a wfh request", "goa", "young",
    ])
    def test_everything_else(self, reply):
        from services.regularisation_guards import is_affirmative_reply
        assert is_affirmative_reply(reply) is False


# -- times and a reason in one message ------------------------------------------

REPORTED = "start (in) time 10 am, the end (out) time 7 pm, and the reason is miss punch"


class TestTimesAndReasonAreRead:
    """Live: the message above was answered "I still need ... the start (in)
    time, the end (out) time, and the reason". The extraction reply was cut
    off at the 250-token budget (finish_reason=length; it needs ~265 on the
    race reasoning model), so nothing was extracted."""

    def test_the_budget_is_no_longer_250(self):
        from services.slot_flow import SlotFlowConfig
        from services.ai_service import LLM_TASK_MAX_TOKENS
        assert reg.REGULARIZATION_CONFIG.llm_max_tokens == LLM_TASK_MAX_TOKENS
        assert SlotFlowConfig.__dataclass_fields__["llm_max_tokens"].default >= 2000

    @pytest.mark.parametrize("query,expected", [
        (REPORTED, {"start_time": "10:00", "end_time": "19:00", "reason": "miss punch"}),
        ("10am to 7pm", {"start_time": "10:00", "end_time": "19:00"}),
        ("from 9:30 to 18:30, reason: forgot to punch out",
         {"start_time": "09:30", "end_time": "18:30", "reason": "forgot to punch out"}),
        ("reason - traffic delay", {"reason": "traffic delay"}),
        ("12 pm to 12 am", {"start_time": "12:00", "end_time": "00:00"}),
    ])
    def test_the_deterministic_read(self, query, expected):
        assert reg._fallback_extract_entry(query) == expected

    @pytest.mark.parametrize("query", ["10 am", "yes", "ok", "the 9th"])
    def test_nothing_to_read(self, query):
        assert reg._fallback_extract_entry(query) is None

    @pytest.mark.parametrize("llm_reply", [
        {"choices": [{"message": {"content": ""}}]},                                   # empty
        {"choices": [{"message": {"content": '{\n  "action": "provide_info",\n  "entries": ['}}]},  # cut off
    ])
    async def test_a_failed_extraction_still_fills_the_entry(self, erp, llm_reply):
        cid = f"fallback-{len(str(llm_reply))}"
        slot_store.set_slots("regularization", COMPANY_ID, cid, {
            "entries": [{"date": "2026-09-09", "_prevalidated": True, "_prefill_fetched": True}],
            "employee_name": None})
        events = []
        with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=llm_reply)):
            await reg.regularisation_node(
                {"query": REPORTED, "company_id": COMPANY_ID, "conversation_id": cid,
                 "bearer_token": "t", "usage_events": []}, events.append)
        done = [e for e in events if e.get("type") == "done"][-1]

        assert done["intent"] == "regularization_awaiting_confirmation", done["data"]["answer"]
        entry = slot_store.get_slots("regularization", COMPANY_ID, cid)["entries"][0]
        assert (entry["start_time"], entry["end_time"], entry["reason"]) == ("10:00", "19:00", "miss punch")


# -- erp-api refusing the caller's token ------------------------------------------

class TestRejectedSessionStopsEarly:
    """Live: erp-api answered 401 to the punch lookup when the date was given.
    That was swallowed, the times and reason were collected, and only the
    final "yes" said "your session has expired". The app forwards the
    caller's JWT unchanged, so every later call is refused the same way — the
    flow now stops at the first refusal."""

    @pytest.fixture
    def token_rejected(self, monkeypatch):
        async def refuse(*args, **kwargs):
            raise reg.attendance_client.ErpApiUnauthorized("erp-api returned 401")

        monkeypatch.setattr(reg.attendance_client, "get_punch_time", refuse)

    async def test_the_date_check_says_so_before_asking_for_anything(self, token_rejected, monkeypatch):
        # The first-step checks that run before the punch lookup are faked as
        # passing: unfaked, they called the REAL erp-api from .env, and this
        # test's result depended on the network (intermittent failures).
        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}))
        monkeypatch.setattr(reg, "_get_shift_details", AsyncMock(return_value=None))
        cid = "session-rejected-gate"
        slot_store.clear_slots("regularization", COMPANY_ID, cid)
        events = []
        out = await reg.regularisation_eligibility_node(
            {"query": "apply regularization for 9 sept 2026", "company_id": COMPANY_ID,
             "conversation_id": cid, "bearer_token": "t", "usage_events": []}, events.append)

        assert out["regularisation_blocked"] is True
        done = [e for e in events if e.get("type") == "done"][-1]
        assert done["data"]["answer"] == reg.SESSION_REJECTED_MESSAGE
        assert not (slot_store.get_slots("regularization", COMPANY_ID, cid) or {}).get(
            reg._PENDING_CLASSIFICATION_KEY)

    async def test_a_date_given_mid_flow_stops_too(self, monkeypatch, token_rejected):
        cid = "session-rejected-midflow"
        slot_store.set_slots("regularization", COMPANY_ID, cid,
                             {"entries": [], "employee_name": None})
        # A branch with the HA-697 checks runs them first; here they pass.
        if hasattr(reg, "_check_duplicate_date"):
            monkeypatch.setattr(reg, "_check_duplicate_date", AsyncMock(return_value={
                "outcome": "none", "message": None, "existing_request": None, "rows": []}))
        llm = {"choices": [{"message": {"content": json.dumps({
            "action": "provide_info",
            "entries": [{"date": "2026-09-09", "start_time": None, "end_time": None, "reason": None}],
            "employee_name": None})}}]}
        events = []
        with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=llm)):
            await reg.regularisation_node(
                {"query": "9 sept 2026", "company_id": COMPANY_ID, "conversation_id": cid,
                 "bearer_token": "t", "usage_events": []}, events.append)
        done = [e for e in events if e.get("type") == "done"][-1]

        assert reg.SESSION_REJECTED_MESSAGE in done["data"]["answer"]
        assert "I still need" not in done["data"]["answer"]


# -- the back-date period, as erp-api counts it ------------------------------------

class TestRegularizationPeriod:
    """Live (today 29 Sep, regularization_allowed_days 20): 9 Sep, entered via
    "apply now", collected every detail and was refused at submit by erp-api's
    AI route ("Regularization to time must be within shift timing."), while
    the portal said what was really wrong: "Regularization period has
    expired". The pre-check let it through for two reasons — it counted 20
    days back as inside the window (<=), and it skipped the window for a
    "_prevalidated" (apply-now) date."""

    TODAY = __import__("datetime").date(2026, 9, 29)

    @pytest.mark.parametrize("day,allowed", [
        ("2026-09-10", True),     # 19 days back
        ("2026-09-09", False),    # 20 days back — the reported date
        ("2026-09-01", False),
    ])
    def test_the_boundary(self, day, allowed):
        reason = reg._regularization_window_block_reason(day, 20, self.TODAY)
        assert (reason is None) is allowed
        if not allowed:
            assert reason.startswith("Regularization period has expired for")

    async def test_an_apply_now_date_is_still_checked(self, monkeypatch):
        monkeypatch.setattr(reg.attendance_mod, "_today", lambda: self.TODAY)
        monkeypatch.setattr(reg, "_get_regularization_window_days", AsyncMock(return_value=20))
        reason = await reg._regularization_eligibility_block_reason(
            {"date": "2026-09-09", "_prevalidated": True}, None, False,
            bearer_token="t", company_id=1, conversation_id="c", attendance_known=False)
        assert reason and reason.startswith("Regularization period has expired for 09 Sep 2026")

    async def test_an_apply_now_date_inside_the_window_still_skips_the_status_check(self, monkeypatch):
        monkeypatch.setattr(reg.attendance_mod, "_today", lambda: self.TODAY)
        monkeypatch.setattr(reg, "_get_regularization_window_days", AsyncMock(return_value=20))
        reason = await reg._regularization_eligibility_block_reason(
            {"date": "2026-09-20", "_prevalidated": True}, "P", False,
            bearer_token="t", company_id=1, conversation_id="c", attendance_known=True)
        assert reason is None

    async def test_the_monthly_limit_is_never_read_as_the_window(self, monkeypatch):
        async def balance(*args, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_settings": {"regularization_limit": "10"}}}}

        monkeypatch.setattr(reg.attendance_client, "get_leave_balance", balance)
        assert await reg._get_regularization_window_days(
            bearer_token="t", company_id=1, conversation_id="c") is None


class TestErpApisRefusalIsShown:
    """erp-api's answer when it refuses: {"success": false, "message":
    "Regularization period has expired", "data": {"error": ...}}. Its own
    sentence must reach the employee whatever HTTP status it comes with."""

    EXPIRED = {"success": False, "message": "Regularization period has expired",
               "data": {"error": "Regularization period has expired"}}

    @pytest.mark.parametrize("http_status", [400, 422, 403, 409])
    async def test_through_the_real_client(self, monkeypatch, http_status):
        import httpx

        async def fake_http(method, url, **kwargs):
            return httpx.Response(http_status, json=self.EXPIRED, request=httpx.Request(method, url))

        monkeypatch.setattr(reg.attendance_client._http, "request", fake_http)
        monkeypatch.setattr(reg.attendance_client, "_log_call_background", lambda **kwargs: None)
        cid = f"expired-{http_status}"
        _store_complete_entry(cid)
        done = await _turn(cid, "yes")

        assert done["intent"] == "regularization_partial"
        assert "Regularization period has expired" in done["data"]["answer"]
        assert "unable to reach" not in done["data"]["answer"]


# -- a card reply with nothing stored never reaches the chat model ------------------

class TestCardReplyWithNoStoredState:
    """Live: with the stored entry gone, "Confirm & Submit" was labelled
    follow_up and the CHAT MODEL answered "Your attendance-regularization
    request ... has been submitted. Reference number: REG-2026-09-22-01" —
    nothing had been sent to erp-api; the reference was invented."""

    @pytest.fixture
    def classify(self, monkeypatch):
        import services.classify_node as classify_node

        async def _no_shift(q):
            return None, 0.0, None

        async def _follow_up(prompt, labels, fallback_label="unknown"):
            return "follow_up", None, False          # what the LLM said live

        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _follow_up)

        async def run(query, last_intent, cid):
            slot_store.clear_slots("regularization", COMPANY_ID, cid)
            return (await classify_node.classify_node(
                {"query": query, "company_id": COMPANY_ID, "conversation_id": cid,
                 "bearer_token": "t", "usage_events": [], "is_manager": False,
                 "last_intent": last_intent}, lambda e: None))["intent"]
        return run

    @pytest.mark.parametrize("query", [
        "Confirm & Submit", "yes", "submit", "cancel",
        json.dumps({"action": "confirm"}),
        json.dumps({"action": "confirm", **FIELDS}),
        json.dumps(FIELDS),
    ])
    @pytest.mark.parametrize("last_intent", [
        "regularization_awaiting_confirmation", "regularization_incomplete", "regularisation_classify",
    ])
    async def test_goes_back_to_the_regularization_flow(self, classify, query, last_intent):
        assert await classify(query, last_intent, f"no-state-{last_intent}") == "regularisation"

    @pytest.mark.parametrize("query,last_intent", [
        ("Confirm & Submit", "apply_leave"),          # another flow's card
        ("yes", None),                                # nothing before it
        ("what is my leave balance", "regularization_awaiting_confirmation"),  # a new question
    ])
    async def test_other_messages_are_not_claimed(self, classify, query, last_intent):
        assert await classify(query, last_intent, "no-state-other") != "regularisation"

    async def test_the_flow_submits_the_cards_fields_for_real(self, erp):
        cid = "no-state-submit"
        slot_store.clear_slots("regularization", COMPANY_ID, cid)
        done = await _turn(cid, json.dumps({"action": "confirm", **FIELDS}))
        assert done["intent"] == "regularization_submitted"
        assert len(erp) == 1

    async def test_with_no_fields_it_says_so_instead_of_claiming_success(self, erp):
        cid = "no-state-nothing"
        slot_store.clear_slots("regularization", COMPANY_ID, cid)
        done = await _turn(cid, "Confirm & Submit")
        assert done["intent"] == "regularization_incomplete"
        assert "submitted" not in done["data"]["answer"].lower()
        assert erp == []

    def test_the_chat_model_is_told_it_cannot_claim_a_submission(self):
        from services.ai_service import HR_SYSTEM_PROMPT
        assert "You cannot submit, apply, approve, cancel or change anything yourself" in HR_SYSTEM_PROMPT
        assert "NEVER write a reference or request number" in HR_SYSTEM_PROMPT
