"""services/regularisation_approval.py

Conversational attendance-regularization review and approval for MANAGERS —
the regularization counterpart of services/leave_approval.py, behind the same
explicit confirmation step FR-08.3 requires.

Two capabilities, one node:

  VIEW     "show pending regularization requests"
           "any regularization requests from A Emp?"
           -> the caller's own direct reports' pending regularizations.

  APPROVE  "approve A Emp's regularization request"
           "approve regularization 55"
           -> a confirmation card on this turn, the write on the NEXT one.

FR-08.3, verbatim: "Any action that changes system state (...manager
approval/override) shall require an explicit user confirmation step before
execution; the assistant shall never execute such an action silently."

This module is arranged the same way leave_approval.py is, so that "executed
silently" is not a reachable state:

  * There is exactly ONE call site for erp_client.approve_regularization, in
    _execute_approval, and the only path into it starts from a stored
    awaiting_confirmation state that a PREVIOUS turn wrote.
  * That state can only be written by _build_confirmation, which returns
    before any write call exists on the path.
  * The confirming turn is matched by explicit patterns, never by an LLM
    judgement. Those patterns are IMPORTED from leave_approval rather than
    restated: "what counts as a manager saying yes" is one rule, and two
    copies of it would drift apart exactly where drift is most expensive.

Team scope — "it will not display other manager's team"
-------------------------------------------------------
Enforced by erp-api, and NOT re-derived here. GET /api/v1/ai/regularizations
resolves the list against the caller's own hierarchy; there is no parameter
that widens it, and this module never sends one. erp-api does NOT narrow the
team list by employee id or name (type=all is always the whole team), so
narrowing to one person is done here, over rows erp-api already scoped — it
can only ever land inside the permitted set.

That leaves one honest gap, and it is deliberate: a manager who names
somebody outside their team is told the request "was not found in your team"
— the same sentence used for a request that exists but is no longer pending.
Identical wording for both is the point. A distinct "that person isn't yours"
would let a manager probe another team's roster one name at a time.

Backing endpoints
-----------------
GET  /api/v1/ai/regularizations?type=all&status=pending  (team list)
POST /api/v1/ai/regularization/approve  ({"regularization_id": N})
POST /api/v1/ai/regularization/reject   ({"regularization_id": N, "rejection_reason": "..."})

Who may act: a Manager, HR user or Admin (erp-api's own rule for both
routes; permission_service.may_view_team here). erp-api still decides WHICH
requests are theirs.

Rejection follows leave_approval's rejection exactly: the confirming reply is
the REASON, not a "yes" — erp-api requires one and the employee reads it, so
it is the one field this flow must never invent. A reason already given in the
instruction ("reject geo3's regularization because the punch exists") is shown
on the card and a plain "yes" submits it.
"""

import json
import logging
import re

from langgraph.types import StreamWriter

import services.access_notice as access_notice
import services.audit_log_service as audit_log_service
import services.erp_client as erp_client
import services.individual_report as individual_report
import services.date_query_resolver as date_query_resolver
import services.leave_slot_service as leave_slot_service
import services.permission_service as permission_service
from services.individual_report import MANAGER_UNKNOWN, _match_selection
from services.nlp_service import fold_regularization_typos
from services.regularisation_guards import TEAM_REGULARISATION_VIEW_NOT_ALLOWED_MESSAGE
from services.regularisation_display import (
    action_time_display, approver_actions, date_range_display, enrich_rows, time_12h,
)
from services.leave_approval import (
    _is_affirmative,
    _is_declining,
    _is_question,
    mentions_action,
    names_a_target,
)

logger = logging.getLogger(__name__)

VIEW_INTENT = "manager_regularisation_view"
APPROVAL_INTENT = "manager_regularisation_approval"

ACTION_APPROVE = "approve"
ACTION_REJECT = "reject"

# Discriminator on the shared manager-action card. leave_approval.py and this
# module both store their pending confirmation under leave_slot_service's
# single manager_action key — deliberately, because a conversation awaiting
# two different "yes" answers at once is a worse problem than either feature
# solves. The kind tag is what keeps a bare "yes" resolving against the card
# that is actually showing: each feature's resolver ignores the other's.
CARD_KIND = "regularization"

NOT_A_MANAGER_MESSAGE = (
    "Approving or rejecting regularization requests is available to managers, "
    "HR and admins only - this isn't something I can do for your role."
)

# Asking to SEE the team's (or another employee's) requests, as opposed to
# approving one, is refused in erp-api's own words — see
# regularisation_guards.TEAM_REGULARISATION_VIEW_NOT_ALLOWED_MESSAGE.
VIEW_NOT_ALLOWED_MESSAGE = TEAM_REGULARISATION_VIEW_NOT_ALLOWED_MESSAGE

# erp-api's own wording for anything outside the caller's hierarchy, reused
# for every "that isn't yours to approve" exit so the answer is identical
# whether the request belongs to another team, was already actioned, or never
# existed. See the module docstring: the sameness is the security property.
NOT_IN_YOUR_TEAM_MESSAGE = "Pending regularization request was not found in your team."

BULK_MESSAGE = (
    "I can only approve or reject one regularization request at a time here, and I "
    "haven't changed anything. Tell me which single request to act on - for "
    "example 'approve A Emp's regularization request' - and I'll show you the "
    "details to confirm first."
)

# The design's rule for the rejection reason: "Shared with the employee.
# 10–500 characters." Checked here so a too-short or too-long reason is asked
# again at once, before anything is sent.
_MIN_REJECTION_REASON = 10
_MAX_REJECTION_REASON = 500
REASON_TOO_SHORT_MESSAGE = ("Please enter a rejection reason (minimum 10 characters) - the "
                            "employee sees it. Reply with the reason, or 'no' to leave the "
                            "request pending.")
REASON_TOO_LONG_MESSAGE = ("That reason is too long - please keep it to 500 characters. Reply "
                           "with a shorter reason, or 'no' to leave the request pending.")
# "edit reason" / "change the reason" at the "Confirm rejection" step.
_EDIT_REASON_RE = re.compile(r"^\s*(?:edit|change|update|modify)\s+(?:the\s+)?reason\b", re.IGNORECASE)

LIST_UNAVAILABLE_MESSAGE = ("Couldn't load pending requests - the approvals service didn't "
                            "respond. No request has been changed. You can try again, or open "
                            "the Approvals page.")

# Sent with every "the service didn't respond" outcome, so the client can offer
# "Try again" and "Open Approvals page" (design: list or action service down).
_SERVICE_DOWN_DATA = {"retry_available": True, "fallback_page": "approvals", "changed": False}

# "reject geo3's regularization because the punch exists" / "... due to ..." /
# "... reason: ..." - a reason given with the instruction itself.
_INLINE_REASON_RE = re.compile(
    r"\b(?:because(?:\s+of)?|since|due\s+to|reason\s*(?:is|was|being|:|-)|as\s+the)\s+(?P<r>.+?)\s*[.!]*\s*$",
    re.IGNORECASE)


def _inline_rejection_reason(query: str):
    match = _INLINE_REASON_RE.search(query or "")
    if not match:
        return None
    reason = match.group("r").strip()
    return reason if _reason_problem(reason) is None else None


def _reason_problem(reason: str):
    """The message to ask again with, or None when the reason is usable."""
    length = len((reason or "").strip())
    if length < _MIN_REJECTION_REASON:
        return REASON_TOO_SHORT_MESSAGE
    if length > _MAX_REJECTION_REASON:
        return REASON_TOO_LONG_MESSAGE
    return None

_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."
_ACCESS_TIMEOUT_MESSAGE = "I couldn't verify your access in time - please try again in a moment."

# A Laravel VALIDATOR complaint, as opposed to a business rule. "The browser id
# field is required." is a bug in THIS service's request, not an answer a
# manager can act on, and reading it back to them is both confusing and a small
# leak of erp-api's request shape. Business refusals ("Attendance is locked for
# this date. Contact HR.") must never match this.
_VALIDATION_MESSAGE = re.compile(
    r"^\s*the\s+.+?\bfield\b.*?\b(is required|must|may not|has already)\b",
    re.IGNORECASE,
)

_MALFORMED_REQUEST_MESSAGE = (
    "I couldn't complete that approval - the HR system rejected the request. "
    "Please approve it in the HR portal instead."
)


_RATE_LIMITED_MESSAGE = ("The HR system is busy right now (too many requests) - please try "
                         "again in a minute. Nothing has been changed.")


