"""Regularization reject (Manager/HR/Admin) and cancel (any employee, own
requests) — erp-api routes added 2026-10-05:

  POST /api/v1/ai/regularization/approve  {"regularization_id"}
  POST /api/v1/ai/regularization/reject   {"regularization_id", "rejection_reason"}
  POST /api/v1/ai/regularization/cancel   {"regularization_id", "cancel_reason"}

Before: reject was refused ("I can't reject regularization requests yet"),
approve was manager-only (HR/admin refused), and there was no cancel flow -
"cancel my regularization" reached the LEAVE cancel flow. Also pinned: a bare
"yes" on these cards was claimed by the regularization APPLY flow ("which
date(s) would you like to regularize?"), and a late "yes" after a cancel card
was dropped fell to the chat model, which wrote "REG-131 has been cancelled"
with nothing sent.
"""
import uuid

import pytest

import services.audit_log_service as audit_log_service
import services.classify_node as classify_node
import services.erp_client as erp_client
import services.leave_slot_service as leave_slot_service
import services.regularisation_approval as ra
import services.regularisation_cancel as rc
from services import slot_store


class Writer:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)

    def of_type(self, t):
        return [e for e in self.events if e.get("type") == t]

    def done(self):
        return self.of_type("done")[-1]

    def answer(self):
        return self.done()["data"]["answer"]


def _row(rid, day, status, reason="Forgot to punch out", name="Ayush Jio", number="geo3", emp=3735):
    return {"regularization_id": rid, "apply_date": day, "from_time": "09:30:00",
            "to_time": "18:30:00", "reason": reason, "status_name": status,
            "status": {"pending": 0, "approved": 1, "rejected": 2, "cancelled": 3}[status],
            "employee_id": emp, "employee_number": number, "employee_name": name,
            "created_at": "2026-10-01 10:00:00"}


def _ok(data, message="ok"):
    return {"http_status": 200, "body": {"success": True, "data": data, "message": message}}


REG_142 = _row(142, "2026-10-02", "pending")


@pytest.fixture(autouse=True)
def _no_audit_db(monkeypatch):
    rows = []
    monkeypatch.setattr(audit_log_service, "_write", lambda **fields: rows.append(fields))
    return rows


@pytest.fixture(autouse=True)
def _action_store(monkeypatch):
    store = {}
    monkeypatch.setattr(leave_slot_service, "get_manager_action",
                        lambda c, v: store.get((str(c), v)))
    monkeypatch.setattr(leave_slot_service, "set_manager_action",
                        lambda c, v, a: store.__setitem__((str(c), v), a) or True)
    monkeypatch.setattr(leave_slot_service, "clear_manager_action",
                        lambda c, v: store.pop((str(c), v), None) or True)
    return store


@pytest.fixture
def erp(monkeypatch):
    class Fake:
        team = [REG_142]
        own = []
        calls = []
        reject_result = None
        cancel_result = None

        async def get_pending_regularizations(self, token, employee_id=None, **kw):
            return _ok({"regularizations": [dict(r) for r in self.team]})

        async def get_my_regularizations(self, token, status=None, **kw):
            return _ok({"regularizations": [dict(r) for r in self.own]})

        async def approve_regularization(self, token, rid, **kw):
            self.calls.append(("approve", rid, None))
            return _ok({"regularization_id": rid, "status": 1, "status_name": "approved"})

        async def reject_regularization(self, token, rid, reason, **kw):
            self.calls.append(("reject", rid, reason))
            return self.reject_result or _ok({"regularization_id": rid, "status": 2,
                                              "status_name": "rejected", "rejection_reason": reason})

        async def cancel_regularization(self, token, rid, reason, **kw):
            self.calls.append(("cancel", rid, reason))
            return self.cancel_result or _ok({"regularization_id": rid, "status": 3,
                                              "status_name": "cancelled", "cancel_reason": reason})

    fake = Fake()
    fake.calls = []
    for name in ("get_pending_regularizations", "get_my_regularizations", "approve_regularization",
                 "reject_regularization", "cancel_regularization"):
        monkeypatch.setattr(erp_client, name, getattr(fake, name))
    return fake


def _state(query, conv, *, manager=True, hr=False, intent=ra.APPROVAL_INTENT):
    return {"query": query, "intent": intent, "usage_events": [], "bearer_token": "t",
            "company_id": 26, "conversation_id": conv, "is_manager_jwt": manager,
            "is_manager": manager, "is_hr_role": hr}


async def _approval_turns(*queries, manager=True, hr=False):
    conv = f"rej-{uuid.uuid4().hex[:6]}"
    writers = []
    for q in queries:
        w = Writer()
        await ra.regularisation_approval_node(_state(q, conv, manager=manager, hr=hr), w)
        writers.append(w)
    return writers


# -- erp_client contract ---------------------------------------------------------

class TestErpContract:
    @pytest.mark.parametrize("fn,path,args,body", [
        ("reject_regularization", "/api/v1/ai/regularization/reject", (138, "due to inappropriate reason"),
         {"regularization_id": 138, "rejection_reason": "due to inappropriate reason"}),
        ("cancel_regularization", "/api/v1/ai/regularization/cancel", (131, "No longer needed"),
         {"regularization_id": 131, "cancel_reason": "No longer needed"}),
    ])
    async def test_path_and_body(self, monkeypatch, fn, path, args, body):
        seen = {}

        async def fake_request(method, p, token, **kw):
            seen.update({"method": method, "path": p, **kw})
            return _ok({})

        monkeypatch.setattr(erp_client, "_request", fake_request)
        await getattr(erp_client, fn)("tok", *args)

        assert seen["method"] == "POST" and seen["path"] == path
        assert {k: seen["json_body"][k] for k in body} == body
        assert seen["allow_business_error_body"] is True and seen["allow_422_body"] is True


# -- who may act -------------------------------------------------------------------

