"""services/regularisation_cancel.py

An employee cancelling ONE of their OWN attendance-regularization requests.

    "cancel my regularization for 29 sept"
    "cancel REG-131"
    "withdraw my regularization request"

Every role may do this (erp-api: "Applicable for all employee types. Users can
only cancel their own regularization requests."), so there is no role gate
here - only the caller's own requests are ever offered, and erp-api enforces
ownership again on the write.

Same discipline as the approval flows (FR-08.3: no state change without an
explicit confirmation):

  * There is exactly ONE call site for erp_client.cancel_regularization, in
    _execute_cancel, reached only from a stored awaiting_confirmation state a
    PREVIOUS turn wrote (_build_confirmation, which returns before any write).
  * The confirming reply is matched by explicit patterns, never by an LLM.
  * The card lasts one reply: anything that is neither a yes nor a no drops
    it (resolve_pending_cancel_intent), so a stray "yes" several turns later
    can never cancel something the employee has stopped looking at.

Which statuses can still be cancelled is erp-api's rule. Pending and Approved
requests are offered; Rejected / Cancelled ones are not (there is nothing to
cancel), and erp-api's own refusal is shown verbatim for anything else.

Backing endpoints
-----------------
GET  /api/v1/ai/regularizations?status=all          (the caller's own requests)
POST /api/v1/ai/regularization/cancel   {"regularization_id": N, "cancel_reason": "..."}
"""

import logging
import json
import re
from typing import Optional

from langgraph.types import StreamWriter

import services.audit_log_service as audit_log_service
import services.erp_client as erp_client
from services import slot_store
from services.nlp_service import (fold_cancel_typos, fold_regularization_typos,
                                  fold_smart_punctuation)
from services.regularisation_approval import _extract_apply_date, _extract_request_id
from services.regularisation_display import (
    action_time_display, card_status_label, count_quota_used, date_range_display, display_date,
    employee_actions, enrich_rows, status_key, status_label, time_12h,
)
from services.regularisation_guards import is_affirmative_reply

logger = logging.getLogger(__name__)

CANCEL_INTENT = "my_regularisation_cancel"
ACTION_CANCEL = "cancel"

#: slot_store namespace for the pending selection / confirmation.
_NAMESPACE = "regularization_cancel"
#: The same, as a paused run's graph state (services/flow_interrupts).
FLOW_NAME = "regularisation_cancel"
STATE_KEY = "reg_cancel_pending"

#: Statuses offered for cancellation: Pending only (design: "Approved and
#: closed requests aren't listed"; the table's Cancel button shows only on a
#: Pending row). erp-api still has the final say on the write.
_CANCELLABLE = ("pending",)

_MIN_REASON = 3
_LIST_LIMIT = 5

_ERP_TIMEOUT_MESSAGE = "I couldn't reach the HR system in time - please try again in a moment."
_ERP_UNAVAILABLE_MESSAGE = "I'm unable to reach the HR system right now - please try again shortly."
SESSION_EXPIRED_MESSAGE = "Sorry, your session has expired — please log in again to continue."
NONE_TO_CANCEL_MESSAGE = "You don't have any pending regularization requests to cancel."
APPROVED_NOT_CANCELLABLE = "Approved requests can't be cancelled under your regularization policy."
# Sent with every "the service didn't respond" outcome: Try again / Open
# regularization page (design).
_SERVICE_DOWN_DATA = {"retry_available": True, "fallback_page": "regularization", "changed": False}

# -- Detection -----------------------------------------------------------------

_CANCEL_VERB_RE = re.compile(
    r"\b(?:cancel|cancell?ing|withdraw|withdrawing|revoke|retract|take\s+back|delete|remove)\b",
    re.IGNORECASE)
_REGULARIZATION_RE = re.compile(r"\bregulari[sz]\w*|\bREG[\s-]*\d+\b", re.IGNORECASE)
# Someone else's requests are not this flow (a manager has no cancel route).
_OTHERS_SCOPE_RE = re.compile(
    r"\b(?:team|team'?s|reportees?|employees?'?|staff|everyone)\b", re.IGNORECASE)
# "show my cancelled regularizations" is a VIEW, not an instruction.
_VIEW_RE = re.compile(
    r"\b(?:show|list|display|view|see|check|fetch|get|track|find|history|status)\b[^.?]{0,40}"
    r"\bcancel(?:l?ed|led|lations?)\b", re.IGNORECASE)
_QUESTION_RE = re.compile(
    r"^\s*(?:how|what|why|when|can\s+i|could\s+i|is\s+it|will|do\s+i|does)\b", re.IGNORECASE)


def is_cancel_regularisation_request(query: str) -> bool:
    """True for an instruction to cancel one of the caller's own
    regularization requests. Deterministic: a cancel verb, a regularization
    reference, no other-people scope, not a view or a how-to question."""
    text = fold_cancel_typos(fold_regularization_typos(fold_smart_punctuation((query or "").lower())))
    if not (_CANCEL_VERB_RE.search(text) and _REGULARIZATION_RE.search(text)):
        return False
    if _OTHERS_SCOPE_RE.search(text) or _VIEW_RE.search(text) or _QUESTION_RE.search(text):
        return False
    return True


# -- Replies to the card -------------------------------------------------------

# "yes" / "confirm" / "go ahead" / "yes cancel it" / "cancel it" / "confirm
# cancellation", optionally followed by a cancel reason ("yes, wrong date").
_CONFIRM_RE = re.compile(
    # The card's own button first: "Confirm cancellation" is one confirm, not
    # "confirm" with the reason "cancellation" (live: the reason came out "lation").
    r"^\s*(?:confirm\s+(?:the\s+)?cancell?ation\b"
    r"|(?:yes|yeah|yep|yup|sure|ok(?:ay)?|confirm(?:ed)?|go\s+ahead|proceed)\b"
    r"(?:\s*,?\s*(?:please\s+)?cancel(?:\s+it|\s+this|\s+the\s+request)?\b)?"
    r"|(?:please\s+)?cancel\s+(?:it|this|the\s+request)\b)"
    r"(?P<tail>.*)$",
    re.IGNORECASE)