def _erp_failure_reply(exc, _finish, action: str):
    """The reply for an approve/reject call that erp-api did not accept.

    ErpApiUnavailable covers more than an outage: any non-2xx the call did not
    opt into lands here - a 403 or 409 with erp-api's own business message, a
    429 from its rate limit. Live, every one of them was answered "I'm unable
    to reach the HR system right now", which blames infrastructure for a
    business rule and invites a retry that cannot succeed. erp-api's message
    is shown when it gave one (4xx), the rate limit is named, and only a real
    outage gets the outage sentence.
    """
    status = getattr(exc, "status_code", None)
    erp_message = getattr(exc, "erp_message", None)
    logger.info("[RegularisationApproval] %s not accepted | status=%s | message=%s",
                action, status, erp_message)
    if isinstance(exc, erp_client.ErpApiUnauthorized):
        return _finish("Sorry, your session has expired — please log in again to continue. "
                       "Nothing has been changed.",
                       finish_intent="regularisation_approval_unavailable",
                       extra_data={"changed": False, "http_status": 401})
    if status == 429:
        return _finish(_RATE_LIMITED_MESSAGE, finish_intent="regularisation_approval_unavailable",
                       extra_data={**_SERVICE_DOWN_DATA, "http_status": 429})
    if status and 400 <= status < 500 and erp_message:
        return _finish(_refusal_sentence(erp_message, NOT_IN_YOUR_TEAM_MESSAGE),
                       finish_intent="regularisation_approval_failed",
                       extra_data={"changed": False, "http_status": status})
    return _finish(_ERP_UNAVAILABLE_MESSAGE, finish_intent="regularisation_approval_unavailable",
                   extra_data=dict(_SERVICE_DOWN_DATA))


def _refusal_sentence(erp_message: str | None, fallback: str) -> str:
    """erp-api's own refusal, punctuated so it reads as its own sentence.

    The rule it enforced is written for a form field and arrives without a
    full stop ("Cannot approve this as leave count exceed remaining leave for
    this user"), so appending the reassurance produced one run-on sentence:
    "...for this user Nothing has been changed." The manager's answer is
    erp-api's wording verbatim - only the terminator is added.

    The one message NOT passed through is a validator complaint: that says this
    service sent a malformed request, so it is logged for us and the manager is
    told plainly that the approval did not happen.
    """
    raw = (erp_message or "").strip()
    if raw and _VALIDATION_MESSAGE.match(raw):
        logger.error(
            "[Approval] erp-api rejected the request as INVALID, not refused: %r. "
            "This is a malformed request from this service, not a business rule.",
            raw,
        )
        raw = _MALFORMED_REQUEST_MESSAGE

    text = raw or fallback.strip()
    if text and text[-1] not in ".!?":
        text += "."
    return f"{text} Nothing has been changed."


# How many rows a chat reply lists before saying "and N more". erp-api returns
# the whole pending list unpaginated, so the cap is ours to apply - same
# treatment, and the same number, as team_leave_query_node uses for leaves.
_LIST_LIMIT = 3

# An explicit request id: "regularization 55", "request #55", "id 55".
# Deliberately NOT a bare number - "approve 2" is far more likely to mean
# "the second one" than "regularization id 2", and acting on that guess
# approves an arbitrary stranger's record.
_REQUEST_ID_PATTERNS = (
    # The reference the cards now show ("REG-22", see regularisation_display).
    re.compile(r"\bREG[\s-]*(\d+)\b", re.IGNORECASE),
    # "reject ref-20644" - this node only runs for regularization, so a REF
    # here is a regularization reference too.
    re.compile(r"\bREF[\s-]*(\d+)\b", re.IGNORECASE),
    re.compile(r"\bregulari[sz]ation\s*(?:request\s*)?#?\s*(\d+)\b", re.IGNORECASE),
    re.compile(r"\brequest\s*(?:id\s*)?#?\s*(\d+)\b", re.IGNORECASE),
    re.compile(r"\bid\s*#?\s*(\d+)\b", re.IGNORECASE),
    re.compile(r"#(\d+)\b"),
)

# "approve BOTH of them", "approve all the pending ones" - out of scope, and
# refused by name rather than by quietly approving the first.
_BULK_PATTERNS = (
    re.compile(r"\b(all|both|every|everything)\b", re.IGNORECASE),
    re.compile(r"\bthese\s+(?:two|three|\d+)\b", re.IGNORECASE),
    re.compile(r"\bmultiple\b", re.IGNORECASE),
)

_REJECT_PATTERNS = (
    re.compile(r"\b(reject|deny|decline|refuse)\b", re.IGNORECASE),
)

# Possessive or "for X" phrasing that names whose request this is. Used only
# after the action verb has already been recognised, so it does not have to
# defend against questions.
_EMPLOYEE_NAME_PATTERNS = (
    re.compile(r"\bfor\s+([A-Za-z][\w.'-]*(?:\s+[A-Za-z][\w.'-]*)?)\b", re.IGNORECASE),
    re.compile(r"\bof\s+([A-Za-z][\w.'-]*(?:\s+[A-Za-z][\w.'-]*)?)\b", re.IGNORECASE),
    re.compile(r"\b([A-Za-z][\w.'-]*)(?:'s|s')\s+regulari[sz]ation\b", re.IGNORECASE),
    re.compile(r"\bfrom\s+([A-Za-z][\w.'-]*(?:\s+[A-Za-z][\w.'-]*)?)\b", re.IGNORECASE),
    # "<verb> <someone> regularization(s)" — the shape with no preposition and
    # no possessive, which is how an employee CODE is usually typed:
    # "show geo6 regularization requests". Without it the name was never
    # extracted, employee_id stayed None, and the node answered a question
    # about ONE report with the whole team's list — the same failure the
    # leave route had for "show geo3 pending leaves".
    #
    # The negative lookahead carries the weight: it keeps the team and
    # first-person phrasings ("show my/all/pending/team regularizations")
    # out, so this can only ever capture something that is actually a name.
    re.compile(r"\b(?:show|check|see|get|fetch|display|pull|view|list|give|tell"
               r"|approve|reject|deny|decline)\s+(?:the\s+)?"
               r"(?!my\b|our\b|all\b|any\b|team\b|pending\b|employee\b|employees\b|staff\b)"
               r"([A-Za-z][\w.'-]*(?:\s+[A-Za-z][\w.'-]*)?)\s+"
               r"(?:pending\s+)?regulari[sz]ation", re.IGNORECASE),
)

# "employee 3759" / "emp id 3759" — erp-api's own narrowing parameter, given
# directly. Checked before the name patterns (an explicit id needs no roster
# lookup) and subtracted from the text before request-id extraction, because
# _REQUEST_ID_PATTERNS' own `\bid\s*#?\s*(\d+)\b` would otherwise read
# "employee id 3759" as REGULARIZATION #3759 and approve-flow the wrong row.
_EMPLOYEE_ID_PATTERNS = (
    re.compile(r"\bemployee\s*(?:id|number|no\.?)?\s*#?\s*(\d+)\b", re.IGNORECASE),
    re.compile(r"\bemp\s*(?:id|no\.?)?\s*#?\s*(\d+)\b", re.IGNORECASE),
)

# Words that look like a name to the patterns above but never are. Kept small
# and literal: this list only has to cover the connective tissue of the
# phrasings this node actually sees.
_NAME_STOPWORDS = {
    "me", "my", "the", "a", "an", "this", "that", "these", "those", "it",
    "them", "him", "her", "his", "their", "team", "all", "any", "pending",
    "regularization", "regularisation", "request", "requests", "approval",
    "attendance", "today", "yesterday", "everyone", "everybody", "us", "our",
    # "for employee 3759" captured the literal word as the name, which then
    # matched nobody on the roster. The id itself is picked up by
    # _extract_employee_id instead.
    #
    # "emp" is deliberately NOT here: it is a real name token in this data
    # ("A Emp" is an actual report), and adding it made that employee
    # unreachable by name. "emp 3759" needs no protection anyway —
    # _extract_employee_id resolves the id and the node prefers it over any
    # name.
    "employee", "employees", "staff", "reports", "report", "id", "number",
    # The connective words of "I want to view TO APPLY regularization for my
    # team" / "view WHO APPLY regularization": the "<verb> <someone>
    # regularization" pattern captured them as a name, which matched nobody,
    # and a request for the team list was answered "not found in your team".
    "to", "who", "whom", "whose", "has", "have", "had", "is", "are", "did", "do",
    "apply", "applied", "applying", "applies", "raised", "submitted", "requested",
    "people", "person", "members", "member", "everyone's",
}


def _is_name_word(word: str) -> bool:
    """Not a stopword and not "regularization" misspelt - the node reads the
    raw message, so "who has apply for regulization" offered "regulization"
    as the employee's name."""
    lowered = word.lower()
    if lowered in _NAME_STOPWORDS:
        return False
    return not fold_regularization_typos(lowered).startswith(("regulari", "regularz"))


def _extract_employee_id(query: str):
    """The employee_id named outright, or None. Matched against the rows'
    own employee_id after the fetch (see _same_employee), so no roster
    lookup is needed."""
    for pattern in _EMPLOYEE_ID_PATTERNS:
        match = pattern.search(query or "")
        if match:
            return int(match.group(1))
    return None