class TestWhoMayAct:
    async def test_hr_may_approve(self, erp):
        card, done = await _approval_turns("approve ayush jio's regularization request", "yes",
                                           manager=False, hr=True)
        assert erp.calls == [("approve", 142, None)]
        assert done.done()["intent"] == "regularisation_approval_success"

    async def test_hr_may_reject(self, erp):
        await _approval_turns("reject ayush jio's regularization", "the reason given is not valid",
                              "yes", manager=False, hr=True)
        assert erp.calls == [("reject", 142, "the reason given is not valid")]

    @pytest.mark.parametrize("query", ["approve ayush jio's regularization request",
                                       "reject ayush jio's regularization request"])
    async def test_an_employee_may_not(self, erp, query):
        (w,) = await _approval_turns(query, manager=False, hr=False)
        assert w.answer() == ra.NOT_A_MANAGER_MESSAGE
        assert erp.calls == []


# -- reject ------------------------------------------------------------------------

class TestReject:
    async def test_reason_then_confirm_rejection_then_yes(self, erp):
        """Design: details + reason -> "Confirm rejection" repeating the reason
        -> confirm -> "Request rejected"."""
        card, confirm, done = await _approval_turns(
            "reject ayush jio's regularization request", "punch records show he was present", "yes")

        assert card.answer().startswith("Reject this request?")
        assert confirm.answer().startswith(
            "Reject REG-142 from Ayush Jio for 02-Oct-2026?\n"
            "Reason: punch records show he was present\nThe employee will see this reason.")
        assert erp.calls == [("reject", 142, "punch records show he was present")]
        assert done.done()["intent"] == "regularisation_rejection_success"
        assert done.answer() == (
            "Rejected - Ayush Jio's regularization request for 02-Oct-2026 (REG-142) "
            "has been rejected.\nReason: punch records show he was present")
        assert done.of_type("regularisation_rejection_success")
        data = done.done()["data"]
        assert data["reference_id"] == "REG-142" and data["status_label"] == "Rejected"
        assert data["rejected_on"] and data["rejection_reason"] == "punch records show he was present"

    async def test_an_approval_keeps_its_own_success_intent(self, erp):
        _, done = await _approval_turns("approve REG-142", "yes")
        assert done.done()["intent"] == "regularisation_approval_success"

    async def test_a_reason_opening_with_could_is_a_reason(self, erp):
        """Live: "Could not verify the punch records" was read as a QUESTION
        (it opens with "could") and never reached the reason prompt."""
        _, confirm, done = await _approval_turns(
            "reject REG-142", "Could not verify the punch records", "yes")
        assert "Reason: Could not verify the punch records" in confirm.answer()
        assert erp.calls == [("reject", 142, "Could not verify the punch records")]

    @pytest.mark.parametrize("new_request", [
        "Show my team regularisation", "show my team regularization requests",
        "what is pending for me?", "list regularization requests",
    ])
    async def test_a_new_request_at_the_reason_prompt_is_not_the_reason(self, erp, new_request):
        """Live: at the reason prompt "Show my team regularisation" became the
        rejection reason. It is a new request: the reject card is dropped and
        a later "yes" sends nothing."""
        _, after, yes = await _approval_turns("reject REG-142", new_request, "yes")
        assert "Reason: " + new_request not in after.answer()
        assert after.done()["intent"] != "regularisation_rejection_confirmation"
        assert erp.calls == []

    @pytest.mark.parametrize("continue_payload", [
        "punch records show he was present",
        "REG-142 - punch records show he was present",
        "Reject REG-142 because punch records show he was present",
        "reject REG-142 reason: punch records show he was present",
        '{"rejection_reason": "punch records show he was present"}',
        '{"action": "reject", "regularization_id": 142, "rejection_reason": "punch records show he was present"}',
        '{"reference_id": "REG-142", "reason": "punch records show he was present"}',
    ])
    async def test_every_shape_of_the_cards_continue_sends_only_the_reason(self, erp, continue_payload):
        """The reject card's Continue may send the reason alone, with the
        reference, or as the card's JSON. Live, the JSON and "REG-149 - ..."
        reached erp-api verbatim as the reason the employee reads."""
        _, confirm, done = await _approval_turns("reject REG-142", continue_payload, "yes")
        assert confirm.done()["intent"] == "regularisation_rejection_confirmation"
        assert "Reason: punch records show he was present\n" in confirm.answer()
        assert erp.calls == [("reject", 142, "punch records show he was present")]
        assert done.done()["intent"] == "regularisation_rejection_success"

    @pytest.mark.parametrize("back", ["Back to list", "back", '{"action": "back_to_list"}'])
    async def test_back_to_list_drops_the_card(self, erp, back):
        """Live: "Back to list" was saved as the reason, and the next "yes"
        rejected the request."""
        _, listed, yes = await _approval_turns("reject REG-142", back, "yes")
        assert "Reason: " not in listed.answer()
        assert erp.calls == []

    @pytest.mark.parametrize("button, expected", [
        ('{"action": "confirm"}', [("reject", 142, "punch records show he was present")]),
        ('{"action": "keep"}', []),
    ])
    async def test_the_confirm_steps_buttons_as_json(self, erp, button, expected):
        await _approval_turns("reject REG-142", "punch records show he was present", button)
        assert erp.calls == expected

    async def test_nothing_is_sent_at_the_reason_turn(self, erp):
        await _approval_turns("reject REG-142", "punch records show he was present")
        assert erp.calls == []

    async def test_edit_reason_asks_again(self, erp):
        _, _, edit, confirm, _ = await _approval_turns(
            "reject REG-142", "punch records show he was present", "edit reason",
            "biometric shows arrival at 11:20 AM", "yes")
        assert "what's the reason for rejecting it" in edit.answer()
        assert erp.calls == [("reject", 142, "biometric shows arrival at 11:20 AM")]

    async def test_nothing_is_written_on_the_instruction_turn(self, erp):
        await _approval_turns("reject REG-142")
        assert erp.calls == []

    async def test_an_inline_reason_is_shown_and_a_yes_submits_it(self, erp):
        card, done = await _approval_turns(
            "reject REG-142 because punch records show he was present", "yes")

        assert card.of_type("regularisation_approval_confirmation")[0]["data"][
            "rejection_reason"] == "punch records show he was present"
        assert erp.calls == [("reject", 142, "punch records show he was present")]

    async def test_an_inline_reason_is_not_read_as_a_name(self, erp):
        (card,) = await _approval_turns("reject ayush jio's regularization because of a fake punch")
        assert card.of_type("regularisation_approval_confirmation")[0]["data"]["regularization_id"] == 142

    async def test_no_leaves_it_pending(self, erp, _action_store):
        _, done = await _approval_turns("reject REG-142", "no")
        assert "left Ayush Jio's regularization request pending" in done.answer()
        assert erp.calls == [] and not _action_store

    async def test_a_too_short_reason_is_asked_again(self, erp):
        _, again = await _approval_turns("reject REG-142", "too short")
        assert again.answer() == ra.REASON_TOO_SHORT_MESSAGE
        assert again.done()["data"]["field_error"] == ra.REASON_TOO_SHORT_MESSAGE
        assert erp.calls == []

    async def test_erp_refusal_is_verbatim(self, erp):
        erp.reject_result = {"http_status": 422, "body": {
            "success": False, "message": "Attendance is locked for this date. Contact HR."}}
        _, _, done = await _approval_turns("reject REG-142", "wrong punch times entered", "yes")
        assert done.answer() == ("Attendance is locked for this date. Contact HR. "
                                 "Nothing has been changed.")

    def test_a_reason_reply_routes_to_the_card_but_a_question_does_not(self, _action_store):
        _action_store[("26", "c")] = {"kind": ra.CARD_KIND, "step": "awaiting_rejection_reason"}
        assert ra.resolve_pending_regularisation_intent(26, "c", "wrong punch times") == ra.APPROVAL_INTENT
        assert ra.resolve_pending_regularisation_intent(26, "c", "no") == ra.APPROVAL_INTENT
        assert ra.resolve_pending_regularisation_intent(26, "c", "what happens if I reject?") is None