# "no" / "keep it" / "don't cancel" / "never mind" / a bare "cancel" (the
# leave-cancel LLD's own reading: "Cancel" at a cancel confirmation = keep).
_DECLINE_RE = re.compile(
    # The WHOLE reply is a no: "no", "nope", "no thanks", "keep it", "don't
    # cancel", "never mind", "stop", or a bare "cancel" (cancel this action).
    # "Keep request" is the confirm card's own button: it ends the cancel flow.
    r"^\s*(?:no+|nope|nah|no\s+thanks?|keep(?:\s+it|\s+this|\s+the\s+request|\s+request|\s+my\s+request)?(?:\s+please)?"
    r"|don'?t(?:\s+cancel)?(?:\s+it)?|do\s+not(?:\s+cancel)?(?:\s+it)?|never\s*mind|leave\s+it"
    r"|stop)\s*[.!]*\s*$"
    # ...or a "no," followed by keeping it: "no, keep it", "no - don't".
    r"|^\s*no+\s*[,.\-]\s*(?:keep|don'?t|do\s+not|leave)\b",
    re.IGNORECASE)
# Not declines: "no longer needed" / "no longer required" is a REASON (and the
# most common one); "Cancel REG-141" names a request (live, it was answered
# "I've kept your regularization request"); a bare "cancel" asks WHICH request
# (see is_bare_cancel) - product decision 2026-10-06.

# "cancel" / "cancel this" / "cancel it" / "cancel this one" - a cancel that
# names no request. In a regularization conversation it means one of the
# requests just shown: the one, if there was exactly one, else the list again
# with "tell me the reference ID or date".
_BARE_CANCEL_RE = re.compile(
    r"^\s*(?:please\s+|pls\s+)?cancel(?:\s+(?:this|it|that|this\s+one|that\s+one|the\s+request|"
    r"this\s+request|my\s+request|the\s+one))?(?:\s+please)?\s*[.!]*\s*$",
    re.IGNORECASE)
_BARE_CANCEL_ONLY_RE = re.compile(r"^\s*(?:please\s+|pls\s+)?cancel(?:\s+please)?\s*[.!]*\s*$",
                                  re.IGNORECASE)

#: Requests the last regularization view showed (ids), so "cancel this" can
#: mean the request on screen. Written by my_regularisation_view_node.
LAST_VIEW_NAMESPACE = "regularization_last_view"

#: Intents after which a bare "cancel" is about regularization requests.
_REGULARISATION_CONTEXT_PREFIXES = ("my_regularisation_view", "regularisation_cancel",
                                    "my_regularisation_cancel")


# A Cancel button's JSON from a regularization table row ("view my
# regularizations" / "Requests you can cancel"): {"action": "cancel",
# "regularization_id": 29} - or reference_id "REG-29", or only the row's date.
# Live: the date-only shape went to the regularization APPLY flow, whose own
# cancel answered with the old "regularization_cancelled" intent, and a
# regularization_id was not read at all.
_CANCEL_ACTIONS = {"cancel", "cancel_request", "cancel_regularization", "cancel_regularisation"}
_REF_NUMBER_RE = re.compile(r"(\d+)\s*$")


def cancel_payload(query: str) -> Optional[dict]:
    """{"regularization_id", "date"} from a Cancel button's JSON, or None
    when the message is not one."""
    text = (query or "").strip()
    if not text.startswith("{"):
        return None
    try:
        obj = json.loads(text)
    except (TypeError, ValueError):
        return None
    if not isinstance(obj, dict) or str(obj.get("action") or "").strip().lower() not in _CANCEL_ACTIONS:
        return None
    rid = _as_int(obj.get("regularization_id") or obj.get("id"))
    if rid is None:
        ref = _REF_NUMBER_RE.search(str(obj.get("reference_id") or obj.get("reference") or ""))
        rid = int(ref.group(1)) if ref else None
    day = obj.get("apply_date") or obj.get("date") or obj.get("date_from")
    return {"regularization_id": rid, "date": str(day)[:10] if day else None}


# "cancel ref-234" / "ref 234" / "reference 234" / "ref no. 234" - a generic
# reference typed (or sent by a table row's Cancel button) in a regularization
# conversation. Read as REG-234. Live: "cancel ref-234" from the "view my
# regularizations" table went to the LEAVE cancel flow.
_GENERIC_REF_RE = re.compile(
    r"\bref(?:erence)?(?:\s*(?:no\.?|number|id))?\s*[-#:.]?\s*(\d+)\b", re.IGNORECASE)


def normalize_reference(query: str) -> str:
    """"cancel ref-234" -> "cancel REG-234". JSON is left to cancel_payload."""
    text = query or ""
    if text.lstrip().startswith("{"):
        return text
    return _GENERIC_REF_RE.sub(lambda m: f"REG-{m.group(1)}", text)


def payload_as_text(query: str) -> Optional[str]:
    """A Cancel button's JSON as the instruction it stands for, so the button
    and the typed words go the same way: "cancel REG-29", "cancel my
    regularization for 2026-09-02", or a bare "cancel"."""
    payload = cancel_payload(query)
    if payload is None:
        return None
    if payload["regularization_id"] is not None:
        return f"cancel REG-{payload['regularization_id']}"
    if payload["date"]:
        return f"cancel my regularization for {payload['date']}"
    return "cancel"


def has_open_card(company_id, conversation_id: str) -> bool:
    """A cancel card (or its reason / which-one step) is waiting on a reply."""
    state = slot_store.get_slots(_NAMESPACE, company_id, conversation_id) or {}
    return state.get("step") in ("awaiting_confirmation", "awaiting_reason", "awaiting_selection")