# Date-shaped spans, subtracted before a regularization id is looked for.
# "approve regularization 2026-10-02 of ayush jio" otherwise matched
# _REQUEST_ID_PATTERNS' own `regularization\s*(\d+)` and armed a confirmation
# for REQUEST #2026 — a number the manager never typed, taken from the year.
_DATE_SPAN_PATTERNS = (
    re.compile(r"\b\d{4}-\d{1,2}-\d{1,2}\b"),
    re.compile(r"\b\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b"),
    re.compile(r"\b\d{1,2}\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?"
               r"(?:\s*,?\s*\d{4})?\b", re.IGNORECASE),
    re.compile(r"\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?\s+\d{1,2}"
               r"(?:\s*,?\s*\d{4})?\b", re.IGNORECASE),
)


_CLOCK_TIME_RE = re.compile(
    r"\b\d{1,2}[:.]\d{2}(?::\d{2})?\s*(?:a\.?m\.?|p\.?m\.?)?(?![\w-])"
    r"|\b\d{1,2}\s*(?:a\.?m\.?|p\.?m\.?)(?![a-z])", re.IGNORECASE)


_CLOCK_RANGE_RE = re.compile(
    r"(?:\bfrom\s+)?(?:" + _CLOCK_TIME_RE.pattern + r")\s*(?:to|till|until|-|–|—)\s*"
    r"(?:" + _CLOCK_TIME_RE.pattern + r")", re.IGNORECASE)


def _strip_date_spans(text: str) -> str:
    for pattern in _DATE_SPAN_PATTERNS:
        text = pattern.sub(" ", text)
    return text


def _extract_apply_date(query: str, today=None):
    """The apply_date the manager named ("2026-10-02", "2 october 2026",
    "yesterday"), as an ISO string, or None.

    Deterministic, via date_query_resolver — the same parser the leave and
    attendance flows use, so "11 aug" means the same day here as there. Only
    a SINGLE resolved date counts: a range names no one request, and the
    resolver returning None (e.g. "approve regularization 56") must stay
    None rather than becoming today.
    """
    # Clock times out first: "2026-10-03 9:30 to 18:30" and "07-Oct-2026
    # (09:30 - 18:30)" - a manager quoting the row's times - otherwise read
    # as a range, or as an invalid date, and the named day was lost.
    # The whole span first, or its "to" is left to read as a date range.
    text = _CLOCK_RANGE_RE.sub(" ", query or "")
    text = _CLOCK_TIME_RE.sub(" ", text)
    resolved = date_query_resolver.resolve(text, today or individual_report._today_in_app_timezone())
    # The resolver can also hand back an InvalidExplicitDate marker.
    if not isinstance(resolved, dict) or resolved.get("type") != "single":
        return None
    value = resolved.get("date")
    return value.isoformat() if value else None


def _extract_request_id(query: str):
    # An employee reference and any date are subtracted first so their digits
    # cannot be read as a regularization id — see the two pattern groups'
    # own comments.
    text = _strip_date_spans(query or "")
    for pattern in _EMPLOYEE_ID_PATTERNS:
        text = pattern.sub(" ", text)
    for pattern in _REQUEST_ID_PATTERNS:
        match = pattern.search(text)
        if match:
            return int(match.group(1))
    return None


def _extract_employee_name(query: str):
    for pattern in _EMPLOYEE_NAME_PATTERNS:
        match = pattern.search(query or "")
        if not match:
            continue
        candidate = (match.group(1) or "").strip()
        # A two-word capture whose first word is a stopword ("for the team")
        # is not a name; a single stopword never is.
        words = [w for w in candidate.split() if _is_name_word(w)]
        if words:
            return " ".join(words)
    return None


# A day of the month on its own - "accept for 7", "reject the 3rd" - read
# against the dates on the manager's own list. Needs a preposition or an
# ordinal suffix: a bare "approve 2" stays "the second one" (see
# _REQUEST_ID_PATTERNS), and times / durations are not days.
_DAY_OF_MONTH_RE = re.compile(
    r"\b(?:for|on|of|dated|date)\s+(?:the\s+)?(\d{1,2})(?:st|nd|rd|th)?\b"
    r"(?!\s*(?:[:.]\d|am\b|pm\b|days?\b|hours?\b|hrs?\b|requests?\b|ones?\b))"
    r"|\b(\d{1,2})(?:st|nd|rd|th)\b(?!\s+(?:one|request)\b)",
    re.IGNORECASE)


def _extract_day_of_month(query: str):
    match = _DAY_OF_MONTH_RE.search(query or "")
    if not match:
        return None
    day = int(match.group(1) or match.group(2))
    return day if 1 <= day <= 31 else None


def _day_of(apply_date):
    match = re.match(r"^\d{4}-\d{2}-(\d{2})", str(apply_date or ""))
    return int(match.group(1)) if match else None


# Approve-family and reject-family words, for telling one instruction from two.
_APPROVE_WORD_RE = re.compile(
    r"\b(?:approve|approving|aprove|apporve|aprrove|accept|accepting|acept|accpet|acceprt)\b",
    re.IGNORECASE)
_ANY_ACTION_WORD_RE = re.compile(
    _APPROVE_WORD_RE.pattern[:-3] + r"|reject|rejecting|rejct|deny|decline|refuse)\b",
    re.IGNORECASE)


def _split_mixed_instruction(query: str):
    """(first_instruction, the_rest) when one message both approves and
    rejects - "Approve for 7 reject for 3" - else (query, None).

    One request is confirmed at a time (FR-08.3), so the first instruction is
    carried out and the rest is handed back to the manager to send next. Live,
    the whole message re-showed the list and acted on neither."""
    words = list(_ANY_ACTION_WORD_RE.finditer(query or ""))
    if len(words) < 2:
        return query, None
    first_is_approve = bool(_APPROVE_WORD_RE.fullmatch(words[0].group(0)))
    for word in words[1:]:
        # "reject it, do not approve" is one instruction, not two.
        if re.search(r"\b(?:not|don'?t|never|no)\s*$", query[:word.start()], re.IGNORECASE):
            continue
        if bool(_APPROVE_WORD_RE.fullmatch(word.group(0))) != first_is_approve:
            head = re.sub(r"[\s,;&]*(?:\band\b|\bthen\b)?[\s,;&]*$", "", query[:word.start()],
                          flags=re.IGNORECASE)
            rest = query[word.start():].strip()
            if head.strip() and rest:
                return head.strip(), rest
            break
    return query, None


# The turns of the manager's review (the list, "which one?", a card, a
# refusal, a success) - after these a bare name or reference means one of
# THESE requests. classify_node routes on the same prefixes.
REVIEW_CONTEXT_PREFIXES = ("manager_regularisation", "regularisation_approval",
                           "regularisation_rejection")

_BARE_NAME_REPLY_RE = re.compile(r"^\s*[A-Za-z][\w.'-]*(?:\s+[A-Za-z][\w.'-]*){0,2}\s*[.!]*\s*$")
_POSITION_WORD_RE = re.compile(
    r"\b(?:first|second|third|fourth|fifth|last|latest|oldest|newest|one|two|three|top|"
    r"bottom|above|below|it|this|that)\b", re.IGNORECASE)


def is_bulk_request(query: str) -> bool:
    return any(p.search(query or "") for p in _BULK_PATTERNS)


def mentions_rejection(query: str) -> bool:
    return any(p.search(query or "") for p in _REJECT_PATTERNS)


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


def _time_span(row: dict) -> str:
    """"09:00 to 18:30", trimmed of the seconds erp-api sends. Falls back to
    whatever is present rather than inventing the missing half - a card that
    silently shows one time as both is worse than one that shows a dash."""
    def _hhmm(value):
        text = str(value or "").strip()
        if not text:
            return ""
        parts = text.split(":")
        return f"{parts[0]}:{parts[1]}" if len(parts) >= 2 else text

    start = _hhmm(row.get("from_time"))
    end = _hhmm(row.get("to_time"))
    if start and end:
        return f"{start} to {end}"
    return start or end or "-"


def _employee_label(row: dict, default: str = "That team member") -> str:
    return (row.get("employee_name") or row.get("employee_number") or default)


def _confirmation_card(row: dict, action: str = ACTION_APPROVE,
                       rejection_reason: str | None = None) -> dict:
    """The summary a manager confirms against. Every field is copied from
    erp-api's row - nothing is computed, defaulted to a plausible-looking
    value, or carried over from a previous card. rejection_reason is the
    manager's own words, only when they gave one with the instruction."""
    return {
        "request_type": "Regularization",
        "action": action,
        "reference_id": row.get("reference_id")
        or (f"REG-{row['regularization_id']}" if row.get("regularization_id") is not None else None),
        "rejection_reason": rejection_reason,
        "regularization_id": row.get("regularization_id"),
        "employee_id": row.get("employee_id"),
        "employee_number": row.get("employee_number"),
        "employee_name": row.get("employee_name"),
        "apply_date": row.get("apply_date"),
        "from_time": row.get("from_time"),
        "to_time": row.get("to_time"),
        "time_span": _time_span(row),
        "reason": row.get("reason"),
        "status_name": row.get("status_name"),
        # The design's card fields (Applied by, Date from-to, Regularization
        # type, In-time, Out-time, Applied on), all from erp-api's row via
        # regularisation_display.enrich_row.
        "applied_by": row.get("employee_name") or row.get("applied_by"),
        "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),
        "regularization_type": row.get("regularization_type"),
        "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"),
        "status_label": row.get("card_status_label") or row.get("status_label"),
    }


