"""Centralised interpretation of erp-api leave failure responses (HEL-283).

When a leave action can't complete, the employee must be shown erp-api's own
reason rather than a generic error — and Helix AI must never invent, reword or
infer one. Every leave node routes its failures through interpret_failure() so
that rule lives in exactly one place instead of being re-implemented per intent.

Observed erp-api failure contract (apply and cancel, verified 2026-08-19):

    {"success": false,
     "message": "You have already applied Casual Leave from 2026-08-20 to 2026-08-20.",
     "data": {"error": "<the same string, duplicated>"}}

There is exactly one piece of information in a failure: a human-readable
sentence. No reason codes, no structured list, no context fields. Two
consequences the caller has to live with:

  * Multiple simultaneous failure reasons cannot be shown (HEL-283 AC4) —
    one string can't be split into several without inferring, which AC5
    forbids. That's a property of erp-api, not a gap here.
  * reason_code is derived locally, by exact pattern, and defaults to
    "POLICY_RULE" whenever nothing more specific matches (product decision,
    2026-08-24 — supersedes the original None/no-badge default). erp-api's
    exact display_message is still shown untouched either way; only the
    badge/category label is ever a guess, never the reason text itself.

If erp-api ever returns structured failures, only this module changes.
"""

import re
from dataclasses import dataclass

# Shown when erp-api gives us nothing usable. Deliberately says nothing about
# cause — we don't know it, and guessing is what AC5 prohibits.
FALLBACK_MESSAGE = (
    "Unable to complete your leave request at this time. Please try again "
    "later or contact HR support if the issue persists."
)

# Markers that mean erp-api leaked an internal error instead of a user-facing
# sentence (an unhandled Laravel exception, a DB error surfacing through
# sendInfo()). This is a denylist for leaking, NOT a classifier for meaning:
# it only decides whether a string is safe to show, never what it means.
# AC5 requires raw technical detail never reach employees, and erp-api has no
# guarantee against it on unhandled paths.
_TECHNICAL_MARKERS = (
    "sqlstate", "exception", "stack trace", "traceback", "#0 /", "\vendor\\",
    "/vendor/", "syntax error", "undefined index", "undefined variable",
    "call to a member function", "class not found", "<!doctype", "<html",
)

# Message pattern -> reason code. Derived from erp-api responses actually
# observed, not from the ticket's assumed taxonomy. First match wins.
#
# Note what is NOT here: INSUFFICIENT_BALANCE, BLOCKED_DATE and
# POLICY_RESTRICTION — the three categories HEL-283 is written around. None
# has ever been seen in a real erp-api response. They get added when one is,
# with the real wording, rather than being guessed at now.
_REASON_CODE_PATTERNS = (
    (re.compile(r"already been cancell?ed", re.IGNORECASE), "ALREADY_CANCELLED"),
    (re.compile(r"have already applied", re.IGNORECASE), "DUPLICATE_APPLICATION"),
    (re.compile(r"attendance (?:has already been calculated|is locked)", re.IGNORECASE),
     "ATTENDANCE_LOCKED"),
    # "Monthly sick leave limit reached. Monthly limit: 2, already applied: 2,
    # requested: 1." Deliberately NOT filed as INSUFFICIENT_BALANCE: a monthly
    # cap is a separate rule from balance exhaustion, and an employee can hit
    # it while still holding plenty of annual balance. Which badge it belongs
    # under is a BA decision, not one to guess at here.
    (re.compile(r"monthly.{0,40}limit reached", re.IGNORECASE), "MONTHLY_LIMIT_REACHED"),
)


@dataclass(frozen=True)
class LeaveFailure:
    """display_message is always safe to show the employee verbatim.

    reason_code is a display hint only (which badge to render) — it defaults
    to "POLICY_RULE" when classify() doesn't recognise the message (see
    classify()'s own docstring), rather than being left unset. is_fallback
    is True when display_message is our own FALLBACK_MESSAGE rather than
    erp-api's words — the UI should not present a fallback as though the
    backend explained anything.

    heading is an optional override for the card's sub_title, for a reason
    that needs context _HEADING_BY_REASON_CODE can't supply on its own —
    INSUFFICIENT_BALANCE's sub_title ("Not enough Sick Leave balance") names
    the specific leave type, which only the caller building the failure
    actually knows. None falls back to the static reason_code lookup.
    """
    display_message: str
    reason_code: str | None
    is_fallback: bool
    heading: str | None = None