def is_bare_cancel(query: str) -> bool:
    return bool(_BARE_CANCEL_RE.match(fold_cancel_typos(query)))


def in_regularisation_context(last_intent) -> bool:
    """The previous reply was a regularization list, status answer or cancel step."""
    return str(last_intent or "").startswith(_REGULARISATION_CONTEXT_PREFIXES)


def is_cancel_in_regularisation_context(query: str, last_intent) -> bool:
    """A bare "cancel" / "cancel this" right after a regularization list,
    status answer or cancel step."""
    return is_bare_cancel(query) and str(last_intent or "").startswith(_REGULARISATION_CONTEXT_PREFIXES)
_REFERENCE_IN_TEXT_RE = re.compile(r"\bREG[\s-]*\d+\b|\bregulari[sz]\w*(?:\s+requests?)?\b",
                                   re.IGNORECASE)
_ORDINALS = {"first": 1, "1st": 1, "second": 2, "2nd": 2, "third": 3, "3rd": 3,
             "fourth": 4, "4th": 4, "fifth": 5, "5th": 5, "last": -1}
_BARE_INDEX_RE = re.compile(r"^\s*(?:#|no\.?\s*|number\s*)?(\d{1,2})\s*[.!]*\s*$")


def _is_decline(query: str) -> bool:
    q = (query or "").strip()
    if _CONFIRM_RE.match(q):
        return False
    return bool(_DECLINE_RE.match(q))


def _confirmation_reason(query: str) -> Optional[str]:
    """None when this is not a confirmation; otherwise the cancel reason given
    with it ("yes, wrong date" -> "wrong date"), or "" for a plain yes."""
    q = fold_smart_punctuation(query or "").strip()
    if is_affirmative_reply(q):
        return ""
    match = _CONFIRM_RE.match(q)
    if not match:
        return None
    # "yes cancel REG-141" - the reference names the request, it is not a reason.
    tail = _REFERENCE_IN_TEXT_RE.sub(" ", match.group("tail") or "")
    tail = re.sub(r"^[\s,.:;-]+|(?:\s*(?:as|because|reason(?:\s+is)?)\s*[:,-]?\s*)", "",
                  tail.strip(), count=1).strip(" .!,")
    return tail if len(tail) >= _MIN_REASON else ""


def _pick(query: str, candidates: list) -> Optional[dict]:
    """The candidate a selection reply names: REG id, date, or position."""
    if not candidates:
        return None
    req_id = _extract_request_id(query)
    if req_id is not None:
        return next((c for c in candidates if _as_int(c.get("regularization_id")) == req_id), None)
    day = _extract_apply_date(query)
    if day:
        dated = [c for c in candidates if str(c.get("apply_date") or "")[:10] == day]
        return dated[0] if len(dated) == 1 else None
    text = (query or "").strip().lower()
    for word, pos in _ORDINALS.items():
        if re.search(rf"\b{word}\b", text):
            return candidates[pos - 1] if pos == -1 or pos <= len(candidates) else None
    m = _BARE_INDEX_RE.match(text)
    if m:
        pos = int(m.group(1))
        return candidates[pos - 1] if 1 <= pos <= len(candidates) else None
    return None


def _is_new_request_or_question(query: str) -> bool:
    """A question or a different request ("show my leave balance", "what is my
    quota?") - never an answer to a cancel prompt, so it goes to its own flow."""
    return bool(_NOT_A_REASON_RE.search((query or "").strip()))


# "cancel again" / "cancel it again" / "cancel my previous request" / "cancel
# that one" - after a "Keep request", a follow-up naming no request resumes the
# SAME one (leave cancel's "declined" memory).
_RESUME_CANCEL_RE = re.compile(
    r"^\s*(?:please\s+)?cancel\s+(?:it\s+|that\s+|this\s+)?(?:again|anyway|after\s+all)\b"
    r"|^\s*cancel\s+(?:my\s+|the\s+)?(?:previous|last|same|earlier)\s+(?:one|request|regulari[sz]\w*)\b",
    re.IGNORECASE)


def resolve_pending_cancel_intent(company_id, conversation_id: str, query: str):
    """CANCEL_INTENT when this turn answers a cancel prompt this conversation
    is waiting on, else None. Same reach as leave cancel: at the card, the
    reason step and the which-one list, every reply is the prompt's - except
    a question or a new request, which drops the prompt and goes elsewhere."""
    state = slot_store.get_slots(_NAMESPACE, company_id, conversation_id) or {}
    if not state.get("step"):
        return None
    answers, after = resolve_reply(state, query)
    if after is None:
        slot_store.clear_slots(_NAMESPACE, company_id, conversation_id)
    elif after is not state:
        slot_store.set_slots(_NAMESPACE, company_id, conversation_id, after)
    return CANCEL_INTENT if answers else None


AWAITING_STEPS = ("awaiting_reason", "awaiting_confirmation", "awaiting_selection")