def _card_lines(card: dict) -> list:
    return [
        f"- Applied by: {card.get('applied_by') or card.get('employee_name') or '-'}",
        f"- Reference: {card.get('reference_id') or card.get('regularization_id')}",
        f"- Date: {card.get('date_range_display') or card.get('apply_date') or '-'}",
        f"- Regularization type: {card.get('regularization_type') or '-'}",
        f"- In-time: {card.get('in_time_display') or '-'}",
        f"- Out-time: {card.get('out_time_display') or '-'}",
        f"- Reason: {card.get('reason') or '-'}",
        f"- Applied on: {card.get('applied_on_display') or '-'}",
    ]


def _render_confirmation(card: dict) -> str:
    is_reject = card.get("action") == ACTION_REJECT
    if is_reject and card.get("rejection_reason"):
        return _render_reject_confirmation(card)
    lines = [f"{'Reject' if is_reject else 'Approve'} this request?"] + _card_lines(card) + [""]
    if is_reject:
        # The ask is for a REASON, not a yes/no - erp-api records it and the
        # employee sees it, so it is the one field this flow must not invent.
        lines.append("Rejection reason: tell the employee why this request is being "
                     "rejected (10-500 characters - they'll see it). Reply 'no' to leave "
                     "it pending.")
    else:
        lines.append("The employee will be notified once you confirm. Reply 'yes' to "
                     "confirm the approval, or 'no' to leave it pending.")
    return "\n".join(lines)


#: A message that is a new request or a question, never a rejection reason:
#: it ends in "?", or opens with a request verb or question word. Deliberately
#: without can/could/is/should at the start - "Could not verify the punch" is
#: a perfectly good reason.
_NEW_REQUEST_RE = re.compile(
    r"\?\s*$"
    r"|^\s*(?:please\s+)?(?:show|list|view|display|open|fetch|get|give\s+me|tell\s+me|"
    r"apply|approve|reject|cancel|regulari[sz]e|what|what's|whats|how|when|where|which|who|"
    r"i\s+want\s+to|i\s+need\s+to)\b",
    re.IGNORECASE)


def _is_new_request(query: str) -> bool:
    return bool(_NEW_REQUEST_RE.search((query or "").strip()))


#: The reject card's "Back to list" button, typed or pressed.
BACK_TO_LIST = "back_to_list"
_BACK_TO_LIST_RE = re.compile(
    r"^\s*(?:go\s+)?back(?:\s+to\s+(?:the\s+)?(?:list|requests?))?\s*[.!]*\s*$", re.IGNORECASE)
_CARD_ACTION_WORDS = {
    "back": BACK_TO_LIST, "back_to_list": BACK_TO_LIST, "list": BACK_TO_LIST,
    "confirm": "yes", "yes": "yes", "confirm_rejection": "yes", "confirm_approval": "yes",
    "no": "no", "keep": "no", "keep_pending": "no", "leave_pending": "no",
    "edit_reason": "edit reason",
}


def _card_reply(query: str, pending: dict):
    """What a reply to the open approve/reject card SAYS, in plain words.

    The card's Continue button may send the reason alone, the reason with the
    request's reference ("REG-149 - the punch records ..."), or the card's
    JSON ({"rejection_reason": ...} / {"reason": ...}, with or without the
    id). Live, each of those went to erp-api verbatim - the JSON itself, or
    "REG-149 - ...", saved as the reason the employee reads - and "Back to
    list" was saved as a reason and then rejected the request on "yes".

    Returns BACK_TO_LIST, the plain text to read instead of the message, or
    None when the message is to be read as it is. A reference to a DIFFERENT
    request comes back as "reject REG-n because ..." so the re-aim path
    handles it.
    """
    text = (query or "").strip()
    own_id = str((pending or {}).get("regularization_id") or "")
    if text.startswith("{"):
        try:
            parsed = json.loads(text)
        except ValueError:
            parsed = None
        if isinstance(parsed, dict):
            action = str(parsed.get("action") or "").strip().lower().replace(" ", "_")
            reason = str(parsed.get("rejection_reason") or parsed.get("reason") or "").strip()
            target = parsed.get("regularization_id") or parsed.get("id") or parsed.get("reference_id")
            target_id = re.sub(r"\D", "", str(target or ""))
            if action in _CARD_ACTION_WORDS and not reason:
                return _CARD_ACTION_WORDS[action]
            if target_id and own_id and target_id != own_id:
                verb = "approve" if action == ACTION_APPROVE else "reject"
                return f"{verb} REG-{target_id}" + (f" because {reason}" if reason else "")
            if reason:
                return reason
            return None
    if _BACK_TO_LIST_RE.match(text):
        return BACK_TO_LIST
    m = re.match(r"^\s*(?:reject\s+)?REG[\s-]*(\d+)\s*(?:[-:,–—]+|because\b|reason\s*[:-]?)\s*(.+)$",
                 text, re.IGNORECASE | re.DOTALL)
    if m and own_id and m.group(1) == own_id:
        return m.group(2).strip()
    return None


def _render_reject_confirmation(card: dict) -> str:
    """The design's "Confirm rejection" step: the reason repeated back before
    anything is sent."""
    who = card.get("applied_by") or card.get("employee_name") or "this employee"
    day = (card.get("date_range_display") or "").split(" – ")[0]
    return (f"Reject {card.get('reference_id')} from {who}{f' for {day}' if day else ''}?\n"
            f"Reason: {card.get('rejection_reason')}\n"
            "The employee will see this reason.\n\n"
            "Reply 'yes' to confirm the rejection, 'edit reason' to change it, or 'no' to "
            "leave it pending.")


def _render_row(row: dict) -> str:
    ref = row.get("reference_id") or f"REG-{row.get('regularization_id')}"
    return (
        f"{_employee_label(row)}: {row.get('apply_date') or '-'}, "
        f"{_time_span(row)} - {row.get('reason') or 'no reason given'} "
        f"({ref})"
    )


def _render_list(rows: list, employee_label: str | None = None) -> str:
    shown = rows[:_LIST_LIMIT]
    whose = f"{employee_label}'s" if employee_label else "your team's"
    header = f"Here are {whose} pending regularization requests:"
    body = "\n".join(_render_row(r) for r in shown)
    if len(rows) > _LIST_LIMIT:
        body += f"\n({len(rows) - _LIST_LIMIT} more pending request(s) not shown)"
    return (f"{header}\n{body}\n\nTell me which one to approve or reject and I'll show you "
            "the details to confirm.")


def _render_choice(rows: list, action: str = ACTION_APPROVE) -> str:
    lines = "\n".join(_render_row(r) for r in rows[:_LIST_LIMIT])
    more = ""
    if len(rows) > _LIST_LIMIT:
        more = f"\n({len(rows) - _LIST_LIMIT} more not shown)"
    first = (rows or [{}])[0]
    ref = first.get("reference_id") or (
        f"REG-{first.get('regularization_id')}" if first.get("regularization_id") else "REG-123")
    return (
        "There's more than one pending regularization request here, so I "
        f"haven't changed anything. Which one should I {action}?\n"
        f"{lines}{more}\n\n"
        f"Tell me the date (e.g. {first.get('apply_date') or '7 Oct'}), the reference "
        f"(e.g. {ref}), or the team member's name."
    )


# -- Pending-card resolution (classify_node's single entry point) -------------


def is_waiting_for_rejection_reason(company_id, conversation_id: str) -> bool:
    """A regularization reject card is on screen asking for its reason."""
    state = leave_slot_service.get_manager_action(company_id, conversation_id) or {}
    return state.get("kind") == CARD_KIND and state.get("step") == "awaiting_rejection_reason"