def is_failure(body: dict) -> bool:
    """erp-api signals business rejections with success=false at HTTP 400,
    which erp_client._request deliberately surfaces as data rather than an
    exception. A missing 'success' key is treated as failure: a body we can't
    read is not a success we can confirm."""
    if not isinstance(body, dict):
        return True
    return not body.get("success", False)


def _is_not_a_sentence(text: str) -> bool:
    """True when the string identifies a condition instead of explaining one.

    AC5 requires a controlled fallback when erp-api returns only a technical
    or unknown error code. Those don't carry the markers _TECHNICAL_MARKERS
    looks for — "ERR_5521", "E1042", "500" and "Failed." are all clean
    strings — but none of them tells an employee anything, so they must not
    be shown as if they were the reason.
    """
    text = text.strip()
    if " " not in text:
        # A bare token: "ERR_5521", "500", "INSUFFICIENT_BALANCE", "Failed."
        return True
    # A short shouted identifier: "ERR 5521", "LEAVE ERROR 42". Bounded to a
    # few words so genuine prose that happens to be capitalised isn't caught.
    words = text.replace("_", " ").replace("-", " ").split()
    letters = [c for c in text if c.isalpha()]
    if len(words) <= 4 and letters and all(c.isupper() for c in letters):
        return True
    return False


def _usable_message(body: dict) -> str | None:
    """erp-api duplicates the reason into both 'message' and data.error.
    Prefer 'message'; fall back to data.error only if it's missing, since the
    two have always been identical."""
    candidates = []
    if isinstance(body, dict):
        candidates.append(body.get("message"))
        data = body.get("data")
        if isinstance(data, dict):
            candidates.append(data.get("error"))

    for candidate in candidates:
        if not isinstance(candidate, str):
            continue
        text = candidate.strip()
        if not text:
            continue
        lowered = text.lower()
        if any(marker in lowered for marker in _TECHNICAL_MARKERS):
            continue
        if _is_not_a_sentence(text):
            continue
        return text
    return None


def classify(message: str) -> str:
    """Message -> reason code by exact pattern, or "POLICY_RULE" when
    unrecognised (product decision, 2026-08-24 — every failure gets a
    category, even a general one, rather than none at all).

    Pattern matching stays deterministic on purpose. HEL-283's QA section
    requires the mapping be validated against an approved matrix, which
    means it has to be a table a person can read — an LLM classifier would
    re-decide per call and couldn't be signed off.
    """
    for pattern, code in _REASON_CODE_PATTERNS:
        if pattern.search(message):
            return code
    return "POLICY_RULE"


def interpret_failure(body: dict) -> LeaveFailure:
    """Turn an erp-api failure body into something displayable.

    Never rewords, never summarises, never explains. erp-api's sentence is
    passed through untouched, or replaced wholesale by FALLBACK_MESSAGE when
    there isn't one worth showing. The reason_code is Helix's own category
    guess either way — the display_message itself is never touched.
    """
    message = _usable_message(body)
    if message is None:
        return LeaveFailure(FALLBACK_MESSAGE, "POLICY_RULE", True)
    return LeaveFailure(message, classify(message), False)


# ── Display grouping ─────────────────────────────────────────────────────────
#
# Reason codes and badges are deliberately separate layers. Codes stay precise
# (a monthly cap is not a duplicate application is not a missing leave type);
# badges are the coarse grouping HEL-283's mockup renders, and several codes
# can share one. Keeping them apart means the display taxonomy can change on a
# BA's say-so without touching the interpretation logic, and no information is
# thrown away to make a code fit one of three boxes.
#
# This table IS the "approved mapping matrix" the ticket's QA section asks for:
# one human-readable place, reviewable row by row.
BADGE_BALANCE = "balance"
BADGE_BLOCKED_DATE = "blocked_date"
BADGE_POLICY_RULE = "policy_rule"
BADGE_DUPLICATE_REQUEST = "duplicate_request"

# Human-readable label for a badge slug — what the chip itself displays
# ("Policy rule"), as opposed to the slug used for styling/lookup.
_BADGE_LABELS = {
    BADGE_BALANCE: "Balance",
    BADGE_BLOCKED_DATE: "Blocked date",
    BADGE_POLICY_RULE: "Policy rule",
    BADGE_DUPLICATE_REQUEST: "Duplicate Request",
}