class TestApplyFlowDoesNotClaimTheseCards:
    @pytest.mark.parametrize("last_intent", [
        "regularisation_approval_confirmation", "regularisation_cancel_confirmation",
        "regularisation_approval_choice", "regularisation_rejection_confirmation",
        "regularisation_rejection_reason_invalid"])
    @pytest.mark.parametrize("reply", ["yes", "no"])
    def test_a_yes_or_no_is_left_to_the_card(self, last_intent, reply):
        assert classify_node._is_regularisation_card_reply(reply, last_intent) is False

    def test_the_apply_card_still_is(self):
        assert classify_node._is_regularisation_card_reply("yes", "regularization_awaiting_confirmation")


# -- cancel ------------------------------------------------------------------------

class TestCancelDetection:
    @pytest.mark.parametrize("q", ["cancel my regularization for 1 oct", "cancel REG-131",
                                   "withdraw my regularization request", "cancel my reqgulariztion",
                                   "i want to cancel my regularisation"])
    def test_is_a_cancel(self, q):
        assert rc.is_cancel_regularisation_request(q) is True

    @pytest.mark.parametrize("q", ["show my cancelled regularizations", "how do i cancel a regularization",
                                   "cancel my team regularization", "cancel my leave",
                                   "reject geo3 regularization", "cancel"])
    def test_is_not(self, q):
        assert rc.is_cancel_regularisation_request(q) is False


async def _cancel_turns(*queries):
    conv = f"can-{uuid.uuid4().hex[:6]}"
    writers = []
    for q in queries:
        # Classify's own gate: an answer reaches the node, anything else drops
        # the card (and a late "yes" after that is routed back here too).
        routed = (rc.resolve_pending_cancel_intent(26, conv, q)
                  or (rc.CANCEL_INTENT if rc.is_cancel_regularisation_request(q) else None))
        w = Writer()
        if routed:
            await rc.regularisation_cancel_node(
                {"query": q, "company_id": 26, "conversation_id": conv, "bearer_token": "t",
                 "usage_events": []}, w)
        writers.append(w)
    return writers