def resolve_pending_regularisation_intent(company_id, conversation_id: str, query: str):
    """APPROVAL_INTENT when this turn answers a regularization confirmation
    this conversation is already waiting on - otherwise None.

    Mirrors leave_approval.resolve_pending_approval_intent, and is
    deliberately blind to a card of any other kind: the two features share
    one manager-action key, so without the kind check a "yes" aimed at a
    leave card would be handled here (and vice versa), approving something
    the manager never saw.
    """
    state = leave_slot_service.get_manager_action(company_id, conversation_id) or {}
    if state.get("kind") != CARD_KIND:
        return None
    reply = _card_reply(query, state)
    if reply == BACK_TO_LIST:
        return APPROVAL_INTENT   # the node drops the card and shows the list
    if reply:
        query = reply
    if state.get("step") == "awaiting_rejection_reason":
        # The whole message is the reason, so almost anything belongs here -
        # but NOT a question and NOT a re-aim at another request, exactly as
        # leave_approval treats its own reason turn. A decline lands here so
        # the node can clear the card and say nothing changed.
        if _is_declining(query):
            return APPROVAL_INTENT
        if names_a_target(query) and mentions_action(query):
            # "reject REG-150 instead" - a re-aim, handled by the node.
            return APPROVAL_INTENT
        if _is_new_request(query):
            # "Show my team regularisation" is not a reason. The card is
            # dropped so a later message cannot become its reason either, and
            # the request is routed as what it is.
            leave_slot_service.clear_manager_action(company_id, conversation_id)
            return None
        # Not _is_question: it reads any message OPENING with "could" / "is"
        # as a question, and "Could not verify the punch records" is a reason.
        # Real questions ("...?", "what ...") were dropped just above.
        if names_a_target(query):
            return None
        return APPROVAL_INTENT if query.strip() else None
    if state.get("step") != "awaiting_confirmation":
        return None
    if _is_affirmative(query) or _is_declining(query):
        return APPROVAL_INTENT
    if state.get("action") == ACTION_REJECT and _EDIT_REASON_RE.match(query or ""):
        return APPROVAL_INTENT
    # A re-aimed instruction ("approve Ayush's instead", "make it 18") belongs
    # here; a QUESTION using the same verb does not - it gets a normal answer
    # and the card keeps waiting.
    if (mentions_action(query) or names_a_target(query)) and not _is_question(query):
        return APPROVAL_INTENT
    return None


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