# Short heading shown above the backend's own message on the failure card
# ("Blocked by leave policy" above "Policy LP-14: approved leave can only be
# cancelled..."). Same "approved mapping matrix" philosophy as badges: only
# populated for a reason code with a real, confirmed mockup/example — added
# to as more are confirmed, never guessed at ahead of one.
_HEADING_BY_REASON_CODE = {
    "POLICY_RULE": "Blocked by leave policy",
    "DUPLICATE_APPLICATION": "Requested date is a duplicate",
    "BLOCKED_DATE": "Requested date is blocked",
    # INSUFFICIENT_BALANCE deliberately excluded from this static table: its
    # confirmed mockup example ("Not enough Sick Leave balance") embeds the
    # specific leave type, which a fixed reason_code -> text mapping can't
    # produce. That case is instead built by the caller and passed in via
    # LeaveFailure.heading / local_failure(..., heading=...), which wins
    # over this table — see build_card()'s "sub_title" field.
}

_BADGE_BY_REASON_CODE = {
    # Unambiguous.
    "INSUFFICIENT_BALANCE": BADGE_BALANCE,
    "BLOCKED_DATE": BADGE_BLOCKED_DATE,
    # A leave type the company hasn't configured, the probation rule, and
    # classify()'s own catch-all default all read as policy deciding what
    # you may ask for or do.
    "LEAVE_TYPE_NOT_IN_POLICY": BADGE_POLICY_RULE,
    "REQUIRES_CONFIRMATION": BADGE_POLICY_RULE,
    "POLICY_RULE": BADGE_POLICY_RULE,
    # A request already sitting on the same date(s) — mapped to its own
    # badge (2026-08-26) rather than left unmapped, matching the same
    # treatment BLOCKED_DATE already gets and consistent with its sub_title
    # ("Requested date is a duplicate") already existing in
    # _HEADING_BY_REASON_CODE above.
    "DUPLICATE_APPLICATION": BADGE_DUPLICATE_REQUEST,

    # Still deliberately UNMAPPED pending BA sign-off — each is a real,
    # SPECIFIC failure that fits none of the mockup's boxes cleanly, and
    # guessing is what produces a "Balance" badge on a blocked-date failure:
    #   ALREADY_CANCELLED       - a state conflict, not a policy rule
    #   ATTENDANCE_LOCKED       - timing/payroll state, arguably policy
    #   MONTHLY_LIMIT_REACHED   - a policy rule expressed in quantities;
    #                             reads as either balance or policy
    # Unmapped means no badge, which is a correct render, not a degraded one:
    # the employee still sees erp-api's exact reason. This is unrelated to
    # classify()'s POLICY_RULE default above — these are already-KNOWN,
    # specific codes that just don't fit a box; POLICY_RULE is for when
    # nothing at all was recognised.
}

# Card titles come from which action failed — known from the intent, never
# from reading the message. No interpretation involved.
_TITLE_BY_ACTION = {
    "apply_leave": "Leave Request Not Completed",
    "cancel_leave": "Cancellation Not Completed",
    "leave_eligibility": "Eligibility Check Not Completed",
}


def badge_for(reason_code: str | None) -> str | None:
    """Display grouping for a reason code, or None when it has no approved
    badge. None is a valid, intended outcome — see _BADGE_BY_REASON_CODE."""
    if not reason_code:
        return None
    return _BADGE_BY_REASON_CODE.get(reason_code)


def badge_label_for(reason_code: str | None) -> str | None:
    """Human-readable label for the badge a reason code maps to ("Policy
    rule"), or None when there's no badge to label."""
    badge = badge_for(reason_code)
    return _BADGE_LABELS.get(badge) if badge else None


def heading_for(reason_code: str | None) -> str | None:
    """Short heading for the failure card ("Blocked by leave policy"), or
    None when this reason code has no approved heading yet — see
    _HEADING_BY_REASON_CODE."""
    if not reason_code:
        return None
    return _HEADING_BY_REASON_CODE.get(reason_code)


def local_failure(
    display_message: str, reason_code: str | None = None, heading: str | None = None,
) -> LeaveFailure:
    """A failure Helix determined itself rather than reading off erp-api —
    the balance pre-check, or a leave type the company hasn't configured.

    Legitimate because these aren't interpretations of a backend rejection:
    the numbers come from the balance API and the configured types from
    leave_settings, so Helix is reporting data it was given, not theorising
    about why erp-api said no. is_fallback is False: this text IS the reason.

    heading lets the caller supply a sub_title that needs context the static
    _HEADING_BY_REASON_CODE table can't have — e.g. INSUFFICIENT_BALANCE's
    "Not enough Sick Leave balance", which names the specific leave type.
    """
    return LeaveFailure(display_message, reason_code, False, heading)