class TestCancel:
    async def test_confirm_card_then_reason_then_cancelled(self, erp):
        """Design: the "Cancel this request?" card (Confirm cancellation / Keep
        request) -> confirm -> the reason is asked, with the card's details ->
        the reason cancels it. No default reason, no approver note."""
        erp.own = [_row(131, "2026-10-01", "pending", name="B Geo")]
        card, ask, done = await _cancel_turns("cancel my regularization for 1 oct",
                                              "Confirm cancellation", "applied for the wrong date")

        assert card.done()["intent"] == "regularisation_cancel_confirmation"
        assert card.answer() == (
            "Cancel this request?\n- Reference: REG-131\n- Date: 01-Oct-2026 – 01-Oct-2026\n"
            "- Regularization type: Missed punch-out\n- Status: Pending approval\n"
            "- Applied on: 01-Oct-2026\n\nConfirm the cancellation, or keep the request.")
        assert card.done()["data"]["actions"] == [
            {"label": "Confirm cancellation", "action": "confirm"},
            {"label": "Keep request", "action": "keep"}]
        assert card.done()["data"]["cancel_reason"] is None

        assert ask.answer() == "Please share the reason for cancelling REG-131."
        assert ask.done()["intent"] == "regularisation_cancel_awaiting_reason"
        # Just the reason prompt: unique step marker, no card, no actions.
        assert ask.done()["data"] == {
            "answer": "Please share the reason for cancelling REG-131.",
            "step": "awaiting_cancel_reason", "input_required": "cancel_reason",
            "reference_id": "REG-131", "regularization_id": 131}
        assert card.done()["data"]["step"] == "awaiting_cancel_confirmation"
        assert erp.calls == [("cancel", 131, "applied for the wrong date")]
        assert done.answer() == ("Cancelled - your regularization request for 01-Oct-2026 "
                                 "(REG-131) is now cancelled.")
        data = done.done()["data"]
        assert data["status_label"] == "Cancelled" and data["cancelled_on"]
        assert data["date_range_display"] == "01-Oct-2026 – 01-Oct-2026"

    async def test_success_shows_the_quota_after_cancelling(self, erp, monkeypatch):
        import services.payroll_cycle as payroll_cycle
        import services.regularisation_node as reg_node
        from datetime import date
        from unittest.mock import AsyncMock
        monkeypatch.setattr(reg_node, "_get_regularization_settings", AsyncMock(return_value={
            "available": True, "window_days": 20, "limit": 2,
            "cycle": payroll_cycle.PayrollCycle("monthly", date(2026, 10, 1), date(2026, 10, 31))}))
        erp.own = [_row(131, "2026-10-01", "pending")]
        *_, done = await _cancel_turns("cancel REG-131", "Confirm cancellation", "no longer required")
        # The re-read after the cancel still lists REG-131 as pending in this
        # fake; what matters is the numbers come from that re-read.
        assert done.done()["data"]["quota"] == {"label": "Oct 2026", "used": 1, "limit": 2}
        assert "Quota for Oct 2026: 1 of 2 used." in done.answer()

    async def test_approved_meanwhile_is_caught_at_confirm(self, erp):
        """Design: final re-check at confirm - approved a moment ago, nothing changed."""
        erp.own = [_row(131, "2026-10-01", "pending")]
        conv = f"can-{uuid.uuid4().hex[:6]}"
        state = {"company_id": 26, "conversation_id": conv, "bearer_token": "t", "usage_events": []}
        await rc.regularisation_cancel_node({**state, "query": "cancel REG-131"}, Writer())
        await rc.regularisation_cancel_node({**state, "query": "Confirm cancellation"}, Writer())
        erp.own = [_row(131, "2026-10-01", "approved")]       # the approver acts meanwhile
        w = Writer()
        await rc.regularisation_cancel_node({**state, "query": "applied by mistake"}, w)

        assert w.answer() == ("Request not cancelled - REG-131 was approved a moment ago, so it "
                              "can no longer be cancelled. Current status: Approved. Nothing was "
                              "changed.")
        assert erp.calls == []

    async def test_service_down_at_confirm_changes_nothing(self, erp, monkeypatch):
        erp.own = [_row(131, "2026-10-01", "pending")]

        async def down(*a, **k):
            raise erp_client.ErpApiUnavailable("down")

        conv = f"can-{uuid.uuid4().hex[:6]}"
        w1, w2 = Writer(), Writer()
        state = {"company_id": 26, "conversation_id": conv, "bearer_token": "t", "usage_events": []}
        await rc.regularisation_cancel_node({**state, "query": "cancel REG-131"}, w1)
        await rc.regularisation_cancel_node({**state, "query": "Confirm cancellation"}, Writer())
        monkeypatch.setattr(erp_client, "get_my_regularizations", down)
        await rc.regularisation_cancel_node({**state, "query": "applied by mistake"}, w2)

        assert w2.answer().startswith("Couldn't cancel right now - the system didn't respond, "
                                      "so REG-131 has not been cancelled.")
        assert w2.done()["data"]["retry_available"] is True
        assert erp.calls == []

    async def test_the_reason_given_is_sent(self, erp):
        erp.own = [_row(131, "2026-10-01", "pending")]
        await _cancel_turns("cancel REG-131 because I applied for the wrong date", "yes")
        assert erp.calls == [("cancel", 131, "I applied for the wrong date")]

    async def test_a_reason_in_the_yes_is_used(self, erp):
        erp.own = [_row(131, "2026-10-01", "pending")]
        await _cancel_turns("cancel REG-131", "yes, the punch was fixed")
        assert erp.calls == [("cancel", 131, "the punch was fixed")]

    async def test_several_lists_only_pending_with_a_cancel_button(self, erp):
        erp.own = [_row(131, "2026-10-01", "pending"), _row(130, "2026-09-29", "pending"),
                   _row(128, "2026-09-27", "approved"), _row(129, "2026-09-26", "rejected")]
        choice, card, _, _ = await _cancel_turns("cancel my regularization request", "2",
                                                 "Confirm cancellation", "applied twice by mistake")

        assert choice.answer().startswith("Requests you can cancel:")
        assert "1. 01-Oct-2026" in choice.answer() and "2. 29-Sep-2026" in choice.answer()
        assert "REG-128" not in choice.answer() and "REG-129" not in choice.answer(), \
            "approved and closed requests aren't listed"
        rows = choice.done()["data"]["regularizations"]
        assert all(r["cancel"] is True and "approve" not in r for r in rows)
        assert choice.done()["data"]["total_count"] == 2
        assert erp.calls == [("cancel", 130, "applied twice by mistake")]

    async def test_an_approved_request_cannot_be_cancelled(self, erp):
        erp.own = [_row(126, "2026-08-28", "approved")]
        (w,) = await _cancel_turns("cancel REG-126")
        assert w.answer() == ("This request can't be cancelled. Your request for 28-Aug-2026 "
                              "(Ref: REG-126) is already Approved. Approved requests can't be "
                              "cancelled under your regularization policy.")
        assert erp.calls == []

    @pytest.mark.parametrize("reply", ["Keep request", "Keep Request", "no", "keep it"])
    async def test_keep_request_ends_the_cancel_flow(self, erp, reply):
        """"Keep request" (the card's button) - or "no" - keeps the request and
        leaves the cancel flow: nothing is pending afterwards."""
        erp.own = [_row(131, "2026-10-01", "pending")]
        conv_turns = await _cancel_turns("cancel REG-131", reply, "applied by mistake")
        kept, after = conv_turns[1], conv_turns[2]
        assert kept.answer().startswith("No problem - I've kept your regularization request")
        assert kept.done()["intent"] == "regularisation_cancel_kept"
        assert after.events == [], "the flow is over - a later message is not its reason"
        assert erp.calls == []

    async def test_keep_request_at_the_reason_step_also_ends_it(self, erp):
        erp.own = [_row(131, "2026-10-01", "pending")]
        *_, kept = await _cancel_turns("cancel REG-131", "Confirm cancellation", "Keep request")
        assert kept.done()["intent"] == "regularisation_cancel_kept"
        assert erp.calls == []

    async def test_already_rejected(self, erp):
        erp.own = [_row(129, "2026-09-26", "rejected")]
        (w,) = await _cancel_turns("cancel REG-129")
        assert w.answer().startswith("This request can't be cancelled. Your request for "
                                     "26-Sep-2026 (Ref: REG-129) is already Rejected.")

    async def test_unknown_reference(self, erp):
        erp.own = [_row(131, "2026-10-01", "pending")]
        (w,) = await _cancel_turns("cancel REG-999")
        assert w.answer().startswith("I couldn't find REG-999 among your regularization requests")

    async def test_erp_refusal_is_verbatim(self, erp):
        erp.own = [_row(131, "2026-10-01", "pending")]
        erp.cancel_result = {"http_status": 422, "body": {
            "success": False, "message": "Approved regularization cannot be cancelled"}}
        *_, done = await _cancel_turns("cancel REG-131", "Confirm cancellation", "applied by mistake")
        assert done.answer() == "Approved regularization cannot be cancelled. Nothing has been changed."

    async def test_a_late_yes_after_the_card_was_dropped_cancels_nothing(self, erp):
        erp.own = [_row(131, "2026-10-01", "pending")]
        _, other, late = await _cancel_turns("cancel REG-131", "show my leave balance", "yes")

        assert other.events == [], "an unrelated reply is not this flow's"
        assert late.done()["intent"] == "regularisation_cancel_expired"
        assert "nothing has been cancelled" in late.answer()
        assert "cancel REG-131" in late.answer()
        assert erp.calls == []

    async def test_a_second_late_yes_is_not_claimed(self, erp):
        erp.own = [_row(131, "2026-10-01", "pending")]
        *_, again = await _cancel_turns("cancel REG-131", "show my leave balance", "yes", "yes")
        assert again.events == []
        assert erp.calls == []