def resolve_reply(pending: dict, query: str):
    """(answers_the_prompt, pending_after) for a reply while `pending` waits.
    pending_after is `pending` itself when unchanged, None when it ends, or
    the "dropped" memory. The one rule for both stores: Redis (above) and the
    graph state of a paused run (services/flow_interrupts)."""
    # A Cancel button's JSON, or "cancel ref-234", as "cancel REG-…".
    query = payload_as_text(query) or normalize_reference(fold_cancel_typos(query))
    pending = pending or {}
    step = pending.get("step")
    if not step:
        return False, None
    if step in AWAITING_STEPS:
        # Answers: yes / Confirm cancellation / no / Keep request / a reason /
        # "Cancel REG-141" / a pick - and anything unclear, which the node
        # re-asks rather than dropping the card (leave cancel's behaviour).
        if (_confirmation_reason(query) is not None or _is_decline(query)
                or is_cancel_regularisation_request(query) or is_bare_cancel(query)
                or (step == "awaiting_selection" and _pick(query, pending.get("candidates") or []))
                or not _is_new_request_or_question(query)):
            return True, pending
    elif step == "declined":
        # After "Keep request": "cancel" / "cancel again" / "cancel my previous
        # request" re-offers the same request; anything else ends the memory.
        if is_bare_cancel(query) or _RESUME_CANCEL_RE.search(query or ""):
            return True, pending
        return False, None
    elif step == "dropped":
        # The turn after a prompt was dropped. A "yes" here is still aimed at
        # the card the employee saw, so it gets a deterministic "that is no
        # longer waiting" from this flow. Left to the chat model, it was
        # answered "Your regularization request REG-131 ... has been
        # cancelled" - a cancellation that never happened.
        if _confirmation_reason(query) is not None:
            return True, pending        # the node reads the card, then clears it
        return False, None
    # A question or a new request: the prompt is dropped, remembered as such
    # for one more turn so a late "yes" can't be mistaken for anything else.
    return False, {"step": "dropped", "card": pending.get("card") or {}}


class PendingStore:
    """Where this flow's waiting card lives: Redis (slot_store), or - when the
    flow pauses with interrupt() (INTERRUPT_REG_CANCEL) - the graph state, so it
    is saved with the paused run in Postgres. The node returns update() with
    its result; Redis writes happen at once, as they always have."""

    def __init__(self, state: dict):
        self.company_id = state.get("company_id")
        self.conversation_id = state.get("conversation_id", "")
        self.in_graph = FLOW_NAME in (state.get("interrupt_flows") or [])
        self._value = state.get(STATE_KEY) if self.in_graph else None
        self._changed = False

    def get(self) -> dict:
        if self.in_graph:
            return dict(self._value or {})
        return slot_store.get_slots(_NAMESPACE, self.company_id, self.conversation_id) or {}

    def set(self, value: dict) -> None:
        if self.in_graph:
            self._value, self._changed = dict(value), True
        else:
            slot_store.set_slots(_NAMESPACE, self.company_id, self.conversation_id, value)

    def clear(self) -> None:
        if self.in_graph:
            self._value, self._changed = None, True
        else:
            slot_store.clear_slots(_NAMESPACE, self.company_id, self.conversation_id)

    def update(self) -> dict:
        return {STATE_KEY: self._value} if self.in_graph and self._changed else {}


# -- Rendering -----------------------------------------------------------------

def _as_int(value):
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def _hhmm(value) -> str:
    parts = str(value or "").strip().split(":")
    return ":".join(parts[:2]) if len(parts) >= 2 else str(value or "").strip()


def _time_span(row: dict) -> str:
    start, end = _hhmm(row.get("from_time")), _hhmm(row.get("to_time"))
    return f"{start} to {end}" if start and end else (start or end or "-")


def _ref(row: dict) -> str:
    return row.get("reference_id") or f"REG-{row.get('regularization_id')}"


def _date(row: dict) -> str:
    return str(row.get("apply_date_display") or row.get("apply_date") or "-")


def _render_row(index: int, row: dict) -> str:
    return (f"{index}. {_date(row)}, {_time_span(row)} - "
            f"{row.get('regularization_type') or 'Regularization'} - "
            f"{status_label(row) or row.get('status_name') or '-'} ({_ref(row)})")


def _card(row: dict, cancel_reason: Optional[str]) -> dict:
    return {
        "request_type": "Regularization",
        "action": ACTION_CANCEL,
        "regularization_id": row.get("regularization_id"),
        "reference_id": _ref(row),
        "apply_date": row.get("apply_date"),
        "apply_date_display": _date(row),
        "from_time": row.get("from_time"),
        "to_time": row.get("to_time"),
        "time_span": _time_span(row),
        "regularization_type": row.get("regularization_type"),
        "reason": row.get("reason"),
        "status_name": row.get("status_name"),
        "status_label": card_status_label(row),
        # The employee's own reason - never a default. None until they give it.
        "cancel_reason": cancel_reason,
        "cancel_reason_required": not cancel_reason,
        "actions": CARD_ACTIONS,
        # The design's card: Reference, Date (from-to), Regularization type,
        # Status ("Pending approval"), Applied on.
        "date_from": row.get("date_from") or row.get("apply_date"),
        "date_to": row.get("date_to") or row.get("apply_date"),
        "date_range_display": row.get("date_range_display") or date_range_display(row),
        "in_time_display": row.get("in_time_display") or time_12h(row.get("from_time")),
        "out_time_display": row.get("out_time_display") or time_12h(row.get("to_time")),
        "applied_on": row.get("applied_on"),
        "applied_on_display": row.get("applied_on_display"),
    }


def _when(card: dict) -> str:
    """"01-Oct-2026, 9:01 AM to 6:30 PM" - the request's day and times."""
    times = " to ".join(t for t in (card.get("in_time_display"), card.get("out_time_display")) if t)
    day = card.get("apply_date_display") or card.get("apply_date") or "-"
    return f"{day}, {times}" if times else day


def _render_confirmation(card: dict, match_label: Optional[str] = None) -> str:
    """The "Cancel this request?" confirm card: the request's details, then
    Confirm cancellation / Keep request. The reason is asked after the confirm
    (shown here only when it was already given)."""
    lines = [
        "Cancel this request?",
        f"- Reference: {card['reference_id']}",
        f"- Date: {card.get('date_range_display') or card['apply_date_display']}",
        f"- Regularization type: {card.get('regularization_type') or '-'}",
        f"- Status: {card.get('status_label') or card.get('status_name') or '-'}",
        f"- Applied on: {card.get('applied_on_display') or '-'}",
    ]
    if card.get("cancel_reason"):
        lines.append(f"- Cancel reason: {card['cancel_reason']}")
    lines += ["", "Confirm the cancellation, or keep the request."]
    return "\n".join(lines)