async def regularisation_approval_node(state: dict, writer: StreamWriter) -> dict:
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    query = state.get("query", "")
    intent = state.get("intent") or APPROVAL_INTENT
    usage_events = list(state.get("usage_events", []))

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

    def _refuse(message: str, finish_intent: str = None, extra_data: dict = None) -> dict:
        """Every "I'm not doing that" exit clears any pending confirmation on
        the way out - leaving a stale card alive after refusing a different
        instruction is how a later bare "yes" approves something the manager
        had already moved on from. Clears unconditionally, a leave card
        included: after a refusal the safe state is "nothing is armed", and
        keeping another feature's card alive across one is how a later "yes"
        lands on something the manager has stopped looking at."""
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        return _finish(message, finish_intent=finish_intent, extra_data=extra_data)

    # -- Gate: is the caller a manager? --------------------------------------
    # Same tri-state contract as leave_approval_node, resolved by
    # hr_graph.manager_gate_node ahead of classification. The fallback is not
    # dead code: this node stays callable on its own, and a permission gate
    # that passes when its input is missing is the wrong failure mode.
    resolved = state.get("is_manager")
    context_data = None
    if resolved is None and not state.get("is_manager_jwt"):
        try:
            context_result = await erp_client.get_leave_context(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
            )
        except erp_client.ErpApiTimeout:
            return _finish(_ACCESS_TIMEOUT_MESSAGE)
        except erp_client.ErpApiUnavailable:
            return _finish(_ERP_UNAVAILABLE_MESSAGE)
        context_data = context_result["body"].get("data") or {}
        resolved = context_data.get("is_manager", False)
    elif resolved is None:
        resolved = True

    # An HR user and an admin may see AND act on regularization requests on
    # the same footing as a manager: erp-api's approve and reject routes are
    # "Managers, HR, and Admin roles only" (services/permission_service).
    # erp-api still decides which requests are theirs.
    if resolved is not True:
        _access = permission_service.may_view_team(state, context_data=context_data)
        if _access is True:
            resolved = True
            logger.info("[RegularisationApproval] allowed as an HR/admin caller")
        elif _access == permission_service.ACCESS_UNKNOWN:
            resolved = MANAGER_UNKNOWN

    if resolved == MANAGER_UNKNOWN:
        return _finish(_ACCESS_TIMEOUT_MESSAGE)
    if not resolved:
        refusal = VIEW_NOT_ALLOWED_MESSAGE if intent == VIEW_INTENT else NOT_A_MANAGER_MESSAGE
        return _refuse(refusal, finish_intent=access_notice.RESTRICTED_INTENT,
                       extra_data=access_notice.refuse(writer, "regularisation_approval", refusal))

    pending = leave_slot_service.get_manager_action(company_id, conversation_id) or {}
    if pending.get("kind") != CARD_KIND:
        pending = {}
    elif intent == VIEW_INTENT:
        # Routed here as a LIST request ("refresh the list", "show team
        # regularizations") - never the open card's reply, which classify
        # sends as APPROVAL_INTENT. At the reason step the message would
        # otherwise be saved as the rejection reason. The card is dropped:
        # after showing the list, nothing is armed.
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        pending = {}

    def _left_pending():
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        card = pending.get("card") or {}
        whose = f"{card['employee_name']}'s" if card.get("employee_name") else "that"
        return _finish(
            f"No problem - I've left {whose} regularization request pending. "
            "Nothing has been changed."
        )

    # -- The rejection REASON turn (FR-08.3) --------------------------------
    # Armed by a reject card with no reason yet. A decline still wins; a
    # re-aim at another request falls through to be read as a fresh
    # instruction. A usable reason (10-500 characters) is NOT sent yet: the
    # design repeats it back on a "Confirm rejection" step first.
    # What the card's buttons sent, in plain words - see _card_reply.
    if pending.get("step") in ("awaiting_rejection_reason", "awaiting_confirmation"):
        reply = _card_reply(query, pending)
        if reply == BACK_TO_LIST:
            logger.info("[RegularisationApproval] back to list - dropping the card")
            leave_slot_service.clear_manager_action(company_id, conversation_id)
            pending = {}
            intent = VIEW_INTENT
            query = "show team regularization requests"
        elif reply:
            query = reply

    if pending.get("step") == "awaiting_rejection_reason":
        if _is_declining(query) and not names_a_target(query):
            return _left_pending()
        if _is_new_request(query):
            # Live: at the reason prompt the manager typed "Show my team
            # regularisation" again, and it became the rejection reason
            # ("Reason: Show my team regularisation"). A new request is never
            # a reason: the reject card is dropped and the message is read as
            # the request it is.
            logger.info("[RegularisationApproval] new request at the reason prompt - "
                        "dropping the reject card")
            leave_slot_service.clear_manager_action(company_id, conversation_id)
            pending = {}
            if not mentions_action(query):
                # Routed here only because the card was open: a list request
                # gets the list, not a fresh approve card.
                intent = VIEW_INTENT
        elif not names_a_target(query):
            reason = query.strip()
            problem = _reason_problem(reason)
            if problem:
                return _finish(problem, finish_intent="regularisation_rejection_reason_invalid",
                               extra_data={"field_error": problem, "changed": False})
            card = {**(pending.get("card") or {}), "rejection_reason": reason}
            leave_slot_service.set_manager_action(company_id, conversation_id, {
                **pending, "step": "awaiting_confirmation", "card": card})
            writer({"type": "regularisation_approval_confirmation", "data": card})
            return _finish(_render_reject_confirmation(card),
                           finish_intent="regularisation_rejection_confirmation",
                           extra_data=card)

    # -- The confirming turn (FR-08.3) --------------------------------------
    if pending.get("step") == "awaiting_confirmation":
        if _is_declining(query) and not names_a_target(query):
            return _left_pending()
        if pending.get("action") == ACTION_REJECT and _EDIT_REASON_RE.match(query or ""):
            # "Edit reason": back to asking for it; nothing has been sent.
            card = {**(pending.get("card") or {}), "rejection_reason": None}
            leave_slot_service.set_manager_action(company_id, conversation_id, {
                **pending, "step": "awaiting_rejection_reason", "card": card})
            return _finish("Sure - what's the reason for rejecting it? (10-500 characters, the "
                           "employee will see it.) Reply 'no' to leave it pending.",
                           finish_intent="regularisation_approval_confirmation", extra_data=card)
        if _is_affirmative(query):
            if pending.get("action") == ACTION_REJECT:
                # A reject card that already carries the manager's reason.
                return await _execute_rejection(
                    pending, (pending.get("card") or {}).get("rejection_reason") or "",
                    bearer_token, company_id, conversation_id, writer, _finish,
                )
            return await _execute_approval(
                pending, query, bearer_token, company_id, conversation_id, writer, _finish,
            )
        # Anything else that reached this node with a card showing is a
        # RE-AIM ("approve Ayush's instead"): fall through and read it as a
        # fresh instruction. The old card is replaced, never silently kept.

    # "Approve for 7 reject for 3": the first instruction now, the rest handed
    # back for the next turn - see _split_mixed_instruction.
    query, next_instruction = _split_mixed_instruction(query)
    if next_instruction:
        _plain_finish = _finish

        def _finish(message, finish_intent=None, extra_data=None):
            return _plain_finish(
                f"{message}\n\nAfter this one, send \"{next_instruction}\" and I'll take "
                "that request next - I confirm one at a time.",
                finish_intent=finish_intent, extra_data=extra_data)

    last_intent = str(state.get("last_intent") or "").lower()
    answering_choice = last_intent in ("regularisation_approval_choice",
                                       "regularisation_rejection_choice")
    reviewing = last_intent.startswith(REVIEW_CONTEXT_PREFIXES)
    wants_approval = intent == APPROVAL_INTENT
    action = ACTION_REJECT if mentions_rejection(query) else ACTION_APPROVE
    # "REG-20645" / "7 oct" in answer to "Which one should I reject?" carries
    # no verb of its own; the question it answers decides.
    if (answering_choice and last_intent.startswith("regularisation_rejection")
            and not _ANY_ACTION_WORD_RE.search(query)):
        action = ACTION_REJECT
    if action == ACTION_REJECT:
        wants_approval = True

    if wants_approval and is_bulk_request(query):
        return _refuse(BULK_MESSAGE, finish_intent="regularisation_approval_bulk")

    # A reason given with a reject instruction is the manager's own words for
    # the card. It is cut out before the target is read, so "because of a fake
    # punch on 2 oct" can't be read as an employee called "a fake" or a date.
    inline_reason = _inline_rejection_reason(query) if action == ACTION_REJECT else None
    target_text = query
    if inline_reason:
        target_text = _INLINE_REASON_RE.sub(" ", query).strip()

    employee_name = _extract_employee_name(target_text)
    request_id = _extract_request_id(target_text)
    # "approve <someone>'s regularization for 2 October" — the manager knows
    # the DAY that was wrong, not the internal id erp-api files it under.
    apply_date = _extract_apply_date(target_text)
    # "accept for 7" - a day of the month, matched against the list's own dates.
    apply_day = (_extract_day_of_month(target_text)
                 if apply_date is None and request_id is None else None)

    # -- Fetch the caller's own team's pending regularizations ---------------
    # An id given outright narrows the rows erp-api returns (see the
    # _same_employee filter below) — erp-api itself ignores it. Scope is
    # unchanged either way: erp-api answers within the CALLER's own
    # hierarchy, so an id outside it matches no row.
    employee_id = _extract_employee_id(target_text)
    matched_employee = None
    # A NAME is resolved after the fetch instead, against the rows erp-api
    # returns — see _resolve_employee_from_rows below. The roster endpoint
    # this used to call (/api/v1/ai/leave/team/members) answers 404 on the
    # deployed erp-api, so every by-name lookup died as "I'm unable to reach
    # the HR system" before it ever reached the list it was asking about.
    # The regularization rows already carry employee_number and
    # employee_name, so the team list is the roster for this purpose and
    # needs no second call.

    writer({"type": "fetching_regularizations",
            "message": "Checking pending regularization requests..."})
    try:
        result = await erp_client.get_pending_regularizations(
            bearer_token, employee_id=employee_id,
            company_id=company_id, conversation_id=conversation_id,
        )
    except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable):
        # Design: "Couldn't load pending requests" with Try again / Open
        # Approvals page.
        return _finish(LIST_UNAVAILABLE_MESSAGE, finish_intent="regularisation_approval_unavailable",
                       extra_data=dict(_SERVICE_DOWN_DATA))

    # erp-api's own scope gate. A caller who manages nobody is refused there
    # rather than shown an empty list, and a role change between the gate
    # above and this call lands here too. erp-api's own sentence ("Only
    # Manager/HR users can view team regularization requests.") is the reply;
    # the constant is only for a 403 that arrives without one.
    if result.get("http_status") == 403:
        refusal = (erp_client.extract_erp_message(result.get("body"))
                   or VIEW_NOT_ALLOWED_MESSAGE)
        return _refuse(refusal, finish_intent=access_notice.RESTRICTED_INTENT,
                       extra_data=access_notice.refuse(writer, "regularisation_approval", refusal))

    body = result.get("body") or {}
    # erp-api refuses type=all for a non-Manager/HR caller with
    # {"success": false, "message": "Only Manager/HR users can view team
    # regularization requests."} — and not necessarily as a 403, so the
    # status code above can't be relied on to catch it. On this route (a
    # fixed GET, nothing to validate) success:false is that refusal, and it
    # gets the same restricted intent and "Not available" card as the 403.
    if not body.get("success", True):
        refusal = erp_client.extract_erp_message(body) or VIEW_NOT_ALLOWED_MESSAGE
        return _refuse(refusal, finish_intent=access_notice.RESTRICTED_INTENT,
                       extra_data=access_notice.refuse(writer, "regularisation_approval", refusal))

    data = body.get("data") or {}
    rows = data.get("regularizations") or []
    # The whole team queue, before any narrowing - for the success card's
    # "N requests are still waiting for you".
    team_pending_total = data.get("total_pending_regularizations") or len(rows)

    # Resolve a NAME (or employee code) against the rows just returned. The
    # list is already scoped to the caller's own hierarchy by erp-api, so a
    # term matching nobody in it is, by construction, not this manager's to
    # see — the same scope guarantee _resolve_employee got from the roster,
    # without the endpoint that 404s.
    # A team member's name ALONE while the review is on screen - "Dileep
    # Anumula" typed under the list or in answer to "which one?". Live it went
    # to the employee search and then the LEAVE lookup ("has no pending leave
    # requests"). It narrows to that person: one request gets its confirmation
    # card, several are asked about again (theirs only). A pick by position
    # ("the second one") is left to _match_selection below.
    if (reviewing and employee_name is None and employee_id is None
            and request_id is None and apply_date is None and apply_day is None
            and _BARE_NAME_REPLY_RE.match(target_text or "")
            and not _POSITION_WORD_RE.search(target_text or "")
            and not _ANY_ACTION_WORD_RE.search(target_text or "")
            and all(_is_name_word(w) for w in (target_text or "").split())
            and _match_selection(target_text, rows) is None):
        employee_name = target_text.strip(" .!")

    if employee_id is None and employee_name:
        matched_employee = _resolve_employee_from_rows(employee_name, rows)
        if matched_employee is None:
            # Nobody WITH a pending request matches. They may still be a
            # report who simply has none — only the roster can tell those
            # apart, and the difference is worth one call because "A Emp has
            # no pending requests" and "not in your team" are different
            # answers. If the roster route is unavailable (it answers 404 on
            # this deployment), fall back to the not-found sentence: it is
            # true either way, since no pending request was found.
            matched_employee, error = await _resolve_employee(
                employee_name, bearer_token, company_id, conversation_id, _finish,
                writer=writer,
            )
            if matched_employee is None:
                return error if error is not None else _finish(NOT_IN_YOUR_TEAM_MESSAGE)
        employee_id = _as_int(matched_employee.get("employee_id"))

    # Defence in depth, not a scope check: erp-api has already scoped the
    # list, and this only drops rows that do not match a narrowing the
    # manager themselves asked for.
    if employee_id is not None:
        rows = [r for r in rows if _same_employee(r, employee_id)]

    # An employee_id given outright narrows just as much as a resolved name,
    # but leaves matched_employee unset — so the heading said "your team's
    # pending regularization requests" while listing exactly one person's.
    # The rows carry the attribution, so take it from them.
    if matched_employee is None and employee_id is not None and rows:
        matched_employee = rows[0]
    label = _employee_label(matched_employee or {}, default=None) if matched_employee else None

    if not rows:
        if label:
            return _finish(f"{label} has no pending regularization requests right now.",
                           finish_intent=VIEW_INTENT if not wants_approval else intent)
        return _finish(
            "Great news! There are currently no pending regularization requests for your team.",
            finish_intent=VIEW_INTENT if not wants_approval else intent,
        )

    # Display fields (Ref ID, type, applied by/on) added for the cards; every
    # erp-api key the approval matching below reads is left as it was.
    # Row buttons for a Manager/HR/Admin: Accept and Reject while Pending
    # (approve/reject=true), never Cancel - see regularisation_display.approver_actions.
    sorted_rows = [{**r, **approver_actions(r)} for r in
                   enrich_rows(sorted(rows, key=lambda r: str(r.get("apply_date") or "")))]

    # -- VIEW ---------------------------------------------------------------
    if not wants_approval:
        total = data.get("total_pending_regularizations", len(sorted_rows))
        table = {
            "title": f"Pending regularization requests ({total})",
            "subtitle": "Waiting for your action, oldest first.",
            "note": "Accept or Reject opens a confirmation. Nothing changes until you confirm.",
            "total_pending_regularizations": total,
            # The count the frontend shows on the team table.
            "total_count": total,
            "regularizations": sorted_rows,
            "has_more": len(sorted_rows) > _LIST_LIMIT,
            "employee": matched_employee,
        }
        writer({"type": "team_pending_regularization", "data": table})
        return _finish(_render_list(sorted_rows, label), finish_intent=VIEW_INTENT,
                       extra_data={k: v for k, v in table.items() if k != "employee"})

    # -- APPROVE: pick the target, or ask ------------------------------------
    # A named DAY narrows before anything else is tried, because it is the
    # manager's own way of pointing at one request: they saw "2026-10-02 was
    # a missed punch", not "request 67". Applied to the rows already scoped
    # to this manager (and to the named employee, if one was given), so it
    # can only ever narrow inside the permitted set.
    if apply_date is not None or apply_day is not None:
        if apply_date is not None:
            dated_rows = [r for r in sorted_rows if str(r.get("apply_date") or "") == apply_date]
        else:
            dated_rows = [r for r in sorted_rows if _day_of(r.get("apply_date")) == apply_day]
            apply_date = f"day {apply_day} of the month"
        if not dated_rows:
            # Say WHICH days do have one rather than a bare "not found" — the
            # manager is one keystroke from the right question, and listing
            # their own team's dates leaks nothing they cannot already see.
            whose = f"{label}'s" if label else "your team's"
            available = ", ".join(
                sorted({str(r.get("apply_date")) for r in sorted_rows if r.get("apply_date")})
            )
            message = f"There's no pending regularization request on {apply_date} in {whose} queue."
            if available:
                message += f" Pending dates: {available}."
            return _refuse(f"{message} Nothing has been changed.",
                           finish_intent="regularisation_approval_failed")
        sorted_rows = dated_rows

    target = None
    if request_id is not None:
        target = next(
            (r for r in sorted_rows if _as_int(r.get("regularization_id")) == request_id), None,
        )
        if target is None:
            # The id is real to the manager but absent from THEIR pending
            # list - the same answer as out-of-team, deliberately.
            return _refuse(f"{NOT_IN_YOUR_TEAM_MESSAGE} Nothing has been changed.",
                           finish_intent="regularisation_approval_failed")
    elif len(sorted_rows) == 1:
        # Not a guess: there is exactly one candidate inside the scope the
        # manager named, and the confirmation card still has to be accepted
        # before anything is written.
        target = sorted_rows[0]
    else:
        selected = _match_selection(target_text, sorted_rows)
        if selected is not None:
            target = selected
        else:
            return _finish(_render_choice(sorted_rows, action),
                           finish_intent=("regularisation_rejection_choice"
                                          if action == ACTION_REJECT
                                          else "regularisation_approval_choice"),
                           extra_data={"regularizations": sorted_rows})

    return _build_confirmation(target, query, company_id, conversation_id, writer, _finish,
                               action=action, rejection_reason=inline_reason,
                               pending_total=team_pending_total)