class TestCancelRouting:
    async def test_routes_to_the_cancel_node_not_leave_cancel(self, monkeypatch):
        async def _no_shift(q):
            return None, 0.0, None

        async def _classify(prompt, labels, fallback_label="unknown"):
            return "cancel_leave", 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": "cancel my regularization for 1 oct", "company_id": 26,
             "conversation_id": f"route-{uuid.uuid4().hex[:6]}", "bearer_token": "t",
             "usage_events": [], "is_manager": False, "last_intent": None}, lambda e: None)
        assert out["intent"] == rc.CANCEL_INTENT


class TestRejectRoutingThroughClassify:
    """The three reject turns all reach the approval card through classify -
    including the "yes" at "Confirm rejection", which the APPLY flow must not
    claim (its last_intent starts with "regularisation_" too)."""

    @pytest.fixture
    def llm_says_small_talk(self, monkeypatch):
        async def _no_shift(q):
            return None, 0.0, None

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

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

    @pytest.mark.parametrize("step,reply,last_intent", [
        ("awaiting_rejection_reason", "punch records show he was present",
         "regularisation_approval_confirmation"),
        ("awaiting_confirmation", "yes", "regularisation_rejection_confirmation"),
        ("awaiting_confirmation", "edit reason", "regularisation_rejection_confirmation"),
    ])
    async def test_routes_to_the_card(self, llm_says_small_talk, _action_store, step, reply,
                                      last_intent):
        conv = f"rr-{uuid.uuid4().hex[:6]}"
        _action_store[("26", conv)] = {"kind": ra.CARD_KIND, "step": step, "action": "reject",
                                       "regularization_id": 142, "card": {}}
        out = await classify_node.classify_node(
            {"query": reply, "company_id": 26, "conversation_id": conv, "bearer_token": "t",
             "usage_events": [], "is_manager": True, "last_intent": last_intent}, lambda e: None)
        assert out["intent"] == ra.APPROVAL_INTENT