def _keep_message(card: dict) -> str:
    """The "Keep request" reply: names WHICH request was left alone."""
    return (f"No problem - I've kept your regularization request for "
            f"{card.get('apply_date_display') or 'that date'} "
            f"({card.get('reference_id')}). Nothing has been changed.")


#: The confirm card's buttons (design). A press arrives as its label text.
CARD_ACTIONS = [{"label": "Confirm cancellation", "action": "confirm"},
                {"label": "Keep request", "action": "keep"}]

# A reply at the reason step that is a question or a new request, not a reason
# ("show my leave balance", "what is my quota?"): never taken as the reason -
# that would cancel the request with someone's unrelated question as its reason.
_NOT_A_REASON_RE = re.compile(
    r"\?\s*$|^\s*(?:show|list|view|display|apply|check|what|whats|what's|how|when|where|why|which|"
    r"who|approve|reject|give|tell|can|could|would|should|is|are|do|does|did|regulari[sz]e|"
    r"i\s+want\s+to\s+(?:apply|see|check|know))\b",
    re.IGNORECASE)


def _usable_reason(query: str) -> Optional[str]:
    """The message as a cancel reason, or None when it can't be one."""
    text = (query or "").strip().strip("'\"“”‘’").strip()
    if len(text) < _MIN_REASON or _NOT_A_REASON_RE.search(text) or is_bare_cancel(text):
        return None
    return text


_INLINE_REASON_RE = re.compile(
    r"\b(?:because(?:\s+of)?|since|due\s+to|reason\s*(?:is|was|:|-))\s+(?P<r>.+?)\s*[.!]*\s*$",
    re.IGNORECASE)


# -- Node ----------------------------------------------------------------------

async def regularisation_cancel_node(state: dict, writer: StreamWriter) -> dict:
    """The cancel flow, with its waiting card in Redis or - when the flow
    pauses (INTERRUPT_REG_CANCEL) - in the graph state it returns with its
    answer (PendingStore.update)."""
    store = PendingStore(state)
    if state.get("resumed_flow") == FLOW_NAME:
        # A reply to the paused card skips classify_node, which would have
        # announced the intent - announced here instead, the same way.
        writer({"type": "intent", "intent": CANCEL_INTENT, "is_hr": True,
                "is_database_related": True, "has_date_expression": False})
    out = await _cancel_flow(state, writer, store)
    return {**(out or {}), **store.update()}