# -- Helpers -----------------------------------------------------------------


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


def _same_employee(row: dict, employee_id) -> bool:
    return _as_int(row.get("employee_id")) == _as_int(employee_id)


def _resolve_employee_from_rows(term: str, rows: list):
    """The one employee `term` names, from the regularization rows
    themselves, or None.

    The rows carry employee_number ("geo6") and employee_name ("A Emp"), so
    they double as the roster for a by-name narrowing — which matters
    because erp-api's dedicated roster route answers 404 here.

    Delegates the matching to individual_report._resolve_from_roster so the
    two features cannot drift: employee_number is matched EXACTLY (never as
    a substring, or "geo1" would also pull in "geo11" and turn a precise
    reference into an ambiguous one), then employee_name as a substring.

    Ambiguity is refused rather than guessed: several distinct employees
    matching returns None, which the caller answers with the same
    not-in-your-team sentence as no match. Approving the wrong person's
    record because two names overlapped is the failure worth avoiding.
    """
    if not term or not rows:
        return None
    matches = individual_report._resolve_from_roster(term, rows)
    distinct = {_as_int(m.get("employee_id")) for m in matches}
    if len(distinct) != 1:
        return None
    return matches[0]


async def _resolve_employee(employee_name, bearer_token, company_id, conversation_id, _finish,
                            writer=None):
    """(employee_row, error_response). Both None means "the roster could not
    be consulted" — the caller decides what to say, because by the time this
    runs the pending list has already been searched and a not-found answer is
    true regardless.

    Only reached when the name matched nobody who HAS a pending request. The
    roster is erp-api's statement of who this manager manages, so it is what
    separates "is your report, has none pending" from "is not your report".

    Transport failure is deliberately NOT an outage message here: this route
    answers 404 on the deployed erp-api, and reporting that as "I'm unable to
    reach the HR system" told a manager to retry something that will never
    succeed, for a question the pending list had already answered.
    """
    try:
        result = await erp_client.get_team_members(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
        )
    except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable) as e:
        logger.info("[RegularisationApproval] roster unavailable (%s) - answering from "
                    "the pending list alone", type(e).__name__)
        return None, None

    if result.get("http_status") == 403:
        return None, _finish(NOT_A_MANAGER_MESSAGE, finish_intent=access_notice.RESTRICTED_INTENT,
                             extra_data=access_notice.refuse(writer, "regularisation_approval",
                                                             NOT_A_MANAGER_MESSAGE))

    members = ((result.get("body") or {}).get("data") or {}).get("members") or []
    matches = individual_report._resolve_from_roster(employee_name, members)

    if len(matches) == 1:
        return matches[0], None
    if not matches:
        return None, _finish(NOT_IN_YOUR_TEAM_MESSAGE)

    names = ", ".join(
        f"{m.get('employee_name')} ({m.get('employee_number')})" for m in matches[:5]
    )
    return None, _finish(
        f"More than one person on your team matches \"{employee_name}\": {names}. "
        "Which one did you mean?",
        finish_intent="regularisation_approval_choice",
    )


def _build_confirmation(row, requested_query, company_id, conversation_id, writer, _finish,
                        action=ACTION_APPROVE, rejection_reason=None, pending_total=None):
    """Shows the summary and STOPS. No erp-api write happens on this turn -
    a property of this function returning before any such call exists on the
    path, not of a flag checked later. Both decisions arm through here."""
    card = _confirmation_card(row, action, rejection_reason)

    # Reject without a reason waits for the REASON (it is the confirmation);
    # with one already given, a plain yes confirms the card as shown.
    step = ("awaiting_rejection_reason"
            if action == ACTION_REJECT and not rejection_reason else "awaiting_confirmation")
    stored = leave_slot_service.set_manager_action(company_id, conversation_id, {
        "kind": CARD_KIND,
        "step": step,
        "action": action,
        "regularization_id": row.get("regularization_id"),
        "card": card,
        "requested_query": requested_query,
        "pending_total": pending_total,
    })
    if not stored:
        # Without the stored action there is nothing for the reply to resolve
        # against, and re-deriving it from the confirming message is exactly
        # what FR-08.3 forbids ("yes" names no request).
        return _finish(
            "I can't hold this action long enough to confirm it right now - "
            f"please {action} this request in the HR portal instead. Nothing has "
            "been changed.",
            finish_intent="regularisation_approval_unavailable",
        )

    writer({"type": "regularisation_approval_confirmation", "data": card})
    # A reject card that already carries its reason ("reject REG-149 because
    # ...") is the "Confirm rejection" step - the same intent as when the
    # reason arrives on its own turn.
    return _finish(_render_confirmation(card),
                   finish_intent=("regularisation_rejection_confirmation"
                                  if action == ACTION_REJECT and rejection_reason
                                  else "regularisation_approval_confirmation"),
                   extra_data=card)