def chip(label: str, action: str) -> dict:
    """One quick-reply chip: a short button label plus a machine-readable
    action slug the frontend dispatches on tap (e.g. "select_another_date").
    A thin constructor rather than a dataclass — the card is already a plain
    dict, and every call site just wants a literal {label, action} pair."""
    return {"label": label, "action": action}


def build_card(
    action: str, failure, next_action: str | None = None,
    next_actions: list[dict] | None = None,
) -> dict:
    """The single shape every leave failure card is emitted in, so apply,
    cancel and eligibility can't drift into three different payloads.

    `failure` is one LeaveFailure or a list of them, most important first.
    AC4 asks for every applicable reason, so the card always carries a
    failures[] array — a single reason is simply an array of one, which keeps
    one shape for the frontend instead of two. The top-level display_message /
    reason_code / badge mirror the first entry, so a simple renderer never has
    to unpack the array.

    Where several reasons can genuinely co-occur: erp-api refuses with its own
    reason, and Helix's own checks (holiday calendar, balance, existing
    applications) find further problems with the same request. Reporting them
    together stops an employee fixing one thing, resubmitting, and meeting the
    next one — which is the round-trip the single-reason version caused.

    next_action is the spoken follow-up sentence appended to the chat reply
    (or None when nothing safe to say — see each call site). next_actions is
    the separate, structured list of quick-reply chips the design mockup
    shows at the bottom of the card (HA-163 Sprint 2 spec) — zero, one, or
    several buttons, each with its own label and machine-readable action, as
    opposed to next_action's single free-text sentence. The two are
    independent: a card can have spoken text with no chips, chips with no
    spoken text, both, or neither — never inferred from each other.
    """
    failures = [failure] if isinstance(failure, LeaveFailure) else list(failure)
    primary = failures[0]
    return {
        # Sibling to the nested "failure" card below, not the same key — a
        # plain top-level boolean so the frontend can decide whether to
        # render the failure card without inspecting the nested object at
        # all. Always True here; a non-failure response simply omits it (or,
        # for apply_leave/cancel_leave/cancel_ask, _finish defaults it False).
        "is_failure": True,
        # Flat, scalar mirrors of the PRIMARY reason's code/badge label —
        # the same values as failure.reason_code[0]/badge_label[0] below, so
        # a consumer that only cares about the leading reason (the common
        # case) can read it straight off the top level of `done`/extra_data
        # without unpacking the nested card or its arrays at all. The
        # eligibility flow already did this by hand before build_card()
        # existed; every flow gets it for free now.
        "reason_code": primary.reason_code,
        "badge_label": badge_label_for(primary.reason_code),
        "failure": {
        # The outcome of the leave operation itself: the apply or cancel did
        # not go through. NOT a statement about whether Helix worked — system
        # errors (timeout, erp-api unreachable) are out of scope for HEL-283
        # and emit no card at all, precisely because they are no verdict on
        # the leave. Constant here by construction, but carried explicitly
        # because HEL-283's expected response structure names Status alongside
        # Reason Code and Display Message, and QA validates against that shape.
        "status": "REJECTED",
        "action": action,
        "title": _TITLE_BY_ACTION.get(action, "Request Not Completed"),
        # AC4: index-aligned lists, one entry per reason, so the UI can render
        # a bullet per reason with its own chip. erp-api's own reason is
        # always first; anything Helix's checks found about the same request
        # follows. badge/badge_label entries are null where the reason code
        # has no approved badge yet — the positions are kept so the lists
        # stay aligned.
        "reason_code": [f.reason_code for f in failures],
        "badge": [badge_for(f.reason_code) for f in failures],
        "badge_label": [badge_label_for(f.reason_code) for f in failures],
        "display_message": [f.display_message for f in failures],
        # Scalar, not list — a single subtitle for the PRIMARY reason only
        # (erp-api's own, or the first Helix check if there's no erp-api
        # reason at all), same as title/status/is_fallback below. The
        # failure's own heading (set by a caller with context the static
        # table lacks, e.g. INSUFFICIENT_BALANCE's leave type) wins over the
        # reason_code lookup; None when neither has one yet.
        "sub_title": primary.heading or heading_for(primary.reason_code),
        # True when erp-api gave nothing usable for the reason it refused on,
        # so display_message opens with our controlled fallback rather than
        # the backend's words. Any enrichment after that is still ours.
        "is_fallback": primary.is_fallback,
        "next_action": next_action,
        # [] rather than None when the caller passes nothing — a renderer
        # can iterate this directly without a null check.
        "next_actions": list(next_actions) if next_actions else [],
    }}