async def _cancel_flow(state: dict, writer: StreamWriter, store: PendingStore) -> dict:
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    query = state.get("query", "") or ""
    # A Cancel button's JSON (a table row) reads as the instruction it stands
    # for - "cancel REG-29" - so the click and the typed words go the same way.
    query = payload_as_text(query) or normalize_reference(fold_cancel_typos(query))
    usage_events = list(state.get("usage_events", []))

    def _finish(message: str, finish_intent: str = CANCEL_INTENT, extra_data: dict = None) -> dict:
        data = {"answer": message}
        if extra_data:
            data.update(extra_data)
        writer({"type": "done", "intent": finish_intent, "is_hr": True,
                "data": data, "message": message, "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    pending = store.get()

    # -- A "yes" to a card that is no longer waiting ---------------------------
    # Routed here by resolve_pending_cancel_intent while the dropped card is
    # still stored, so the reply can name the request.
    if pending.get("step") == "dropped":
        store.clear()
        card = pending.get("card") or {}
        again = (f"say 'cancel {card['reference_id']}'" if card.get("reference_id")
                 else "tell me which request to cancel")
        return _finish("That cancellation is no longer waiting for your confirmation, so "
                       f"nothing has been cancelled. If you still want to cancel it, {again} "
                       "and I'll show it to you again.",
                       finish_intent="regularisation_cancel_expired")

    # -- The card's replies (same steps as leave cancel) ------------------------
    #   awaiting_confirmation: the preview card ("Would you like to cancel this
    #     request? Reply to confirm and the reason for cancelling."). A confirm
    #     with a reason cancels; without one, the reason is asked next.
    #   awaiting_reason: confirmed; the whole reply is the reason.
    #   declined: "Keep request" was chosen; a bare "cancel" / "cancel again"
    #     re-offers the same request (see resolve_pending_cancel_intent).
    if pending.get("step") in ("awaiting_reason", "awaiting_confirmation"):
        card = pending.get("card") or {}
        stored_reason = card.get("cancel_reason")

        def _execute(reason):
            return _execute_cancel(pending, reason, query, bearer_token, company_id,
                                   conversation_id, writer, _finish, store=store)

        def _ask_reason():
            store.set({**pending, "step": "awaiting_reason"})
            # A plain "type your reason" step - NOT the card again, and only
            # what that needs (step / input_required say "show a text input").
            return _finish(f"Please share the reason for cancelling {card.get('reference_id')}.",
                           finish_intent="regularisation_cancel_awaiting_reason",
                           extra_data={"step": "awaiting_cancel_reason",
                                       "input_required": "cancel_reason",
                                       "reference_id": card.get("reference_id"),
                                       "regularization_id": card.get("regularization_id")})

        async def _confirmed(reason):
            # Confirmed: cancel now if the reason is known, else ask for it.
            if reason:
                return await _execute(reason)
            return _ask_reason()

        if _is_decline(query):
            # Kept as a short-lived "declined" memory (leave cancel does the
            # same), so "cancel again" picks straight back up.
            store.set({"step": "declined", "card": card,
                                  "regularization_id": pending.get("regularization_id")})
            return _finish(_keep_message(card), finish_intent="regularisation_cancel_kept",
                           extra_data={**card, "changed": False})
        given = _confirmation_reason(query)
        if given is not None:
            # "Confirm cancellation" / "yes" / "yes, applied for the wrong date"
            return await _confirmed(given or stored_reason)
        # "Cancel REG-141" (or "cancel my regularization for 1 oct") naming the
        # request on this card confirms it; naming another one is a new
        # instruction, read fresh below.
        if is_cancel_regularisation_request(query):
            inline = _INLINE_REASON_RE.search(query)
            target = _INLINE_REASON_RE.sub(" ", query) if inline else query
            named_id = _extract_request_id(target)
            named_day = _extract_apply_date(target) if named_id is None else None
            same = ((named_id is not None
                     and _as_int(named_id) == _as_int(pending.get("regularization_id")))
                    or (named_day is not None and named_day == card.get("apply_date")))
            if not same:
                store.clear()
            else:
                reason = inline.group("r").strip() if inline else ""
                return await _confirmed(reason if len(reason) >= _MIN_REASON else stored_reason)
        elif pending.get("step") == "awaiting_reason":
            if is_bare_cancel(query):
                store.clear()
            else:
                # The whole reply is the reason; an empty one is asked again.
                reason = _usable_reason(query)
                if reason:
                    return await _execute(reason)
                return _ask_reason()
        elif is_bare_cancel(query):
            # A bare "cancel" at the card asks which request (product decision).
            store.clear()
        else:
            # Unclear - re-ask and keep the card (leave cancel's behaviour).
            return _finish(f"Sorry, I didn't catch that — would you like me to go ahead and cancel "
                           f"your regularization request ({_when(card)}, ref "
                           f"{card.get('reference_id')})? (yes/no)",
                           finish_intent="regularisation_cancel_confirmation",
                           extra_data={**card, "step": "awaiting_cancel_confirmation"})

    # -- Resuming after "Keep request" -------------------------------------------
    if pending.get("step") == "declined":
        card = pending.get("card") or {}
        store.clear()
        if pending.get("regularization_id") is not None and (
                is_bare_cancel(query) or _RESUME_CANCEL_RE.search(query)):
            return _build_confirmation(_row_from_card(card), None, company_id, conversation_id,
                                       writer, _finish, store=store)

    # -- The "which one?" turn -------------------------------------------------
    if pending.get("step") == "awaiting_selection":
        candidates = pending.get("candidates") or []
        if _is_decline(query):
            store.clear()
            return _finish("No problem - nothing has been cancelled.",
                           finish_intent="regularisation_cancel_kept")
        chosen = _pick(query, candidates)
        if chosen is not None:
            # "cancel REG-141 because I applied twice" - the pick can carry the
            # reason too; it is kept for the card.
            inline = _INLINE_REASON_RE.search(query)
            picked_reason = inline.group("r").strip() if inline else ""
            return _build_confirmation(
                chosen, picked_reason if len(picked_reason) >= _MIN_REASON
                else pending.get("cancel_reason"),
                company_id, conversation_id, writer, _finish, store=store)
        if not (is_bare_cancel(query) or is_cancel_regularisation_request(query)):
            # Couldn't tell which - same list again, and a specific ask
            # (leave cancel's wording).
            writer({"type": "regularization_cancel_choice",
                    "data": _selection_data(candidates, len(candidates))})
            named = _extract_request_id(query)
            if named is not None:
                message = (f"I couldn't find a request with reference REG-{named} in this list — "
                           f"please pick one below by date, number, or reference.")
            else:
                message = ("Sorry, I couldn't quite tell which request you mean — could you let "
                           "me know the date, applied date, number, or reference so I can find "
                           "the right one for you?")
            return _finish(message, finish_intent="regularisation_cancel_choice",
                           extra_data=_selection_data(candidates, len(candidates)))
        store.clear()

    # -- A fresh instruction ---------------------------------------------------
    inline = _INLINE_REASON_RE.search(query)
    cancel_reason = inline.group("r").strip() if inline and len(inline.group("r").strip()) >= _MIN_REASON else None
    target_text = _INLINE_REASON_RE.sub(" ", query) if inline else query
    request_id = _extract_request_id(target_text)
    apply_date = _extract_apply_date(target_text) if request_id is None else None

    writer({"type": "fetching_my_regularizations",
            "message": "Checking your regularization requests..."})
    try:
        result = await erp_client.get_my_regularizations(
            bearer_token, company_id=company_id, conversation_id=conversation_id)
    except erp_client.ErpApiUnauthorized:
        return _finish(SESSION_EXPIRED_MESSAGE)
    except erp_client.ErpApiTimeout:
        return _finish(_ERP_TIMEOUT_MESSAGE)
    except erp_client.ErpApiUnavailable:
        return _finish(_ERP_UNAVAILABLE_MESSAGE)

    body = result.get("body") or {}
    if not body.get("success", True) or (result.get("http_status") or 200) >= 400:
        return _finish(str(body.get("message") or _ERP_UNAVAILABLE_MESSAGE))

    rows = enrich_rows((body.get("data") or {}).get("regularizations") or [])
    rows.sort(key=lambda r: (str(r.get("apply_date") or ""), _as_int(r.get("regularization_id")) or 0),
              reverse=True)
    cancellable = [r for r in rows if status_key(r) in _CANCELLABLE]

    def _nothing_to_cancel(row: dict) -> dict:
        # Design: "This request can't be cancelled" - the status as recorded,
        # and for an approved one the policy line.
        label = status_label(row) or row.get("status_name")
        why = (APPROVED_NOT_CANCELLABLE if status_key(row) == "approved"
               else "There's nothing left to cancel.")
        return _finish(f"This request can't be cancelled. Your request for {_date(row)} "
                       f"(Ref: {_ref(row)}) is already {label}. {why}",
                       finish_intent="regularisation_cancel_failed",
                       extra_data={"reference_id": _ref(row), "status_label": label,
                                   "changed": False})

    if request_id is not None:
        row = next((r for r in rows if _as_int(r.get("regularization_id")) == request_id), None)
        if row is None:
            return _finish(f"I couldn't find REG-{request_id} among your regularization requests. "
                           f"Nothing has been changed.", finish_intent="regularisation_cancel_failed")
        if row not in cancellable:
            return _nothing_to_cancel(row)
        return _build_confirmation(row, cancel_reason, company_id, conversation_id, writer, _finish, store=store)

    if apply_date:
        on_day = [r for r in rows if str(r.get("apply_date") or "")[:10] == apply_date]
        candidates = [r for r in on_day if r in cancellable]
        if not candidates:
            if on_day:
                return _nothing_to_cancel(on_day[0])
            return _finish(f"You don't have a pending regularization request for "
                           f"{apply_date}. Nothing has been changed.",
                           finish_intent="regularisation_cancel_failed")
    else:
        candidates = cancellable

    # A bare "cancel" / "cancel this" names no request: it means one of those
    # the last regularization reply showed ("take the conversation in mind").
    bare = is_bare_cancel(query)
    on_screen_one = False
    if bare:
        last = slot_store.get_slots(LAST_VIEW_NAMESPACE, company_id, conversation_id) or {}
        seen = {str(i) for i in last.get("ids") or []}
        on_screen = [r for r in candidates if str(r.get("regularization_id")) in seen]
        if on_screen:
            candidates = on_screen
            on_screen_one = len(on_screen) == 1

    if not candidates:
        return _finish(NONE_TO_CANCEL_MESSAGE, finish_intent="regularisation_cancel_failed")
    # Straight to the card only when the employee pointed at ONE request: by
    # date ("cancel my regularization for 1 oct"), or "cancel this" right
    # after a reply that showed exactly one. A request that names nothing
    # ("i want to cancel my regularization") always gets the list of what can
    # be cancelled - even a list of one (QA: it jumped straight to the card).
    pointed_at_one = (apply_date is not None
                      or (bare and not _BARE_CANCEL_ONLY_RE.match(query) and on_screen_one))
    if len(candidates) == 1 and pointed_at_one:
        return _build_confirmation(candidates[0], cancel_reason, company_id, conversation_id,
                                   writer, _finish, store=store)

    shown = [{**r, **employee_actions(r)} for r in candidates[:_LIST_LIMIT]]
    store.set({
        "step": "awaiting_selection", "candidates": shown, "cancel_reason": cancel_reason})
    table = _selection_data(shown, len(candidates))
    writer({"type": "regularization_cancel_choice", "data": table})
    return _finish(_selection_message(shown, len(candidates)),
                   finish_intent="regularisation_cancel_choice", extra_data=table)


def _selection_data(shown: list, total: int) -> dict:
    """The "Requests you can cancel" table - each row with its Cancel button
    (cancel=true)."""
    return {"title": "Requests you can cancel",
            "subtitle": "Based on your regularization policy. Approved and closed requests "
                        "aren't listed.",
            # Every request that can be cancelled (the table shows up to 5).
            "total_count": total,
            "regularizations": shown}


def _selection_message(shown: list, total: int) -> str:
    lines = "\n".join(_render_row(i, r) for i, r in enumerate(shown, start=1))
    more = f"\n({total - _LIST_LIMIT} more not shown)" if total > _LIST_LIMIT else ""
    example = shown[0]
    return ("Requests you can cancel:\n"
            f"{lines}{more}\n\nWhich one would you like to cancel? Please tell me its "
            f"reference ID or date - for example 'cancel {_ref(example)}' or "
            f"'cancel {_date(example)}'.")


def _row_from_card(card: dict) -> dict:
    """The stored card back as a row, to re-offer the same request."""
    return {**card, "status_name": card.get("status_name") or "pending"}


def _build_confirmation(row, cancel_reason, company_id, conversation_id, writer, _finish,
                        match_label=None, store=None):
    """Shows the summary and STOPS - no write on this turn."""
    store = store or PendingStore({'company_id': company_id, 'conversation_id': conversation_id})
    card = _card(row, cancel_reason or None)
    store.set({
        # The confirm card first; the reason is asked after "Confirm cancellation".
        "step": "awaiting_confirmation",
        "regularization_id": row.get("regularization_id"),
        "card": card,
        "cancel_reason": card["cancel_reason"],
    })
    writer({"type": "regularization_cancel_confirmation", "data": card})
    # step tells the client which screen this is: the confirm card (with its
    # Confirm cancellation / Keep request actions), vs "awaiting_cancel_reason".
    return _finish(_render_confirmation(card), finish_intent="regularisation_cancel_confirmation",
                   extra_data={**card, "step": "awaiting_cancel_confirmation"})


async def _execute_cancel(pending, cancel_reason, confirmation_query, bearer_token, company_id,
                          conversation_id, writer, _finish, store=None):
    """The ONLY path that changes state, reachable only from a stored
    awaiting_confirmation written by a previous turn."""
    store = store or PendingStore({'company_id': company_id, 'conversation_id': conversation_id})
    card = pending.get("card") or {}
    regularization_id = pending.get("regularization_id")
    # Cleared BEFORE the call: a failed clear after a successful cancel would
    # leave a card a second "yes" could re-send.
    store.clear()
    if regularization_id is None:
        return _finish("I've lost track of which request that was - could you name it again? "
                       "Nothing has been changed.")

    ref = card.get("reference_id") or f"REG-{regularization_id}"
    service_down = (f"Couldn't cancel right now - the system didn't respond, so {ref} has not "
                    f"been cancelled. Your request is unchanged. You can try again, or open the "
                    f"regularization page.")

    # Final re-check at confirm (design): the approver may have acted since
    # the card was shown. Read the request's status now; if it is no longer
    # Pending, say so and change nothing.
    try:
        recheck = await erp_client.get_my_regularizations(
            bearer_token, company_id=company_id, conversation_id=conversation_id)
        rows = ((recheck.get("body") or {}).get("data") or {}).get("regularizations")
    except erp_client.ErpApiUnauthorized:
        return _finish(SESSION_EXPIRED_MESSAGE)
    except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable):
        return _finish(service_down, finish_intent="regularisation_cancel_failed",
                       extra_data=dict(_SERVICE_DOWN_DATA))
    current = next((r for r in rows or [] if _as_int(r.get("regularization_id")) == _as_int(regularization_id)),
                   None) if isinstance(rows, list) else None
    if current is not None and status_key(current) not in _CANCELLABLE:
        label = status_label(current) or current.get("status_name")
        return _finish(f"Request not cancelled - {ref} was {label.lower()} a moment ago, so it can "
                       f"no longer be cancelled. Current status: {label}. Nothing was changed.",
                       finish_intent="regularisation_cancel_failed",
                       extra_data={"reference_id": ref, "status_label": label, "changed": False})

    writer({"type": "cancelling_regularization",
            "message": "Cancelling your regularization request..."})

    async def _log(executed, erp_status, erp_message):
        # The regularization audit row (resource_type regularization); the
        # action column records that this was a cancel by the employee.
        await audit_log_service.log_regularization_approval(
            action=ACTION_CANCEL, regularization_id=regularization_id, executed=executed,
            confirmation_query=confirmation_query, requested_query=None,
            erp_status=erp_status, erp_message=erp_message,
            company_id=company_id, conversation_id=conversation_id,
        )

    try:
        result = await erp_client.cancel_regularization(
            bearer_token, regularization_id, cancel_reason,
            company_id=company_id, conversation_id=conversation_id)
    except erp_client.ErpApiUnauthorized:
        await _log(False, 401, "session rejected")
        return _finish(SESSION_EXPIRED_MESSAGE)
    except erp_client.ErpApiTimeout:
        # A timeout may or may not have been applied, so it is not "unchanged".
        await _log(False, None, "erp-api timeout - outcome unknown")
        return _finish("I couldn't reach the HR system in time to cancel this. Please check "
                       "your regularization requests before trying again.",
                       finish_intent="regularisation_cancel_failed",
                       extra_data={**_SERVICE_DOWN_DATA, "changed": None})
    except erp_client.ErpApiUnavailable as exc:
        await _log(False, None, "erp-api unavailable")
        if getattr(exc, "erp_message", None):
            return _finish(f"{exc.erp_message.rstrip('.')}. Nothing has been changed.",
                           finish_intent="regularisation_cancel_failed")
        return _finish(service_down, finish_intent="regularisation_cancel_failed",
                       extra_data=dict(_SERVICE_DOWN_DATA))
    except Exception as e:
        logger.exception("[RegularisationCancel] unexpected error cancelling %s: %s",
                         regularization_id, e)
        await _log(False, None, f"unexpected error - outcome unknown: {type(e).__name__}: {e}")
        return _finish("Something went wrong while I was cancelling that, and I can't tell "
                       "whether it went through. Please check your regularization requests "
                       "before trying again.", finish_intent="regularisation_cancel_failed")

    body = result.get("body") or {}
    http_status = result.get("http_status")
    erp_message = body.get("message")
    if not body.get("success", False):
        await _log(False, http_status, erp_message)
        reason = str(erp_message or "I couldn't cancel that request").strip().rstrip(".")
        return _finish(f"{reason}. Nothing has been changed.",
                       finish_intent="regularisation_cancel_failed")

    cancelled = body.get("data") or {}
    await _log(True, http_status, erp_message)
    status = str(cancelled.get("status_name") or "cancelled")
    message = (f"Cancelled - your regularization request for "
               f"{card.get('apply_date_display') or 'that date'} ({ref}) "
               f"is now {status}.")
    data = {
        **cancelled,
        "reference_id": ref,
        "date_range_display": card.get("date_range_display"),
        "regularization_type": card.get("regularization_type"),
        "status_label": status.replace("_", " ").title(),
        "cancelled_on": action_time_display(),
    }
    # Design: "Quota for <cycle>: 0 of 2 used" - re-read after the cancel, so
    # it is what erp-api now holds, never a number worked out here.
    quota = await _quota_after_cancel(card, bearer_token, company_id, conversation_id)
    if quota:
        data["quota"] = quota
        message += f" Quota for {quota['label']}: {quota['used']} of {quota['limit']} used."
    writer({"type": "regularization_cancel_success", "data": {**data, "message": message}})
    return _finish(message, finish_intent="regularisation_cancel_success", extra_data=data)


async def _quota_after_cancel(card, bearer_token, company_id, conversation_id):
    """{"label", "used", "limit"} for the cancelled request's payroll cycle, or
    None when it can't be read (the success itself never depends on it)."""
    import services.regularisation_node as regularisation_node  # cycle: it imports nothing of ours
    from services import payroll_cycle
    from datetime import datetime as _dt
    try:
        settings = await regularisation_node._get_regularization_settings(
            bearer_token=bearer_token, company_id=company_id, conversation_id=conversation_id)
        if not settings.get("available") or settings.get("limit") is None or not settings.get("cycle"):
            return None
        day = _dt.strptime(str(card.get("apply_date") or "")[:10], "%Y-%m-%d").date()
        cycle = payroll_cycle.cycle_for(settings["cycle"], day)
        result = await erp_client.get_my_regularizations(
            bearer_token, company_id=company_id, conversation_id=conversation_id)
        rows = ((result.get("body") or {}).get("data") or {}).get("regularizations")
        if cycle is None or not isinstance(rows, list):
            return None
        return {"label": cycle.label(), "used": count_quota_used(rows, cycle),
                "limit": settings["limit"]}
    except Exception:
        logger.info("[RegularisationCancel] quota after cancel unavailable", exc_info=True)
        return None