async def _execute_approval(pending, confirmation_query, bearer_token, company_id,
                            conversation_id, writer, _finish):
    """The ONLY path that changes state, reachable only from a stored
    awaiting_confirmation written by a previous turn."""
    card = pending.get("card") or {}
    regularization_id = pending.get("regularization_id")

    if regularization_id is None:
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        return _finish("I've lost track of which request that was - could you name it again? "
                       "Nothing has been changed.")

    # Cleared BEFORE the call, not after: if the approval succeeds and the
    # clear then fails, the state still says awaiting_confirmation and the
    # manager's next "yes" re-approves. Clearing first makes the failure mode
    # a second "yes" that finds nothing pending (harmless) instead of a
    # duplicate write.
    cleared = leave_slot_service.clear_manager_action(company_id, conversation_id)
    if not cleared:
        cleared = leave_slot_service.clear_manager_action(company_id, conversation_id)
    if not cleared:
        logger.error(
            "[RegularisationApproval] could not clear pending action before "
            "executing (regularization_id=%s, conversation_id=%s) - refusing "
            "rather than risking a repeatable approval",
            regularization_id, conversation_id,
        )
        return _finish(
            "I can't safely confirm this action right now - please approve this "
            "request in the HR portal instead. Nothing has been changed.",
            finish_intent="regularisation_approval_unavailable",
        )

    writer({"type": "submitting_regularisation_approval",
            "message": "Approving that regularization request..."})

    async def _log(executed, erp_status, erp_message):
        await audit_log_service.log_regularization_approval(
            action=ACTION_APPROVE,
            regularization_id=regularization_id,
            executed=executed,
            confirmation_query=confirmation_query,
            requested_query=pending.get("requested_query"),
            employee_id=card.get("employee_id"),
            employee_name=card.get("employee_name"),
            erp_status=erp_status,
            erp_message=erp_message,
            company_id=company_id,
            conversation_id=conversation_id,
        )

    try:
        result = await erp_client.approve_regularization(
            bearer_token, regularization_id,
            company_id=company_id, conversation_id=conversation_id,
        )
    except erp_client.ErpApiTimeout:
        # Logged as an ATTEMPT, not an outcome: a timeout means erp-api may
        # or may not have applied it, and the audit row says exactly that.
        await _log(False, None, "erp-api timeout - outcome unknown")
        return _finish("I couldn't reach the HR system in time to approve this. "
                       "Please check the request in the HR portal before trying again.",
                       extra_data={**_SERVICE_DOWN_DATA, "changed": None})
    except erp_client.ErpApiUnavailable as exc:
        await _log(False, getattr(exc, "status_code", None), f"erp-api did not accept: {exc}")
        return _erp_failure_reply(exc, _finish, ACTION_APPROVE)
    except Exception as e:
        # Deliberately broad, and deliberately only here: this is the one
        # point where the card has already been cleared and erp-api may or
        # may not have applied the approval. An exception escaping would cost
        # the manager both the answer AND the card.
        logger.exception(
            "[RegularisationApproval] unexpected error approving regularization_id=%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 approving that, and I can't tell "
            "whether it went through. Please check the request in the HR portal "
            "before trying again.",
            finish_intent="regularisation_approval_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)
        logger.info("[RegularisationApproval] erp-api refused approval | status=%s | message=%s",
                    http_status, erp_message)
        return _finish(
            _refusal_sentence(erp_message, NOT_IN_YOUR_TEAM_MESSAGE),
            finish_intent="regularisation_approval_failed",
        )

    approved = body.get("data") or {}
    await _log(True, http_status, erp_message)

    employee = card.get("employee_name") or "That team member"
    on_date = card.get("apply_date")
    when = f" for {on_date}" if on_date else ""
    message = (
        f"Approved - {employee}'s regularization request{when} is now "
        f"{approved.get('status_name') or 'approved'}. The action has been logged."
    )
    message, data = _success_card(message, approved, card, pending, ACTION_APPROVE)

    # The sentence travels WITH the event, not only on the done frame, so a
    # client rendering a success card never has to rebuild the wording from
    # the raw erp-api row (and invent fallbacks when a field is absent).
    writer({"type": "regularisation_approval_success", "data": {**data, "message": message}})

    return _finish(message, finish_intent="regularisation_approval_success", extra_data=data)


def _success_card(message: str, erp_data: dict, card: dict, pending: dict, action: str):
    """The design's "Request approved" / "Request rejected" card: Reference,
    Employee, Date, Status, Approved/Rejected on, and how many requests are
    still waiting. Status comes from erp-api's answer; the on-time is when it
    confirmed (its response carries none)."""
    status = str(erp_data.get("status_name") or ("approved" if action == ACTION_APPROVE
                                                 else "rejected"))
    total = pending.get("pending_total")
    remaining = max(int(total) - 1, 0) if isinstance(total, int) else None
    data = {
        **erp_data,
        "action": action,
        "reference_id": card.get("reference_id"),
        "employee_name": erp_data.get("employee_name") or card.get("employee_name"),
        "employee_number": erp_data.get("emp_no") or card.get("employee_number"),
        "date_range_display": card.get("date_range_display"),
        "status_label": status.replace("_", " ").title(),
        f"{'approved' if action == ACTION_APPROVE else 'rejected'}_on": action_time_display(),
        "remaining_pending": remaining,
    }
    who = data["employee_name"] or "The employee"
    extra = (f" {who} has been notified with your reason." if action == ACTION_REJECT
             else f" {who} has been notified.")
    if remaining:
        extra += (f" {remaining} request{'s are' if remaining != 1 else ' is'} still "
                  f"waiting for you.")
    return message + extra, data


async def _execute_rejection(pending, rejection_reason, bearer_token, company_id,
                             conversation_id, writer, _finish):
    """The second path that changes state, reachable only from a stored
    awaiting_rejection_reason (or a reject card that already carries the
    manager's reason) written by a previous turn.

    Mirrors _execute_approval deliberately - same clear-before-write ordering,
    same audit on every outcome, same catch-all - so the two decisions cannot
    drift into different safety properties.
    """
    card = pending.get("card") or {}
    regularization_id = pending.get("regularization_id")

    if regularization_id is None:
        leave_slot_service.clear_manager_action(company_id, conversation_id)
        return _finish("I've lost track of which request that was - could you name it again? "
                       "Nothing has been changed.")
    if len((rejection_reason or "").strip()) < _MIN_REJECTION_REASON:
        # Never sent without a reason the manager wrote: erp-api records it and
        # the employee reads it.
        return _finish("Please tell me the reason for rejecting it - the employee sees "
                       "this reason. Reply with the reason, or 'no' to leave it pending.")

    cleared = leave_slot_service.clear_manager_action(company_id, conversation_id)
    if not cleared:
        cleared = leave_slot_service.clear_manager_action(company_id, conversation_id)
    if not cleared:
        logger.error(
            "[RegularisationApproval] could not clear pending action before rejecting "
            "(regularization_id=%s, conversation_id=%s) - refusing rather than "
            "risking a repeatable rejection", regularization_id, conversation_id,
        )
        return _finish(
            "I can't safely confirm this action right now - please reject this "
            "request in the HR portal instead. Nothing has been changed.",
            finish_intent="regularisation_approval_unavailable",
        )

    writer({"type": "submitting_regularisation_approval",
            "message": "Rejecting that regularization request..."})

    async def _log(executed, erp_status, erp_message):
        await audit_log_service.log_regularization_approval(
            action=ACTION_REJECT,
            regularization_id=regularization_id,
            executed=executed,
            confirmation_query=rejection_reason,
            requested_query=pending.get("requested_query"),
            employee_id=card.get("employee_id"),
            employee_name=card.get("employee_name"),
            erp_status=erp_status,
            erp_message=erp_message,
            company_id=company_id,
            conversation_id=conversation_id,
        )

    try:
        result = await erp_client.reject_regularization(
            bearer_token, regularization_id, rejection_reason.strip(),
            company_id=company_id, conversation_id=conversation_id,
        )
    except erp_client.ErpApiTimeout:
        await _log(False, None, "erp-api timeout - outcome unknown")
        return _finish("I couldn't reach the HR system in time to reject this. "
                       "Please check the request in the HR portal before trying again.",
                       extra_data={**_SERVICE_DOWN_DATA, "changed": None})
    except erp_client.ErpApiUnavailable as exc:
        await _log(False, getattr(exc, "status_code", None), f"erp-api did not accept: {exc}")
        return _erp_failure_reply(exc, _finish, ACTION_REJECT)
    except Exception as e:
        logger.exception(
            "[RegularisationApproval] unexpected error rejecting regularization_id=%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 rejecting that, and I can't tell "
            "whether it went through. Please check the request in the HR portal "
            "before trying again.",
            finish_intent="regularisation_approval_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)
        logger.info("[RegularisationApproval] erp-api refused rejection | status=%s | message=%s",
                    http_status, erp_message)
        return _finish(
            _refusal_sentence(erp_message, NOT_IN_YOUR_TEAM_MESSAGE),
            finish_intent="regularisation_approval_failed",
        )

    rejected = body.get("data") or {}
    await _log(True, http_status, erp_message)

    _, data = _success_card("", rejected, card, pending, ACTION_REJECT)
    reason = (rejected.get("rejection_reason") or rejection_reason).strip()
    data["rejection_reason"] = reason
    message = _rejection_success_message(data, card, reason)

    writer({"type": REJECTION_SUCCESS_INTENT, "data": {**data, "message": message}})

    return _finish(message, finish_intent=REJECTION_SUCCESS_INTENT, extra_data=data)


#: A confirmed rejection has its own success intent (an approval keeps
#: "regularisation_approval_success"), so the client can show the "Request
#: rejected" card without inspecting `action`.
REJECTION_SUCCESS_INTENT = "regularisation_rejection_success"


def _rejection_success_message(data: dict, card: dict, reason: str) -> str:
    """ "Rejected - A Khan Test's regularization request for 05-Oct-2026
    (REG-149) has been rejected.\\nReason: ..." plus how many are still
    waiting. States only what erp-api confirmed - no claim that anyone was
    notified."""
    employee = data.get("employee_name") or card.get("employee_name") or "That team member"
    # The same day the confirmation showed ("05-Oct-2026"), not erp-api's ISO.
    on_date = (card.get("date_range_display") or "").split(" – ")[0] or card.get("apply_date")
    ref = data.get("reference_id") or card.get("reference_id")
    when = f" for {on_date}" if on_date else ""
    ref_part = f" ({ref})" if ref else ""
    message = (f"Rejected - {employee}'s regularization request{when}{ref_part} "
               f"has been rejected.\nReason: {reason}")
    remaining = data.get("remaining_pending")
    if remaining:
        message += (f"\n\n{remaining} request{'s are' if remaining != 1 else ' is'} "
                    f"still waiting for you.")
    return message