class TestCancelByReferenceAtTheCard:
    """Live (2026-10-06): "cancel my regularization request" showed the REG-141
    card; the reply "Cancel REG-141" was read as a DECLINE ("I've kept your
    regularization request"). A message starting with "cancel" counted as "keep
    it". Only a bare "cancel" is that; naming the card's request confirms it."""

    async def test_cancel_with_the_cards_reference_asks_for_the_reason(self, erp):
        """Confirming by reference is not "keep it" - it goes on to the reason
        (never defaulted), and the reason then cancels."""
        erp.own = [_row(141, "2026-10-01", "pending")]
        listed, card, ask, done = await _cancel_turns(
            "cancel my regualarisation request", "Cancel REG-141", "Cancel REG-141",
            "applied for the wrong date")

        assert listed.done()["intent"] == "regularisation_cancel_choice", "a vague ask lists first"
        assert card.done()["intent"] == "regularisation_cancel_confirmation"
        assert ask.answer() == "Please share the reason for cancelling REG-141."
        assert ask.done()["intent"] == "regularisation_cancel_awaiting_reason"
        assert erp.calls == [("cancel", 141, "applied for the wrong date")]
        assert done.done()["intent"] == "regularisation_cancel_success"

    async def test_with_a_reason(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        await _cancel_turns("cancel REG-141",
                            "cancel REG-141 because I applied for the wrong date")
        assert erp.calls == [("cancel", 141, "I applied for the wrong date")]

    async def test_a_pick_from_the_list_keeps_its_reason(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending"), _row(140, "2026-09-30", "pending")]
        _, card, _ = await _cancel_turns("cancel my regularization request",
                                         "cancel REG-141 because I applied twice", "yes")
        assert "- Cancel reason: I applied twice" in card.answer()
        assert erp.calls == [("cancel", 141, "I applied twice")]

    async def test_by_the_cards_date(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        await _cancel_turns("cancel REG-141",
                            "cancel my regularization for 1 oct because the punch was fixed")
        assert erp.calls == [("cancel", 141, "the punch was fixed")]

    async def test_another_reference_starts_over_with_that_one(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending"), _row(140, "2026-09-30", "pending")]
        _, other = await _cancel_turns("cancel REG-141", "cancel REG-140")

        assert erp.calls == [], "nothing cancelled - a new card for REG-140"
        assert other.done()["intent"] == "regularisation_cancel_confirmation"
        assert "- Reference: REG-140" in other.answer()

    async def test_a_bare_cancel_asks_which_request_by_reference_or_date(self, erp):
        """Product decision 2026-10-06: a bare "cancel" at the card is not "keep
        it" - the requests are listed again and the employee is asked for the
        reference ID or date. Nothing is changed."""
        erp.own = [_row(141, "2026-10-01", "pending")]
        _, again = await _cancel_turns("cancel REG-141", "cancel")
        assert again.done()["intent"] == "regularisation_cancel_choice"
        assert again.answer().startswith("Requests you can cancel:\n1. 01-Oct-2026")
        assert again.answer().endswith("Please tell me its reference ID or date - for example "
                                       "'cancel REG-141' or 'cancel 01-Oct-2026'.")
        assert erp.calls == []

    @pytest.mark.parametrize("reply", ["no", "keep it", "don't cancel"])
    async def test_no_still_keeps_it(self, erp, reply):
        erp.own = [_row(141, "2026-10-01", "pending")]
        _, kept = await _cancel_turns("cancel REG-141", reply)
        assert kept.done()["intent"] == "regularisation_cancel_kept"
        assert erp.calls == []

    async def test_no_longer_needed_is_a_reason_not_a_no(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        await _cancel_turns("cancel REG-141", "Confirm cancellation", "no longer needed")
        assert erp.calls == [("cancel", 141, "no longer needed")]


class TestBareCancelUsesTheConversation:
    """"cancel" / "cancel this" right after a regularization reply means one of
    the requests that reply showed."""

    async def _after_view(self, monkeypatch, erp, view_query, reply):
        import services.my_regularisation_view as view
        monkeypatch.setattr(view, "_today", lambda: __import__("datetime").date(2026, 10, 6))
        conv = f"ctx-{uuid.uuid4().hex[:6]}"
        state = {"company_id": 26, "conversation_id": conv, "bearer_token": "t", "usage_events": []}
        await view.my_regularisation_view_node({**state, "query": view_query}, Writer())
        assert rc.is_cancel_in_regularisation_context(reply, view.VIEW_INTENT)
        w = Writer()
        await rc.regularisation_cancel_node({**state, "query": reply}, w)
        return w

    async def test_cancel_this_after_one_request_opens_its_card(self, erp, monkeypatch):
        erp.own = [_row(141, "2026-10-01", "pending"), _row(140, "2026-09-30", "pending")]
        w = await self._after_view(monkeypatch, erp, "status of REG-141", "cancel this")
        assert w.done()["intent"] == "regularisation_cancel_confirmation"
        assert "- Reference: REG-141" in w.answer()
        assert w.answer().endswith("Confirm the cancellation, or keep the request.")

    async def test_cancel_after_a_list_asks_which_one(self, erp, monkeypatch):
        erp.own = [_row(141, "2026-10-01", "pending"), _row(140, "2026-09-30", "pending")]
        w = await self._after_view(monkeypatch, erp, "show my pending regularizations", "cancel")
        assert w.done()["intent"] == "regularisation_cancel_choice"
        assert "REG-141" in w.answer() and "REG-140" in w.answer()
        assert "reference ID or date" in w.answer()
        assert erp.calls == []

    def test_outside_a_regularization_conversation_a_bare_cancel_is_untouched(self):
        assert not rc.is_cancel_in_regularisation_context("cancel", "leave_status")
        assert not rc.is_cancel_in_regularisation_context("cancel", "regularization_incomplete")
        assert not rc.is_cancel_in_regularisation_context("cancel", None)

    async def test_yes_cancel_reference_does_not_use_the_reference_as_the_reason(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        _, ask = await _cancel_turns("cancel REG-141", "yes cancel REG-141")
        assert erp.calls == [], "no reason given - asked for it, not sent with 'REG-141'"
        assert ask.answer() == "Please share the reason for cancelling REG-141."

    async def test_a_bare_yes_without_a_reason_asks_for_it(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        _, ask, done = await _cancel_turns("cancel REG-141", "yes", "wrong date entered")
        assert ask.done()["intent"] == "regularisation_cancel_awaiting_reason"
        assert erp.calls == [("cancel", 141, "wrong date entered")]

    @pytest.mark.parametrize("reply", ["show my leave balance", "what is my regularization quota?",
                                       "how do I apply for leave"])
    async def test_a_question_is_never_taken_as_the_reason(self, erp, reply):
        erp.own = [_row(141, "2026-10-01", "pending")]
        _, other = await _cancel_turns("cancel REG-141", reply)
        assert erp.calls == [] and other.events == []


class TestBareCancelRoutingAndReplies:
    async def test_the_suggested_replies_pick_the_request(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending"), _row(140, "2026-09-30", "pending")]
        for reply, ref in (("cancel REG-140", "REG-140"), ("cancel 01-Oct-2026", "REG-141")):
            _, card = await _cancel_turns("cancel my regularization request", reply)
            assert card.done()["intent"] == "regularisation_cancel_confirmation", reply
            assert f"- Reference: {ref}" in card.answer()

    @pytest.mark.parametrize("last_intent,expected", [
        ("my_regularisation_view", rc.CANCEL_INTENT),
        ("regularisation_cancel_kept", rc.CANCEL_INTENT),
    ])
    async def test_classify_routes_by_the_previous_reply(self, monkeypatch, last_intent, expected):
        async def _no_shift(q):
            return None, 0.0, None

        async def _classify(prompt, labels, fallback_label="unknown"):
            return "cancel_leave", 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": "cancel this", "company_id": 26, "conversation_id": f"bc-{uuid.uuid4().hex[:6]}",
             "bearer_token": "t", "usage_events": [], "is_manager": False,
             "last_intent": last_intent}, lambda e: None)
        assert out["intent"] == expected


class TestCardButtonsReachTheRegularizationCard:
    """The leave cancel card has the same buttons; with a REGULARIZATION cancel
    card open, a press is that card's answer, never the leave flow's."""

    @pytest.mark.parametrize("button", ["Confirm Cancellation", "Keep Request",
                                        "Confirm cancellation", "Keep request"])
    async def test_routed_to_the_regularization_cancel(self, monkeypatch, button):
        async def _no_shift(q):
            return None, 0.0, None

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

        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _classify)
        conv = f"btn-{uuid.uuid4().hex[:6]}"
        slot_store.set_slots(rc._NAMESPACE, 26, conv, {"step": "awaiting_confirmation",
                                                       "regularization_id": 141, "card": {}})
        out = await classify_node.classify_node(
            {"query": button, "company_id": 26, "conversation_id": conv, "bearer_token": "t",
             "usage_events": [], "is_manager": False,
             "last_intent": "regularisation_cancel_confirmation"}, lambda e: None)
        assert out["intent"] == rc.CANCEL_INTENT
        slot_store.clear_slots(rc._NAMESPACE, 26, conv)

    async def test_without_a_regularization_card_they_stay_with_leave(self, monkeypatch):
        conv = f"btn-{uuid.uuid4().hex[:6]}"
        out = await classify_node.classify_node(
            {"query": "Keep Request", "company_id": 26, "conversation_id": conv, "bearer_token": "t",
             "usage_events": [], "is_manager": False, "last_intent": None}, lambda e: None)
        assert out["intent"] == "cancel_leave"


class TestReasonPromptIsJustAPrompt:
    """Live: "Cancel REG-141" asked for the reason, then the client showed the
    card again (the prompt carried its fields and Confirm/Keep actions) and
    "Confirm cancellation" asked again with the same payload."""

    async def test_confirming_again_at_the_reason_step_asks_plainly_again(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        _, first, second = await _cancel_turns("cancel REG-141", "Cancel REG-141",
                                               "Confirm cancellation")
        for w in (first, second):
            data = w.done()["data"]
            assert data["step"] == "awaiting_cancel_reason"
            assert data["input_required"] == "cancel_reason"
            assert "actions" not in data and "date_range_display" not in data
        assert erp.calls == []


class TestAwaitingReasonIntentKeepsTheFlowsPrefix:
    """The reason prompt's intent (regularisation_cancel_awaiting_reason) is
    saved as last_intent; the routing rules that recognise a cancel-flow reply
    by the "regularisation_cancel" prefix must still see it."""

    INTENT = "regularisation_cancel_awaiting_reason"

    def test_a_bare_cancel_after_it_is_still_this_flow(self):
        assert rc.is_cancel_in_regularisation_context("cancel", self.INTENT)

    def test_the_apply_flow_does_not_claim_a_yes_after_it(self):
        assert classify_node._is_regularisation_card_reply("yes", self.INTENT) is False


class TestSameStepsAsLeaveCancel:
    """2026-10-06: regularization cancel follows the cancel-leave flow's STEPS,
    while its texts, data and event names stay as they were."""

    @pytest.mark.parametrize("again", ["cancel", "cancel again", "cancel my previous request"])
    async def test_after_keep_request_a_follow_up_re_offers_the_same_request(self, erp, again):
        erp.own = [_row(141, "2026-10-01", "pending"), _row(140, "2026-09-30", "pending")]
        _, kept, card = await _cancel_turns("cancel REG-141", "Keep request", again)
        assert kept.done()["intent"] == "regularisation_cancel_kept"
        assert card.done()["intent"] == "regularisation_cancel_confirmation"
        assert "- Reference: REG-141" in card.answer(), "the same request, not the whole list"
        assert erp.calls == []

    async def test_after_keep_request_anything_else_ends_it(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        *_, after = await _cancel_turns("cancel REG-141", "Keep request", "applied by mistake")
        assert after.events == []

    async def test_an_unclear_reply_re_asks_and_keeps_the_card(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        _, unclear, ask = await _cancel_turns("cancel REG-141", "hmm not sure", "yes")
        assert unclear.answer() == ("Sorry, I didn't catch that — would you like me to go ahead and "
                                    "cancel your regularization request (01-Oct-2026, 9:30 AM to "
                                    "6:30 PM, ref REG-141)? (yes/no)")
        assert unclear.done()["data"]["step"] == "awaiting_cancel_confirmation"
        assert ask.done()["intent"] == "regularisation_cancel_awaiting_reason", "card was kept"

    async def test_an_empty_reason_is_asked_again(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        *_, again = await _cancel_turns("cancel REG-141", "yes", "'   '")
        assert again.answer() == "Please share the reason for cancelling REG-141."
        assert again.done()["data"]["step"] == "awaiting_cancel_reason"
        assert erp.calls == []

    async def test_an_unclear_pick_re_shows_the_list(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending"), _row(140, "2026-09-30", "pending")]
        _, unclear = await _cancel_turns("cancel my regularization request", "the other one")
        assert unclear.done()["intent"] == "regularisation_cancel_choice"
        assert unclear.answer().startswith("Sorry, I couldn't quite tell which request you mean")
        assert unclear.of_type("regularization_cancel_choice")
        assert [r["reference_id"] for r in unclear.done()["data"]["regularizations"]] == [
            "REG-141", "REG-140"]

    async def test_a_reference_not_in_the_list(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending"), _row(140, "2026-09-30", "pending")]
        _, unclear = await _cancel_turns("cancel my regularization request", "REG-999")
        assert unclear.answer().startswith("I couldn't find a request with reference REG-999 in this list")

    async def test_a_question_at_the_card_still_goes_elsewhere(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        _, other = await _cancel_turns("cancel REG-141", "show my leave balance")
        assert other.events == []


class TestAVagueCancelListsFirst:
    """QA (2026-10-06): "i want to cancel my regularization" went straight to
    the confirm card (regularisation_cancel_confirmation) when there was one
    pending request. A request that names no request always gets the list of
    what can be cancelled first; naming one (REG ID or date) opens its card."""

    @pytest.mark.parametrize("query", ["i want to cancel my regularization",
                                       "cancel my regularisation", "Cancel my regularization request."])
    async def test_one_pending_request_is_still_listed(self, erp, query):
        erp.own = [_row(141, "2026-10-01", "pending")]
        (w,) = await _cancel_turns(query)
        assert w.done()["intent"] == "regularisation_cancel_choice"
        assert w.answer().startswith("Requests you can cancel:\n1. 01-Oct-2026")
        assert w.done()["data"]["total_count"] == 1
        assert [r["cancel"] for r in w.done()["data"]["regularizations"]] == [True]

    @pytest.mark.parametrize("query", ["cancel REG-141", "cancel my regularization for 1 oct"])
    async def test_naming_the_request_opens_its_card(self, erp, query):
        erp.own = [_row(141, "2026-10-01", "pending")]
        (w,) = await _cancel_turns(query)
        assert w.done()["intent"] == "regularisation_cancel_confirmation"

    async def test_picking_it_from_the_list_opens_the_card(self, erp):
        erp.own = [_row(141, "2026-10-01", "pending")]
        _, card = await _cancel_turns("i want to cancel my regularization", "1")
        assert card.done()["intent"] == "regularisation_cancel_confirmation"
        assert "- Reference: REG-141" in card.answer()


class TestCancelFromTheMyRegularizationsTable:
    """Live (2026-10-06): the "view my regularizations" table's Cancel ("cancel
    ref-234", or its JSON) went to the LEAVE cancel flow / the apply flow's old
    "regularization_cancelled" - not the regularization cancel flow."""

    @pytest.mark.parametrize("payload,text", [
        ({"action": "cancel", "regularization_id": 29}, "cancel REG-29"),
        ({"action": "cancel", "reference_id": "REG-29"}, "cancel REG-29"),
        ({"action": "cancel", "date": "2026-09-02"}, "cancel my regularization for 2026-09-02"),
        ({"action": "cancel"}, "cancel"),
    ])
    def test_a_buttons_json_reads_as_the_instruction(self, payload, text):
        import json
        assert rc.payload_as_text(json.dumps(payload)) == text

    def test_other_json_is_not_a_cancel_button(self):
        import json
        assert rc.payload_as_text(json.dumps({"action": "confirm", "date": "2026-09-02"})) is None
        assert rc.payload_as_text("cancel REG-29") is None

    @pytest.mark.parametrize("typed", ["cancel ref-234", "Cancel REF 234", "cancel reference 234",
                                       "cancel ref no. 234"])
    def test_ref_reads_as_reg(self, typed):
        assert rc.normalize_reference(typed).lower() == "cancel reg-234"

    @pytest.mark.parametrize("query", ["cancel ref-234", '{"action": "cancel", "regularization_id": 234}',
                                       '{"action": "cancel", "date": "2026-10-01"}'])
    async def test_routed_to_regularization_cancel_after_the_view(self, monkeypatch, query):
        async def _no_shift(q):
            return None, 0.0, None

        async def _classify(prompt, labels, fallback_label="unknown"):
            return "cancel_leave", 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": 26, "conversation_id": f"tbl-{uuid.uuid4().hex[:6]}",
             "bearer_token": "t", "usage_events": [], "is_manager": False,
             "last_intent": "my_regularisation_view"}, lambda e: None)
        assert out["intent"] == rc.CANCEL_INTENT

    @pytest.mark.parametrize("query", ["cancel ref-234", '{"action": "cancel", "regularization_id": 234}'])
    async def test_the_node_opens_that_requests_card(self, erp, query):
        # Routing is covered above (it needs the conversation's last_intent);
        # here the node itself, given what the table sent.
        erp.own = [_row(234, "2026-10-01", "pending"), _row(140, "2026-09-30", "pending")]
        w = Writer()
        await rc.regularisation_cancel_node(
            {"query": query, "company_id": 26, "conversation_id": f"tbl-{uuid.uuid4().hex[:6]}",
             "bearer_token": "t", "usage_events": []}, w)
        assert w.done()["intent"] == "regularisation_cancel_confirmation"
        assert "- Reference: REG-234" in w.answer()


class TestApproveRejectFailuresSayWhatHappened:
    """Live: an approval answered "I'm unable to reach the HR system right
    now" for every non-2xx erp-api reply, including a business refusal and its
    rate limit. Each now says what erp-api actually answered."""

    @pytest.fixture
    def erp_says(self, monkeypatch):
        def _install(exc):
            async def _raise(*a, **k):
                raise exc
            monkeypatch.setattr(erp_client, "approve_regularization", _raise)
            monkeypatch.setattr(erp_client, "reject_regularization", _raise)
        return _install

    @pytest.mark.parametrize("turns", [("approve REG-142", "yes"),
                                       ("reject REG-142", "punch records show he was present", "yes")])
    async def test_a_business_refusal_is_shown(self, erp, erp_says, turns):
        erp_says(erp_client.ErpApiUnavailable(
            "erp-api returned 409", status_code=409,
            body={"success": False, "message": "This request has already been actioned"}))
        *_, done = await _approval_turns(*turns)
        assert done.answer() == "This request has already been actioned. Nothing has been changed."
        assert done.done()["intent"] == "regularisation_approval_failed"

    async def test_the_rate_limit_is_named(self, erp, erp_says):
        erp_says(erp_client.ErpApiUnavailable("erp-api returned 429", status_code=429, body=None))
        _, done = await _approval_turns("approve REG-142", "yes")
        assert done.answer() == ra._RATE_LIMITED_MESSAGE

    async def test_an_expired_session_says_log_in(self, erp, erp_says):
        erp_says(erp_client.ErpApiUnauthorized("erp-api returned 401"))
        _, done = await _approval_turns("approve REG-142", "yes")
        assert "log in again" in done.answer()

    @pytest.mark.parametrize("exc", [
        erp_client.ErpApiUnavailable("connection refused"),
        erp_client.ErpApiUnavailable("erp-api returned 503", status_code=503, body=None),
    ])
    async def test_a_real_outage_keeps_the_outage_message(self, erp, erp_says, exc):
        erp_says(exc)
        _, done = await _approval_turns("approve REG-142", "yes")
        assert done.answer() == ra._ERP_UNAVAILABLE_MESSAGE
        assert done.done()["intent"] == "regularisation_approval_unavailable"
