import json
import logging
import calendar
import re
import os
from datetime import date, datetime, timedelta

from schema.agent import HRState
from langgraph.types import StreamWriter
from langgraph.graph import END

from services import erp_client as attendance_client
from services import slot_store
from services.slot_flow import SlotFlowConfig, run_slot_flow, _build_entry_cards
from services.regularisation_guards import (
    is_affirmative_reply,
    APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE,
)
from dataclasses import replace
# Reused for its deterministic explicit-date regexes/resolver (numeric
# DD/MM(/YYYY) and day+named-month) — see _build_detected_dates_block
# below. Aliased rather than importing individual names since several of
# these are regex objects rather than functions.
import services.attendance as attendance_mod
# The SAME shared deterministic resolver attendance.py/attendance_explain.py/
# punch_details.py all use for weekday names, "yesterday", "last week
# Wednesday", etc. — see _build_detected_dates_block below for why this
# flow only takes its SINGLE-date results as an extra hint rather than
# replacing the day-of-week table wholesale.
import services.date_query_resolver as date_query_resolver
# Used only by regularisation_eligibility_node's LLM date-extraction
# fallback (see its own docstring) — the deterministic resolver above
# requires exact spelling and silently misses a typo'd month name etc.
from services.ai_service import LLM_TASK_MAX_TOKENS
from services.ai_service import _call_llm, _extract_text, _safe_json_parse, _normalize_usage, INTENT_MODEL
import services.regularisation_display as regularisation_display
import services.payroll_cycle as payroll_cycle

logger = logging.getLogger(__name__)

# Separate slot_store namespace (NOT touched by slot_flow.py's own
# set_slots/clear_slots calls on the "regularization" namespace) used only
# to carry the fetched punch-in/punch-out preview across turns. Without
# this, punch_previews below was a plain local dict rebuilt empty on every
# node invocation — it only ever had data on the SAME turn _fetch_prefill
# ran (i.e. the turn a date first got resolved), so the confirmation turn
# ("yes submit it", handled by the very same node re-entered with
# action="confirm") always sent an empty punch_details block even though
# the punch times had already been fetched and shown to the employee one
# turn earlier (observed bug).
_PUNCH_PREVIEW_NAMESPACE = "regularization_punch_preview"


ENTRY_FIELDS = ["date", "start_time", "end_time", "reason"]

ENTRY_FIELD_LABELS = {
    "date": "the date",
    "start_time": "the start (in) time",
    "end_time": "the end (out) time",
    "reason": "the reason for regularization",
}

_MULTISESSION_STATUS = "multisession"
_COMPLETE_STATUS = "complete"

_EXCEPTION_LABELS = {
    "missing_checkin": "Missing Check-in",
    "missing_checkout": "Missing Check-out",
    "no_punch": "No Punch Recorded",
}

# Explicit cancel language only — short neutral acknowledgments like "ok"
# must NOT match this, or a bare "ok" sent while fields are still missing
# gets treated as abandoning the request (observed bug). "not now" is a
# safe substring add — it's specific enough that it won't appear inside a
# genuine reason/time answer by accident, same reasoning as "cancel"/
# "withdraw" above.
_EXPLICIT_CANCEL_PATTERN = re.compile(
    r"\b(cancel|never\s*mind|forget\s*it|withdraw|drop\s*it|not\s+now|"
    r"don'?t\s*(bother|submit|do\s*it)|stop\s*(this|it)?)\b",
    re.IGNORECASE,
)

# A bare decline ("no", "nope", "nah") only counts as an explicit cancel
# when it IS essentially the whole message — unlike "cancel"/"not now"
# above, "no" is a common word that can legitimately open a genuine
# reason/time answer while a field is still pending (e.g. "no particular
# reason, just forgot to punch out") — matching it as a substring there
# would wrongly abandon an in-progress answer instead of recording it.
# Anchoring to (almost) the entire message keeps the two apart: a bare
# "no"/"nope" reply matches, "no particular reason..." does not.
_BARE_DECLINE_PATTERN = re.compile(r"^\s*(no|nope|nah)\s*[.!]*\s*$", re.IGNORECASE)


def _is_explicit_cancel(query: str) -> bool:
    return bool(_EXPLICIT_CANCEL_PATTERN.search(query)) or bool(_BARE_DECLINE_PATTERN.match(query))


# Explicit "start a brand-new request" language, e.g. "I want to apply a
# new regularization", "start a new regularization request", "another
# regularization request", "let's start over". Deliberately requires a
# "new"/"another"/"fresh"/"start over" qualifier tied to
# "regulari[sz]e/-ation"/"request"/"application" — narrow enough that an
# ordinary correction to the entry already in progress ("change the reason
# to traffic delay", "actually make the date the 20th") never matches this,
# only matches _build_prompt's own entry-update rules instead.
#
# Confirmed live/reported: with an entry already complete and awaiting
# confirmation (or even just incomplete) from an EARLIER, unrelated turn,
# "I want to apply for a new regularization" — no date/time/reason
# mentioned — had the LLM correctly extract no new entry data at all (there
# genuinely isn't any in that message), so the flow just re-displayed the
# STALE entry unchanged ("Shall I go ahead and submit this?" for a request
# the employee never meant to resume) instead of resetting and asking
# "which date(s) would you like to regularize?" the way a first-ever
# regularisation message would. See regularisation_node() below for where
# this triggers the reset — BEFORE the stale entries are ever handed to
# _build_prompt as "already collected", so the LLM sees a genuinely blank
# slate and the normal first-turn flow (including its own candidate-dates
# disambiguation for a multi-date message) runs unchanged from there.
_EXPLICIT_NEW_REQUEST_PATTERN = re.compile(
    r"\b(new|another|fresh)\b[\w\s]{0,20}?\b(regulari[sz]e|regulari[sz]ation|request|application)\b"
    r"|\b(regulari[sz]e|regulari[sz]ation|request)\b[\w\s]{0,20}?\b(new|another|fresh)\b"
    r"|^\s*(start\s+(over|again|fresh)|let'?s\s+start\s+over)\s*[.!]*\s*$",
    re.IGNORECASE,
)


def _is_explicit_new_request(query: str) -> bool:
    return bool(_EXPLICIT_NEW_REQUEST_PATTERN.search(query))


def _display_date(iso_date: str) -> str:
    try:
        return datetime.strptime(iso_date, "%Y-%m-%d").strftime("%d %b %Y")
    except (ValueError, TypeError):
        return iso_date


# ---------------------------------------------------------------------------
# Multi-entry summary / success formatters
# ---------------------------------------------------------------------------

def _format_multi_summary(entries: list[dict]) -> str:
    lines = [
        f"- **{_display_date(e['date'])}:** {e.get('start_time')}–"
        f"{e.get('end_time')}, reason: {e.get('reason')}"
        for e in entries
    ]

    plural = "s" if len(entries) > 1 else ""

    return (
        f"Here's the regularization request{plural} I'll submit:\n\n"
        + "\n".join(lines)
        + f"\n\nShall I go ahead and submit {'these' if len(entries) > 1 else 'this'}?"
    )


def _format_multi_success(entries: list[dict], results: list[dict]) -> str:
    lines = []

    for entry, result in zip(entries, results):
        status = "" if result["ok"] else f"{result['error']}"
        if not result["ok"]:
            lines.append(f"- {status}")

    ok_count = sum(r["ok"] for r in results)

    if ok_count == len(results):
        header = "Your regularization request is submitted successfully."
    elif ok_count == 0:
        header = "Sorry, I wasn't able to submit your regularization request."
    else:
        header = "Your regularization request is submitted successfully."

    return header + "\n\n" + "\n".join(lines)


def _extract_failure_message(entry: dict, body: dict):
    """Pulls a human-readable message out of the ERP's 400 body for a
    single entry. Sync is fine here (no LLM call needed) — kept as a
    plain function so inspect.isawaitable(...) is False and slot_flow.py
    uses the return value directly."""
    return (
        body.get("message")
        or body.get("msg")
        or body.get("error")
        or body.get("detail")
    )


def _submit_failure_message(entry: dict, body: dict, shift: dict | None):
    """SlotFlowConfig.extract_failure_message, shift-aware.

    Same as _extract_failure_message except that a refusal no edit can clear
    is replaced with an explanation of what actually has to change and who
    can change it. Everything else is passed through untouched, so every
    other erp-api reason still reaches the employee verbatim."""
    error = _extract_failure_message(entry, body)
    if _shift_refusal_is_unfixable(error, shift, entry):
        return _unfixable_shift_message(error, shift, entry)
    return error


# ---------------------------------------------------------------------------
# Punch/shift pre-fill
# ---------------------------------------------------------------------------

def _extract_punch_datetime(value: str | None) -> datetime | None:
    if not value:
        return None
    value = value.strip()
    try:
        return datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
    except ValueError:
        return None


def _format_punch_display(dt: datetime | None, requested_date: str) -> str | None:
    if not dt:
        return None
    label = dt.strftime("%H:%M")
    try:
        req = datetime.strptime(requested_date, "%Y-%m-%d").date()
        if dt.date() != req:
            label += " (next day)" if dt.date() > req else " (prev day)"
    except (ValueError, TypeError):
        pass
    return label


def _session_display(session: dict, date_iso: str) -> dict:
    check_in_dt = _extract_punch_datetime(session.get("check_in"))
    check_out_dt = _extract_punch_datetime(session.get("check_out"))
    return {
        "check_in": _format_punch_display(check_in_dt, date_iso),
        "check_out": _format_punch_display(check_out_dt, date_iso),
        "complete": bool(session.get("complete")),
    }


def _resolve_exception(punch_status: str | None, punches: list[dict]) -> str:
    # If the API provided a punch_status, use it directly (formatted to title case)
    if punch_status:
        if punch_status.lower() in (_COMPLETE_STATUS, "complete"):
            return "None"
        return punch_status.replace("_", " ").title()

    # Fallback logic if punch_status is missing from API response
    if not punches:
        return "No Punch Recorded"

    has_check_in = any(p.get("check_in") for p in punches)
    has_check_out = any(p.get("check_out") for p in punches)

    if has_check_in and not has_check_out:
        return "Missing Check-out"
    if has_check_out and not has_check_in:
        return "Missing Check-in"
    if not has_check_in and not has_check_out:
        return "No Punch Recorded"

    return "None"


# The employee's shift for the apply flow, from GET /api/v1/ai/shift-details
# (data.shift: shift_name / start_time / end_time) - works for every role, and
# is the shift the request is checked against, so the employee sees it while
# giving a start and end time. Cached for the conversation: one call, not one
# per turn.
_SHIFT_NAMESPACE = "regularization_shift_details"


async def _get_shift_details(*, bearer_token, company_id, conversation_id,
                             employee_name: str | None = None) -> dict | None:
    """{"shift_name", "start_time", "end_time"} or None. Never raises and never
    blocks the request - a shift the flow can't read is simply not shown."""
    cache_key = f"{conversation_id}:{(employee_name or '').strip().lower()}"
    cached = slot_store.get_slots(_SHIFT_NAMESPACE, company_id, cache_key)
    if cached:
        return cached.get("shift")
    try:
        result = await attendance_client.get_active_shift(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
            employee_name=employee_name)
    except Exception as exc:
        logger.info("[Graph] regularization shift details unavailable: %s", exc)
        return None
    body = result.get("body") if isinstance(result, dict) else None
    if not isinstance(body, dict) or not body.get("success", True):
        return None
    data = body.get("data") or {}
    raw = data.get("shift")
    if not isinstance(raw, dict) or not (raw.get("start_time") or raw.get("end_time")):
        return None
    # The SHIFT's own start_time and end_time, and nothing else, normalised
    # to HH:MM ("15:00") rather than erp-api's "15:00:00" - these values are
    # shown on the card as they are.
    #
    # This deliberately does NOT narrow to the assigned session any more.
    # Sessions are erp-api's internal breakdown of a split shift; confirmed
    # with the erp-api developer on 2026-10-08 that `shift.start_time` and
    # `shift.end_time` are the only keys a regularization is concerned with.
    #
    # What the previous version did, and why it was removed: for a SPLIT
    # shift ("QA Team" 10:00-20:00 = "QA 1st" 10:00-14:30 + "QA 2nd"
    # 15:00-20:00) it replaced the shift with the employee's assigned
    # session, so the card showed "QA Team - QA 2nd, 3:00-8:00 PM" instead of
    # the shift's 10:00 AM-8:00 PM. That was added when submitting the whole
    # shift came back "Assigned session does not belong to the employee
    # shift" - but narrowing never actually fixed the submission, it only
    # changed which error came back.
    #
    # SEPARATE, STILL-OPEN erp-api defect, measured 2026-10-08 for employee
    # 704 whose shift-details publishes start_time 10:00:00, end_time
    # 20:00:00. Bisected on a single date, varying only to_time:
    #
    #     10:00-18:30  -> 200 accepted
    #     10:00-18:31  -> 400 refused
    #     10:00-18:35 / 18:40 / 18:45 / 18:50 / 18:59 / 19:00 / 20:00
    #                  -> 400 refused, all of them
    #
    # So erp-api caps `to_time` at 18:30 while publishing the shift as ending
    # at 20:00. `from_time` is not constrained - 10:00, the shift start, is
    # accepted. Every refusal ever seen on this flow fits that one rule.
    #
    # 18:30 appears NOWHERE in the shift-details response: end_time is
    # 20:00:00, and break_time_minutes + relief_time_minutes (30 + 30) only
    # gets to 19:00. There is no field to read it from, so prefilling a
    # to_time that erp-api will accept is not possible without hardcoding a
    # number erp-api does not publish - which is why this code prefills the
    # SHIFT'S OWN end_time and _shift_refusal_is_unfixable explains the
    # refusal honestly instead of pretending a correction exists.
    #
    # An earlier reading of this said erp-api "only accepts times inside the
    # first session". That was wrong: 10:30-14:00 passed because 14:00 is
    # under the 18:30 cap, not because of the session it sits in. Do not
    # reintroduce session logic on the strength of it.
    shift = {"shift_name": raw.get("shift_name"),
             "start_time": regularisation_display.time_24h(raw.get("start_time")),
             "end_time": regularisation_display.time_24h(raw.get("end_time"))}
    slot_store.set_slots(_SHIFT_NAMESPACE, company_id, cache_key, {"shift": shift})
    return shift


def _assigned_session(data: dict) -> dict | None:
    """The session of a split shift this employee is assigned to, or None for
    a shift without sessions. Picked by the assignment's selected_session_id,
    else the session erp-api marks is_selected_session; a shift with exactly
    one session is that session.

    NO LONGER USED by _get_shift_details - regularization reads the SHIFT's
    own start/end time and ignores sessions entirely (see the comment there
    for the measurements behind that). Kept because it is the one place that
    knows how erp-api expresses "which session is this employee on", which
    the erp-api ticket needs, and because a future feature that genuinely is
    about sessions should not have to work it out again. Do not wire it back
    into the regularization shift lookup."""
    raw = data.get("shift") if isinstance(data, dict) else None
    sessions = [s for s in ((raw or {}).get("sessions") or []) if isinstance(s, dict)]
    if not sessions:
        return None
    selected_id = ((data.get("assignment") or {}).get("selected_session_id"))
    for s in sessions:
        if selected_id is not None and str(s.get("session_id")) == str(selected_id):
            return s
    for s in sessions:
        if s.get("is_selected_session"):
            return s
    return sessions[0] if len(sessions) == 1 else None


def _shift_sentence(shift: dict | None) -> str:
    """" Your shift: General-Shift, 9:00 AM to 6:30 PM." or ""."""
    if not shift:
        return ""
    start = regularisation_display.time_12h(shift.get("start_time"))
    end = regularisation_display.time_12h(shift.get("end_time"))
    span = f"{start} to {end}" if start and end else (start or end or "")
    name = shift.get("shift_name")
    if name and span:
        return f" Your shift: {name}, {span}."
    return f" Your shift: {name or span}." if (name or span) else ""


# erp-api refusing the TIMES because of the employee's shift - "No sessions
# configured for the assigned split shift.", "time is outside your shift",
# "punch out time must be within working hours". QA: the reply was a final
# "Regularization not submitted" card, leaving the employee nowhere to correct
# the times. Only shift/session/timing wording - "Regularization period has
# expired" or "Attendance is locked" are not something the form can fix.
_SHIFT_REFUSAL_RE = re.compile(
    r"\bshifts?\b|\bsessions?\b|\bworking\s+hours?\b|\boffice\s+hours?\b"
    r"|\b(?:in|out|start|end|punch)[\s-]*time\b|\btime\s+(?:range|slot|window)\b",
    re.IGNORECASE)


def _shift_refusal_is_unfixable(error: str | None, shift: dict | None,
                                entry: dict | None) -> bool:
    """True when erp-api refused on shift/timing grounds but the times ALREADY
    fit the session we resolved as this employee's.

    No edit to the form can satisfy a refusal like that, so bringing the form
    back is a loop with no exit - which is exactly what was reported: the
    employee corrected the times, resubmitted, and got the identical message
    every time.

    Live cause, measured against erp-api on 2026-10-08 for a SPLIT shift
    ("QA Team" = "QA 1st" 10:00-14:30 + "QA 2nd" 15:00-20:00):

        15:00-20:00  session 37, the ASSIGNED one      -> 400 refused
        15:30-19:00  session 37, the ASSIGNED one      -> 400 refused
        10:30-14:00  session 36, NOT assigned          -> 200 accepted

    erp-api answers `selected_session_id: 37` when asked which session the
    employee is on, then validates the submission against session 36 anyway.
    So the only times it accepts are hours the employee does not work. That is
    an erp-api defect; nothing this service can send will pass while it
    stands, and pretending otherwise is what produced the loop.

    Deliberately narrow: it needs BOTH a shift/timing refusal AND times that
    already fit. A genuine mismatch - times really outside the shift - still
    returns a correctable refusal and still gets the form, because there the
    employee CAN fix it.
    """
    if not error or not _SHIFT_REFUSAL_RE.search(error):
        return False
    return _within_shift(entry, shift)


def _unfixable_shift_message(error: str, shift: dict | None, entry: dict | None) -> str:
    """What to say instead of "correct the times and submit again".

    Names the real obstacle and who can clear it. Quotes erp-api's own
    sentence verbatim at the end so the employee has something exact to give
    HR, and so the message stays truthful if erp-api's wording changes."""
    start = regularisation_display.time_12h(
        regularisation_display.time_24h((entry or {}).get("start_time")))
    end = regularisation_display.time_12h(
        regularisation_display.time_24h((entry or {}).get("end_time")))
    entered = f"{start} to {end}" if start and end else "the times you entered"
    shift_hint = ""
    if shift:
        s_start = regularisation_display.time_12h(shift.get("start_time"))
        s_end = regularisation_display.time_12h(shift.get("end_time"))
        span = f"{s_start} to {s_end}" if s_start and s_end else ""
        details = ", ".join(x for x in (shift.get("shift_name"), span) if x)
        shift_hint = f" ({details})" if details else ""
    return (
        f"I can't submit this regularization. {entered} is inside the shift I have "
        f"for you{shift_hint}, but the HR system refused it anyway, so there is "
        f"nothing wrong with what you entered for me to ask you to correct. "
        f"If you actually worked different hours that day, tell me the times and "
        f"I'll try again. Otherwise this needs HR - your shift assignment looks "
        f"misconfigured, and no times will go through until it's fixed. The exact "
        f"message from the HR system is: \"{error.strip()}\""
    )


def _shift_correction(error: str, shift: dict | None, entry: dict | None = None) -> dict | None:
    """SlotFlowConfig.correctable_refusal for regularization: the start and end
    time are what the form can fix, and the employee's shift (from
    /shift-details) is what they have to fit."""
    if not error or not _SHIFT_REFUSAL_RE.search(error):
        return None
    shift_hint = ""
    if shift:
        start = regularisation_display.time_12h(shift.get("start_time"))
        end = regularisation_display.time_12h(shift.get("end_time"))
        span = f"{start} to {end}" if start and end else (start or end or "")
        details = ", ".join(x for x in (shift.get("shift_name"), span) if x)
        shift_hint = f" (your shift: {details})" if details else ""
    if _within_shift(entry, shift):
        # The times already fit the shift, so there is nothing in the form to
        # correct. This used to return the form anyway with "correct the times
        # and submit again ... if it keeps happening, contact HR" - and it
        # ALWAYS kept happening, because no times could satisfy it. See
        # _shift_refusal_is_unfixable for the measurement.
        #
        # Returning None hands the turn to slot_flow's final "Sorry, I wasn't
        # able to submit your regularization request" card, which carries
        # _unfixable_shift_message (wired through extract_failure_message) and
        # invites no retry.
        return None
    else:
        message = (f"{error.strip().rstrip('.')}. The start and end time don't match your "
                   f"shift{shift_hint}. Please correct the start (in) time and end (out) time in "
                   f"the form below and submit again - or say **cancel** to stop.")
    return {"fields": ["start_time", "end_time"], "message": message}


def _align_entry_to_shift(entry: dict, shift: dict | None):
    """SlotFlowConfig.align_entry: a typed start/end time outside the
    employee's assigned shift is brought to the shift's edge, and the
    employee is told so. Changes `entry` in place; returns the sentence, or
    None when nothing changed.

    Product rule (QA, Oct 14): "from time is 9:20 AM" on a 9:30 AM - 8:30 PM
    shift is corrected to 9:30 AM rather than sent and refused by erp-api
    ("time must be within shift timing"). Times inside the shift are the
    employee's own and are never touched. A shift that crosses midnight is
    left alone - "outside" has no simple meaning there.
    """
    if not entry or not shift:
        return None
    s_start = regularisation_display.time_24h(shift.get("start_time"))
    s_end = regularisation_display.time_24h(shift.get("end_time"))
    if not (len(str(s_start or "")) == 5 and len(str(s_end or "")) == 5) or s_start >= s_end:
        return None
    start = regularisation_display.time_24h(entry.get("start_time")) if entry.get("start_time") else None
    end = regularisation_display.time_24h(entry.get("end_time")) if entry.get("end_time") else None
    # Reversed times ("in 6:30 PM, out 9:30 AM", QA TC-053) are a mistake for
    # the employee to fix, not a request to reshape: correcting one edge of
    # them invents a span nobody asked for (it became 6:30-8:30 PM and was
    # sent). Left as typed, so erp-api's "out time must be after in time"
    # brings the times back to correct.
    if start and end and start >= end:
        return None
    new_start =s_start if start and len(start) == 5 and not (s_start <= start < s_end) else start
    new_end = s_end if end and len(end) == 5 and not (s_start < end <= s_end) else end
    if (new_start, new_end) == (start, end):
        return None
    t12 = regularisation_display.time_12h
    typed = " – ".join(t12(x) for x in (start, end) if x)
    fixed = " – ".join(t12(x) for x in (new_start, new_end) if x)
    entry["start_time"], entry["end_time"] = new_start or entry.get("start_time"), new_end or entry.get("end_time")
    name = shift.get("shift_name")
    shift_text = f"{name}, {t12(s_start)} – {t12(s_end)}" if name else f"{t12(s_start)} – {t12(s_end)}"
    day = _display_date(entry["date"]) if entry.get("date") else "that day"
    return (f"The time you gave for {day} ({typed}) doesn't match the shift assigned to you "
            f"({shift_text}), so I've corrected it to {fixed}.")


def _within_shift(entry: dict | None, shift: dict | None) -> bool:
    """The entry's start and end both fall inside the shift's span."""
    if not entry or not shift:
        return False
    start = regularisation_display.time_24h(entry.get("start_time"))
    end = regularisation_display.time_24h(entry.get("end_time"))
    s_start = regularisation_display.time_24h(shift.get("start_time"))
    s_end = regularisation_display.time_24h(shift.get("end_time"))
    if not all(len(str(x or "")) == 5 for x in (start, end, s_start, s_end)):
        return False
    return s_start <= start < end <= s_end


# erp-api's field rules the form can fix, besides the shift (QA TC-053/TC-056):
# an out time not after the in time, and a reason that is too long. Each brings
# the form back with ONLY that field to correct - the rest is kept.
_TIME_ORDER_REFUSAL_RE = re.compile(
    r"\b(?:to|end|out)[\s-]*time\b[^.]*\b(?:after|greater|later)\b"
    r"|\b(?:from|start|in)[\s-]*time\b[^.]*\b(?:before|less|earlier)\b", re.IGNORECASE)
_REASON_LENGTH_REFUSAL_RE = re.compile(
    r"\breason\b[^.]*\b(?:characters?|length|too\s+long|greater\s+than|max(?:imum)?|exceed\w*)\b",
    re.IGNORECASE)


def _form_correction(error: str, shift: dict | None, entry: dict | None = None) -> dict | None:
    """SlotFlowConfig.correctable_refusal for regularization: which field(s)
    erp-api's refusal says to fix, and what to tell the employee - or None
    when the form can't fix it (e.g. "Regularization period has expired")."""
    if not error:
        return None
    said = error.strip().rstrip(".")
    if _REASON_LENGTH_REFUSAL_RE.search(error):
        return {"fields": ["reason"],
                "message": (f"{said}. Please shorten the reason in the form below and submit "
                            f"again - the date and times are kept - or say **cancel** to stop.")}
    if _TIME_ORDER_REFUSAL_RE.search(error):
        return {"fields": ["start_time", "end_time"],
                "message": (f"{said}. The end (out) time must be after the start (in) time. "
                            f"Please correct the start and end time in the form below and submit "
                            f"again - the date and reason are kept - or say **cancel** to stop.")}
    return _shift_correction(error, shift, entry)


def _company_now():
    """Company-local date and time (QUOTA_TIMEZONE) - the clock attendance._today
    reads its date from."""
    from zoneinfo import ZoneInfo
    return datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC")))


#: erp-api's own limit on the reason ("The reason may not be greater than 500
#: characters.").
MAX_REASON_LENGTH = 500


_VALID_HHMM_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")


def _invalid_time_problem(entry: dict) -> dict | None:
    """A start or end time that is not a time of day at all. time_24h hands
    unparseable input back unchanged, so "25:00" reached the summary as
    "25:00–18:30" and was offered for submission (negative run, 28 Oct, #25)."""
    bad = []
    for field, label in (("start_time", "start (in)"), ("end_time", "end (out)")):
        raw = entry.get(field)
        if raw and not _VALID_HHMM_RE.match(str(regularisation_display.time_24h(raw) or "")):
            bad.append((field, label, str(raw).strip()))
    if not bad:
        return None
    said = " and ".join(f"the {label} time \"{raw}\"" for _, label, raw in bad)
    return {"fields": [f for f, _, _ in bad],
            "message": (f"{said[0].upper()}{said[1:]} isn't a valid time of day - times run from "
                        f"00:00 to 23:59 (e.g. 09:30 or 6:30 PM). Please correct it in the form "
                        f"below - the date and reason are kept - or say **cancel** to stop.")}


def _pre_submit_problem(entry: dict) -> dict | None:
    """SlotFlowConfig.pre_submit_check: what erp-api would refuse, said before
    sending - a time that isn't a time of day, a reason over its 500-character
    limit, or a time today that hasn't come yet."""
    invalid = _invalid_time_problem(entry)
    if invalid:
        return invalid
    reason = str(entry.get("reason") or "")
    if len(reason) > MAX_REASON_LENGTH:
        return {"fields": ["reason"],
                "message": (f"The reason is {len(reason)} characters - the limit is "
                            f"{MAX_REASON_LENGTH}. Please shorten it in the form below and submit "
                            f"again - the date and times are kept - or say **cancel** to stop.")}
    return _not_yet_happened_today(entry)


def _not_yet_happened_today(entry: dict) -> dict | None:
    """SlotFlowConfig.pre_submit_check: an entry for TODAY whose times have not
    come yet. Live: "today" at 11:03 AM with 3:00-8:00 PM was sent, and erp-api
    refused it after the employee had filled the whole form ("Regularization to
    time must be within shift timing"). Said before sending instead."""
    now = _company_now()
    if str(entry.get("date") or "") != now.date().isoformat():
        return None
    now_hm = now.strftime("%H:%M")
    start = regularisation_display.time_24h(entry.get("start_time"))
    end = regularisation_display.time_24h(entry.get("end_time"))
    now_12 = regularisation_display.time_12h(now_hm)
    if start and start > now_hm:
        return {"fields": ["start_time", "end_time"],
                "message": (f"It's {now_12} now, so {regularisation_display.time_12h(start)} today "
                            f"hasn't come yet - you can only regularize time that has already "
                            f"passed. Please correct the start and end time in the form below, or "
                            f"pick an earlier date - or say **cancel** to stop.")}
    if end and end > now_hm:
        return {"fields": ["end_time"],
                "message": (f"It's {now_12} now, so the end (out) time "
                            f"{regularisation_display.time_12h(end)} today hasn't come yet - you "
                            f"can only regularize time that has already passed. Please correct the "
                            f"end time in the form below, or pick an earlier date - or say "
                            f"**cancel** to stop.")}
    return None


async def _get_attendance_prefill(
    *, bearer_token, date_iso: str, company_id, conversation_id, writer: StreamWriter, employee_name: str | None = None
) -> dict:
    # attendance_known distinguishes the two ways attendance_status_code
    # ends up None, which the eligibility gate below has to tell apart:
    #
    #   False — nothing was read. erp-api was unreachable, timed out, or
    #           answered something this code could not parse. Nobody knows
    #           what that day is, so the gate fails OPEN.
    #   True  — the day WAS read and carries no attendance record at all.
    #           Live-verified (see erp_client.get_attendance_punch_details):
    #           a day with nothing on file comes back 200 with
    #           attendance: null and punch_status "no_records", not 404.
    #           That is an answer, not an absence of one — and the answer is
    #           "there is nothing here to regularize".
    #
    # Conflating the two is what let "apply regularization" -> a date with no
    # attendance record walk straight into "Good news — that day is eligible"
    # and on to collecting a start time, an end time and a reason for a day
    # that has no record to correct.
    empty_preview = {
        "date": date_iso, "shift": None, "lms_punch": [],
        "biometric": None, "exception": "No Punch Recorded", "punch_status": None,
        "attendance_status_code": None, "is_regularized": False,
        "attendance_known": False,
    }

    try:
        writer({"type": "fetching_punch_time", "message": "Checking your punch-in and punch-out times..."})

        result = await attendance_client.get_punch_time(
            bearer_token, company_id=company_id, conversation_id=conversation_id, date=date_iso,
            employee_name=employee_name,
        )

        # Safely unwrap response whether nested inside 'body' or top-level dict
        body = result.get("body") if isinstance(result, dict) and "body" in result else result
        if not isinstance(body, dict) or not body.get("success", True):
            logger.warning("[Graph] punch details API returned failure: %s", result)
            return {"slot_prefill": {}, "preview": empty_preview}

        data = body.get("data") or {}
        punches = data.get("punches") or data.get("sessions") or []
        shift = data.get("shift")
        punch_status = data.get("punch_status")
        # Raw single-letter erp-api day-status code (P/A/PA/WO/...), NOT the
        # punch-completeness "punch_status" above — see
        # _regularization_eligibility_block_reason below, which gates a
        # direct (no attendance/attendance_explain hand-off) regularization
        # request on this being Absent/Half Day Absent, same codes
        # punch_details.py's own comment documents.
        attendance_info = data.get("attendance") or {}
        attendance_status_code = attendance_info.get("attendance")
        # erp-api's own record of whether this day was ALREADY regularized —
        # same field attendance_explain.py's _build_status_reason already
        # reads ("This attendance record was manually regularized."). Gated
        # on below so a second regularization request for the same day is
        # rejected up front instead of walking into asking for a start/end
        # time and a reason erp-api's own post_regularization() would just
        # reject anyway.
        is_regularized = bool(attendance_info.get("is_regularized"))

        exception = _resolve_exception(punch_status, punches)

        # Case-insensitive: _resolve_exception above already lowercases when
        # deciding the "None" label, so an exact-case comparison here could
        # show the user "exception: None" (implying nothing to worry about)
        # while silently NOT auto-filling anything if erp-api ever returns
        # punch_status as "Complete" or another case variant — confirmed
        # live, a real mismatch between the two checks.
        is_complete = bool(punch_status) and punch_status.lower() == _COMPLETE_STATUS

        if is_complete and len(punches) > 1:
            # Multiple complete sessions (split shift) — erp-api's status is
            # genuinely "complete" so the plain exception label would read
            # "None", but auto-fill (below) can't populate a single
            # start/end pair from more than one session. Make that explicit
            # instead of leaving the user to wonder why nothing got filled
            # in on an apparently-fine day.
            exception = "Multiple Sessions — review times manually"

        preview = {
            "date": date_iso,
            "shift": {
                "name": shift.get("name"),
                "start_time": regularisation_display.time_24h(shift.get("start_time")),
                "end_time": regularisation_display.time_24h(shift.get("end_time")),
            } if shift else None,
            "lms_punch": [_session_display(p, date_iso) for p in punches],
            "biometric": None,
            "exception": exception,
            "punch_status": punch_status,
            "attendance_status_code": attendance_status_code,
            "is_regularized": is_regularized,
            # erp-api answered, so whatever it says about this day is known —
            # including saying there is no record for it.
            "attendance_known": True,
        }

        slot_prefill = {}
        if is_complete and len(punches) == 1:
            p = punches[0]
            check_in_dt = _extract_punch_datetime(p.get("check_in"))
            check_out_dt = _extract_punch_datetime(p.get("check_out"))
            if check_in_dt:
                slot_prefill["start_time"] = check_in_dt.strftime("%H:%M")
            if check_out_dt:
                slot_prefill["end_time"] = check_out_dt.strftime("%H:%M")

        logger.info(
            "[Graph] attendance prefill for %s: punch_status=%s punches=%d slot_prefill=%s",
            date_iso, punch_status, len(punches), slot_prefill,
        )

        return {"slot_prefill": slot_prefill, "preview": preview}

    except attendance_client.ErpApiTimeout:
        logger.warning("[Graph] punch details timeout for %s", date_iso)
        writer({"type": "punch_time_warning",
                "message": "I couldn't retrieve your punch times. I'll ask you for them instead."})
        return {"slot_prefill": {}, "preview": empty_preview}

    # ErpApiUnauthorized is a SUBCLASS of ErpApiUnavailable (see
    # erp_client.py) — must be caught first, or the general clause below
    # silently swallows every 401 into the wrong message.
    except attendance_client.ErpApiUnauthorized:
        # erp-api refused the caller's token. Every later call in this flow —
        # the submit included — will be refused the same way, so the flow
        # stops here (session_rejected) instead of collecting a start time,
        # an end time and a reason that can never be submitted. Live: the
        # details were all collected, then "yes" answered "your session has
        # expired".
        logger.warning("[Graph] punch details request unauthorized for %s", date_iso)
        return {"slot_prefill": {}, "preview": {**empty_preview, "session_rejected": True}}

    except attendance_client.ErpApiUnavailable:
        logger.warning("[Graph] punch details unavailable for %s", date_iso)
        writer({"type": "punch_time_warning",
                "message": "I couldn't reach the HR system for your punch details, so I'll just ask you for the times instead."})
        return {"slot_prefill": {}, "preview": empty_preview}

    except Exception as e:
        logger.exception("[Graph] unexpected punch details error for %s: %s", date_iso, e)
        return {"slot_prefill": {}, "preview": empty_preview}


# ---------------------------------------------------------------------------
# Direct-entry eligibility gate
# ---------------------------------------------------------------------------
#
# attendance_node/attendance_explain_node already gate their own "would you
# like to regularize this?" offer on the day's status being Absent/Half Day
# Absent BEFORE ever seeding a pending regularization entry (see
# attendance.py's _is_regularizable/_seed_pending_regularization and
# attendance_explain.py's _ADVERSE_ATTENDANCE_STATUSES) — those entries are
# marked "_prevalidated" (see attendance.py) so the STATUS check below doesn't
# re-run for them (the back-date window still does — neither hand-off looks
# at regularization_allowed_days). The gap this closes is a regularization request that
# NEVER went through either of those nodes at all — e.g. "I want to apply
# for regularization for 5 September" typed directly — which used to walk
# straight into asking for start/end time and a reason with no check at all
# that the day was even eligible.
#
# All three checks (already-regularized, status, window — see
# _regularization_eligibility_block_reason below) are advisory, same
# discipline as the rest of this file's own punch-prefill fetch: they fail
# OPEN (never block) when the data needed to decide isn't available (an
# unreachable HR system, a response missing the expected field) — erp-api's
# own post_regularization() call remains the real authority regardless of
# what these three say.

_REGULARIZABLE_ATTENDANCE_CODES = {"A", "PA"}

# Best-effort display labels for erp-api's raw single-letter day-status
# codes — falls back to the raw code itself for anything not listed here
# rather than guessing, since this codebase has no confirmed full mapping.
_ATTENDANCE_CODE_LABELS = {
    "P": "Present", "A": "Absent", "PA": "Half Day Absent",
    "WO": "Week Off", "HD": "Holiday", "L": "On Leave",
}


def _already_regularized_block_reason(date_iso: str, is_regularized: bool) -> str | None:
    """None means "not blocked". Checked ahead of (and regardless of)
    "_prevalidated" in _regularization_eligibility_block_reason below — a day
    erp-api already has a regularization record for is never valid to submit
    again, no matter which path (direct entry or an attendance/attendance_
    explain hand-off) found the date."""
    if not is_regularized:
        return None
    return (
        f"Regularisation has already been applied for {_display_date(date_iso)} "
        f"— you can't submit another request for the same day."
    )


def _attendance_status_block_reason(date_iso: str, attendance_status_code: str | None,
                                     attendance_known: bool = False) -> str | None:
    """None means "not blocked" — the day IS Absent/Half Day Absent, or
    nothing could be read about it at all (fail open, per this section's
    docstring).

    attendance_known says which kind of "no status code" this is. A day
    erp-api HAS answered for and that carries no attendance record is
    blocked: there is no record to correct, so walking on to ask for a start
    time, an end time and a reason produces a request about nothing. A day
    nothing could be read for still fails open, because refusing there would
    be an outage refusing a legitimate request.

    Defaults to False so any caller that hasn't been taught about the flag
    keeps the old fail-open behaviour rather than silently starting to
    refuse.
    """
    if not attendance_status_code:
        if attendance_known:
            return (
                f"I can't regularize {_display_date(date_iso)} — there's no attendance "
                f"record for that day. Regularization is only available for a day marked "
                f"Absent or Half Day Absent. Could you give me a different date instead?"
            )
        return None
    if attendance_status_code in _REGULARIZABLE_ATTENDANCE_CODES:
        return None
    label = _ATTENDANCE_CODE_LABELS.get(attendance_status_code, attendance_status_code)
    return (
        f"I can't regularize {_display_date(date_iso)} — that day is marked "
        f"**{label}**. Regularization is only available for a day marked "
        f"Absent or Half Day Absent. Could you give me a different date instead?"
    )


async def _get_regularization_settings(
    *, bearer_token, company_id, conversation_id,
) -> dict:
    """The regularization settings from ONE /leave/balance call:

        {"available": bool,          False = the call failed / unusable answer
         "window_days": int | None,  regularization_allowed_days
         "limit": int | None,        the policy's max_apply_in_month
         "cycle": PayrollCycle | None}

    The window comes from the regularization policy entry first (moved to
    leave_settings.regularization_policy by erp_client.get_leave_balance),
    then the top-level leave_settings key.

    NOT regularization_limit. It used to be the window's second fallback, but
    it is the monthly REQUEST quota ("10", the same figure as the policy's
    max_apply_in_month), not a number of days — reading it as the window
    would enforce a 10-day window on a tenant with no allowed_days set."""
    unavailable = {"available": False, "window_days": None, "limit": None, "cycle": None}
    try:
        result = await attendance_client.get_leave_balance(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
        )
    except (attendance_client.ErpApiTimeout, attendance_client.ErpApiUnavailable):
        logger.warning("[Graph] regularization settings lookup failed for company=%s", company_id)
        return unavailable

    body = result.get("body") if isinstance(result, dict) else None
    if not isinstance(body, dict) or not body.get("success", True):
        return unavailable

    data = body.get("data") or {}
    settings = data.get("leave_settings") or {}
    policy = settings.get("regularization_policy") or {}

    window_days = None
    for value in (policy.get("regularization_allowed_days"),
                  settings.get("regularization_allowed_days")):
        days = _as_non_negative_int(value)
        if days is not None:
            window_days = days
            break

    return {
        "available": True,
        "window_days": window_days,
        "limit": _as_non_negative_int(policy.get("max_apply_in_month")),
        "cycle": payroll_cycle.from_balance_data(data),
    }


def _as_non_negative_int(value) -> int | None:
    if value is None:
        return None
    try:
        number = int(str(value).strip())
    except (TypeError, ValueError):
        return None
    return number if number >= 0 else None


async def _get_regularization_window_days(
    *, bearer_token, company_id, conversation_id,
) -> int | None:
    """regularization_allowed_days, or None — "no window to enforce" — on
    anything that isn't a clean non-negative integer, including an
    unreachable HR system. See _get_regularization_settings."""
    settings = await _get_regularization_settings(
        bearer_token=bearer_token, company_id=company_id, conversation_id=conversation_id,
    )
    return settings["window_days"]


# ---------------------------------------------------------------------------
# Quota check (HA-697 AC-05) — step 3 of Duplicate > Eligibility > Quota
# ---------------------------------------------------------------------------
#
# The limit is the regularization policy's max_apply_in_month; "month" is the
# company's payroll cycle (services/payroll_cycle.py) — for this tenant the
# 21st to the 20th — taken from /leave/balance's payroll_cycle, never a
# calendar month worked out here. Used = the caller's own Pending + Approved
# requests (product decision) whose date falls in the cycle of the date being
# requested, counted from the SAME rows the duplicate-date check fetched.
#
# Fails CLOSED when the settings lookup failed (AC-12). A policy with no
# limit, or a balance answer with no payroll_cycle, has nothing to enforce
# and passes: erp-api's submission still revalidates the quota (AC-09).

QUOTA_OK = "ok"
QUOTA_EXHAUSTED = "exhausted"
QUOTA_NOT_ENFORCED = "not_enforced"
QUOTA_UNAVAILABLE = "unavailable"


def _check_quota(date_iso: str, rows: list | None, settings: dict) -> dict:
    """{"outcome": QUOTA_*, "message": str | None, "used", "limit", "cycle"}.
    message is the whole reply for EXHAUSTED/UNAVAILABLE and a one-line
    summary ("Quota available: 1 of 2 used for Sep 2026.") for OK."""
    def result(outcome, message=None, used=None, cycle=None):
        return {"outcome": outcome, "message": message, "used": used,
                "limit": settings.get("limit"),
                "cycle": cycle.as_dict() if cycle else None}

    if not settings.get("available") or rows is None:
        return result(QUOTA_UNAVAILABLE, (
            f"I couldn't check your regularization quota for {_display_date(date_iso)}, "
            f"so I can't continue. Nothing has been submitted. You can try again, or "
            f"apply using the regularization form instead."
        ))

    limit = settings.get("limit")
    try:
        day = datetime.strptime(date_iso, "%Y-%m-%d").date()
    except (TypeError, ValueError):
        return result(QUOTA_NOT_ENFORCED)
    cycle = payroll_cycle.cycle_for(settings.get("cycle"), day)
    if limit is None or cycle is None:
        logger.info("[Graph] regularisation quota not enforced for %s (limit=%s, cycle=%s)",
                    date_iso, limit, settings.get("cycle"))
        return result(QUOTA_NOT_ENFORCED)

    used = regularisation_display.count_quota_used(rows, cycle)

    if used >= limit:
        return result(QUOTA_EXHAUSTED, (
            f"Your regularization quota for {cycle.label()} has been used "
            f"({used} of {limit}), so I can't take a new request for "
            f"{_display_date(date_iso)}."
        ), used=used, cycle=cycle)
    return result(QUOTA_OK, f"Quota available: {used} of {limit} used for {cycle.label()}.",
                  used=used, cycle=cycle)


def _quota_check_data(quota: dict) -> dict:
    data = {"quota_check": {k: quota.get(k) for k in ("outcome", "used", "limit", "cycle")}}
    if quota["outcome"] == QUOTA_UNAVAILABLE:
        data["check_unavailable"] = True
        data["retry_available"] = True
        data["form_fallback"] = True
    return data


def _future_date_block_reason(date_iso: str, today: date) -> str | None:
    """None means "not blocked". Deterministic, no API call — checked by
    regularisation_eligibility_node BEFORE the two API-backed checks below,
    so a future date is reported as intent "regularisation_classify" /
    regularisation_classification_status=false directly, the same shape
    every other classification outcome uses, instead of silently falling
    through to regularisation_node's own (differently-shaped,
    "regularization_incomplete") reject_future_dates handling in
    slot_flow.py. That handling still exists and still fires for a future
    date introduced later, mid-flow, correcting an already-in-progress
    entry — this is only about the classify gate's OWN first look at a
    date, kept consistent with its other three outcomes."""
    try:
        record_date = datetime.strptime(date_iso, "%Y-%m-%d").date()
    except (TypeError, ValueError):
        return None
    if record_date <= today:
        return None
    return regularisation_display.future_date_message(
        _display_date(date_iso), _display_date(today.strftime('%Y-%m-%d')))


def _regularization_window_block_reason(date_iso: str, window_days: int | None, today: date) -> str | None:
    if window_days is None:
        return None
    try:
        record_date = datetime.strptime(date_iso, "%Y-%m-%d").date()
    except (TypeError, ValueError):
        return None
    # Strictly LESS than the allowed days, as erp-api counts it: the portal
    # answered "Regularization period has expired" for 9 Sep asked on 29 Sep
    # (20 days back, regularization_allowed_days 20), while this check let it
    # through (<=) and the AI submit route refused it on a different rule.
    if (today - record_date).days < window_days:
        return None
    # Opens with erp-api's own wording for this rule ("Regularization period
    # has expired"), so the pre-check and a refusal from the submit itself
    # read the same.
    return (
        f"Regularization period has expired for {_display_date(date_iso)} — you "
        f"can only regularize dates within the last {window_days} "
        f"day{'s' if window_days != 1 else ''}. Could you give me a more "
        f"recent date instead?"
    )


async def _regularization_eligibility_block_reason(
    entry: dict, attendance_status_code: str | None, is_regularized: bool = False,
    *, bearer_token, company_id, conversation_id, attendance_known: bool = False,
    settings: dict | None = None,
) -> str | None:
    """Entry point for the three checks above.

    The already-regularized check and the back-date WINDOW run for every
    entry. Only the attendance-status check is skipped for a "_prevalidated"
    entry: that flag means attendance_node/attendance_explain_node already
    confirmed the day is Absent/Half Day Absent, which is all they check.

    The window used to be skipped with it. Neither hand-off looks at
    regularization_allowed_days, so "show my attendance for 1 Aug" -> "you
    were absent, regularize it?" -> "yes" walked into collecting details for
    a date far outside the allowed back-dated period. The "apply now" seed is
    "_prevalidated" too: live, a date 20 days back entered that way skipped
    the window, collected every detail, and was refused by erp-api at submit."""
    date_iso = entry.get("date")
    if not date_iso:
        return None

    reason = _already_regularized_block_reason(date_iso, is_regularized)
    if reason:
        return reason

    if not entry.get("_prevalidated"):
        reason = _attendance_status_block_reason(
            date_iso, attendance_status_code, attendance_known=attendance_known)
        if reason:
            return reason

    # settings: already fetched by a caller that also runs the quota check,
    # so one /leave/balance call serves both.
    if settings is not None:
        window_days = settings.get("window_days")
    else:
        window_days = await _get_regularization_window_days(
            bearer_token=bearer_token, company_id=company_id, conversation_id=conversation_id,
        )
    return _regularization_window_block_reason(date_iso, window_days, attendance_mod._today())


# ---------------------------------------------------------------------------
# Duplicate-date check (HA-697 AC-03) — step 1 of Duplicate > Eligibility > Quota
# ---------------------------------------------------------------------------
#
# Reads the caller's own requests from GET /api/v1/ai/regularizations (every
# status) and looks for one already on the date. Runs BEFORE every other
# check, on every path a date enters the flow: the classify gate's first look
# (regularisation_eligibility_node) and _fetch_prefill for a date changed
# mid-flow or handed off by attendance_node/attendance_explain_node.
#
# Unlike the eligibility checks below, this one fails CLOSED (AC-12): a lookup
# that could not complete stops the flow rather than assuming "no duplicate".
#
# erp-api returns the existing request's status but no "new request allowed"
# flag, so which statuses block is the one piece of policy this layer holds.
# It lives in these two sets and nowhere else, so it can be swapped for an
# erp-api flag without touching the flow. A status in neither set (one
# erp-api adds later) blocks: guessing that it allows a new request could
# create a duplicate.
_DUPLICATE_BLOCKING_STATUSES = {"pending", "approved"}
_DUPLICATE_PASSTHROUGH_STATUSES = {"rejected", "cancelled", "withdrawn"}

DUPLICATE_NONE = "none"
DUPLICATE_PRIOR = "prior"            # earlier request exists, a new one is allowed
DUPLICATE_BLOCKED = "blocked"        # Pending/Approved (or unknown) — stop
DUPLICATE_UNAVAILABLE = "unavailable"  # lookup failed — stop, offer retry/form


def _regularization_status_name(row: dict) -> str | None:
    """status_name lowercased ("canceled" folded to "cancelled"), falling back
    to the numeric code (0 pending, 1 approved) for a row with no name."""
    return regularisation_display.status_key(row)


def _status_label(status: str | None) -> str:
    if status == "pending":
        return "Pending approval"
    return (status or "unknown").replace("_", " ").title()


def _ref_suffix(row: dict) -> str:
    ref = regularisation_display.reference_id(row)
    return f" (Ref: {ref})" if ref else ""


def _duplicate_unavailable_message(date_iso: str, exc: Exception | None = None) -> str:
    if isinstance(exc, attendance_client.ErpApiUnauthorized):
        return "Sorry, your session has expired — please log in again to continue."
    return (
        f"I couldn't check whether you already have a regularization request "
        f"for {_display_date(date_iso)}, so I can't continue. Nothing has been "
        f"submitted. You can try again, or apply using the regularization form instead."
    )


async def _check_duplicate_date(
    date_iso: str, *, bearer_token, company_id, conversation_id,
) -> dict:
    """{"outcome": DUPLICATE_*, "message": str | None, "existing_request": row | None,
    "rows": every row erp-api returned | None}.

    rows is None only for DUPLICATE_UNAVAILABLE; the quota check (step 3)
    counts from it rather than fetching the same list again.

    message is None only for DUPLICATE_NONE. For DUPLICATE_PRIOR it is a
    notice to show ahead of whatever the next check says; for BLOCKED and
    UNAVAILABLE it is the whole reply. Never raises."""
    def unavailable(exc=None):
        return {"outcome": DUPLICATE_UNAVAILABLE, "existing_request": None, "rows": None,
                "message": _duplicate_unavailable_message(date_iso, exc)}

    try:
        result = await attendance_client.get_my_regularizations(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
        )
    except (attendance_client.ErpApiTimeout, attendance_client.ErpApiUnavailable) as exc:
        logger.warning("[Graph] regularisation duplicate-date check failed for %s: %s", date_iso, exc)
        return unavailable(exc)
    except Exception:
        logger.exception("[Graph] regularisation duplicate-date check crashed for %s", date_iso)
        return unavailable()

    body = result.get("body") if isinstance(result, dict) else None
    http_status = result.get("http_status") if isinstance(result, dict) else None
    if (not isinstance(body, dict) or not body.get("success", True)
            or (http_status is not None and http_status >= 400)):
        logger.warning("[Graph] regularisation duplicate-date check answered %s: %s", http_status, body)
        return unavailable()

    rows = (body.get("data") or {}).get("regularizations")
    if not isinstance(rows, list):
        return unavailable()

    # Enriched so the existing-request card (AC-03) has its Ref ID, type,
    # applied-on and status label ready — see regularisation_display.
    same_date = regularisation_display.enrich_rows([
        r for r in rows
        if isinstance(r, dict) and str(r.get("apply_date") or "")[:10] == date_iso
    ])
    if not same_date:
        return {"outcome": DUPLICATE_NONE, "message": None, "existing_request": None,
                "rows": rows}

    # Newest first, so the request a Pending/Approved reply names is the
    # latest one on the date.
    same_date.sort(key=lambda r: _as_sortable_id(r.get("regularization_id")), reverse=True)
    blocking = next(
        (r for r in same_date
         if _regularization_status_name(r) not in _DUPLICATE_PASSTHROUGH_STATUSES),
        None,
    )
    # Figma ("You already have a request for this date"): the date as
    # 12-Sep-2026 and one sentence. The existing request's details (type,
    # applied on, reason) are on the existing-request card, not in the sentence
    # - see _existing_request_card.
    display = regularisation_display.display_date(date_iso) or _display_date(date_iso)

    if blocking is not None:
        status = _regularization_status_name(blocking)
        if status == "approved":
            message = f"Your request for {display} is already Approved{_ref_suffix(blocking)}."
        elif status == "pending":
            message = (
                f"You've already applied for regularization on {display}, currently "
                f"Pending approval{_ref_suffix(blocking)}."
            )
        else:
            message = (
                f"You already have a regularization request for {display}"
                f"{_ref_suffix(blocking)}, with status {_status_label(status)}, "
                f"so I can't start a new one for this date."
            )
        return {"outcome": DUPLICATE_BLOCKED, "message": message, "existing_request": blocking,
                "rows": rows}

    earlier = same_date[0]
    # QA TC-025: "shows reason if backend returns it" - why it was rejected
    # (or cancelled) is what the employee needs before applying again.
    why = str(earlier.get("rejection_reason") or earlier.get("cancel_reason") or "").strip().rstrip(".")
    message = (
        f"Your earlier request for {display}{_ref_suffix(earlier)} was "
        f"{_status_label(_regularization_status_name(earlier))}"
        f"{f' (reason: {why})' if why else ''}, so a new request is allowed."
    )
    return {"outcome": DUPLICATE_PRIOR, "message": message, "existing_request": earlier,
            "rows": rows}


def _as_sortable_id(value) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):
        return -1


def _existing_request_card(row: dict) -> dict:
    """The "Existing request REG-…" card's fields, from erp-api's row
    (enriched by regularisation_display)."""
    ref = row.get("reference_id") or regularisation_display.reference_id(row)
    return {
        "title": f"Existing request {ref}",
        "reference_id": ref,
        "date": row.get("apply_date_display") or regularisation_display.display_date(row.get("apply_date")),
        "regularization_type": row.get("regularization_type"),
        "status": row.get("card_status_label") or regularisation_display.card_status_label(row),
        "status_key": regularisation_display.status_key(row),
        "applied_on": row.get("applied_on_display"),
        "reason": row.get("reason"),
        "rejection_reason": row.get("rejection_reason"),
        "cancel_reason": row.get("cancel_reason"),
    }


def _duplicate_check_data(duplicate: dict) -> dict:
    """Response-data fields describing the check, so a UI can render the
    existing-request card (AC-03) or the retry/form offer (AC-12) without
    parsing the sentence."""
    outcome = duplicate["outcome"]
    data = {"duplicate_check": {
        "outcome": outcome,
        "existing_request": duplicate.get("existing_request"),
    }}
    existing = duplicate.get("existing_request")
    if outcome in (DUPLICATE_BLOCKED, DUPLICATE_PRIOR) and existing:
        # Figma: a notice ("You already have a request for this date") above an
        # "Existing request REG-…" card (Date, Regularization type, Status,
        # Applied on) with a "View in Requests" button.
        data["title"] = ("You already have a request for this date" if outcome == DUPLICATE_BLOCKED
                         else "You have an earlier request for this date")
        data["existing_request_card"] = _existing_request_card(existing)
        data["actions"] = [{"label": "View in Requests", "action": "view_requests"}]
    if outcome == DUPLICATE_UNAVAILABLE:
        data["check_unavailable"] = True
        data["retry_available"] = True
        data["form_fallback"] = True
    return data


# ---------------------------------------------------------------------------
# Submit
# ---------------------------------------------------------------------------

async def _submit(merged: dict, *, bearer_token, company_id, conversation_id) -> dict:
    payload = {
        "apply_date": merged["date"],
        # 24-hour "HH:MM" whatever filled the entry (form, typed reply, model).
        "from_time": regularisation_display.time_24h(merged["start_time"]),
        "to_time": regularisation_display.time_24h(merged["end_time"]),
        "reason": merged["reason"],
    }
    if merged.get("employee_name"):
        payload["employee_name"] = merged["employee_name"]

    return await attendance_client.post_regularization(
        bearer_token, payload=payload, company_id=company_id, conversation_id=conversation_id,
    )


SESSION_REJECTED_MESSAGE = "Sorry, your session has expired — please log in again to continue."


def _map_exception(exc: Exception):
    if isinstance(exc, attendance_client.ErpApiTimeout):
        return "I couldn't reach the HR system in time — please try again in a moment."
    # ErpApiUnauthorized is a SUBCLASS of ErpApiUnavailable (see
    # erp_client.py) — must be checked first, or the isinstance check below
    # matches it too and returns the wrong message.
    if isinstance(exc, attendance_client.ErpApiUnauthorized):
        return SESSION_REJECTED_MESSAGE
    if isinstance(exc, attendance_client.ErpApiUnavailable):
        # erp-api ANSWERED with a refusal ("Regularization period has
        # expired", "Attendance is locked for this date. Contact HR.") on a
        # status _request doesn't hand back as data. Its own sentence is the
        # reply (AC-09: "the assistant shows the backend-provided reason");
        # "unable to reach the HR system" would blame an outage for a rule.
        if exc.erp_message:
            return exc.erp_message
        return "I'm unable to reach the HR system right now — please try again shortly."
    return None


# ---------------------------------------------------------------------------
# Prompt
# ---------------------------------------------------------------------------

def _build_day_of_week_table(today: date, days_back: int = 21, days_forward: int = 7) -> str:
    """A literal date -> weekday-name lookup table for the surrounding ~4
    weeks, injected into the prompt so the LLM can LOOK UP which date a
    weekday name means instead of computing it — confirmed live and
    repeatedly wrong when left to compute it itself (e.g. "Monday and
    Tuesday" resolved to a Saturday and a Sunday; "last week Monday"
    resolved to a date two weeks out that wasn't even a Monday). This
    codebase already learned this lesson elsewhere (see
    attendance_explain.py's deterministic weekday resolver) — this prompt
    is the one place date math was still being left to the model itself."""
    lines = []
    for offset in range(-days_back, days_forward + 1):
        d = today + timedelta(days=offset)
        tag = " <- TODAY" if offset == 0 else ""
        lines.append(f"{d.isoformat()} {d.strftime('%A')}{tag}")
    return "\n".join(lines)


def _build_detected_dates_block(query: str, today: date) -> str:
    """Deterministically pre-resolves any explicit numeric (DD/MM(/YYYY))
    or day+named-month date(s) mentioned in the CURRENT message — the same
    closed, unambiguous shape attendance.py's own deterministic layer
    resolves for the plain attendance/attendance_explain/punch_details
    flows — and hands the LLM the already-computed ISO date(s) to use
    verbatim. Same "look it up, don't compute" approach as the
    DAY-OF-WEEK REFERENCE TABLE above (see its docstring): without this,
    the LLM has to get day-first-not-month-first and current-year-when-
    absent right on its own every time, and this family of date-extraction
    prompts has repeatedly shown that's not reliable (observed bug: a
    year-less explicit date silently defaulting to today's date).

    Also runs the query through date_query_resolver.resolve() — the same
    shared deterministic layer attendance.py/attendance_explain.py/
    punch_details.py all use for weekday names, "yesterday", "last week
    Wednesday", etc. — and adds its result as one more verbatim hint when
    it confidently resolves to a SINGLE date. Deliberately NOT used to
    replace the DAY-OF-WEEK REFERENCE TABLE/LLM path entirely: that
    resolver returns exactly one date per call, so a message naming
    several dates at once ("Monday and Tuesday") would silently lose every
    date but the first if this were the only resolution path — the LLM +
    day-of-week table stays authoritative for multi-date messages, this is
    purely an extra, higher-confidence signal for the common single-date
    case."""
    seen = set()
    resolved_pairs = []

    for m in attendance_mod._ATTENDANCE_EXPLICIT_NUMERIC_DATE_RE.finditer(query):
        resolved = attendance_mod._resolve_explicit_date_symbolic(
            int(m.group(1)), int(m.group(2)), m.group(3), today,
        )
        if resolved and m.group(0) not in seen:
            seen.add(m.group(0))
            resolved_pairs.append((m.group(0), resolved["explicit_date"]))

    for pattern in (
        attendance_mod._ATTENDANCE_DAY_THEN_MONTH_RE,
        attendance_mod._ATTENDANCE_MONTH_THEN_DAY_RE,
    ):
        for m in pattern.finditer(query):
            if m.group(0) in seen:
                continue
            g1, g2, year_str = m.group(1), m.group(2), m.group(3)
            if g1.isdigit():
                day, month_word = int(g1), g2.lower()
            else:
                month_word, day = g1.lower(), int(g2)
            month = attendance_mod._MONTH_NAMES.get(month_word)
            if not month:
                continue
            resolved = attendance_mod._resolve_explicit_date_symbolic(day, month, year_str, today)
            if resolved:
                seen.add(m.group(0))
                resolved_pairs.append((m.group(0), resolved["explicit_date"]))

    # Extra deterministic pass — see this function's own docstring for why
    # only a SINGLE-date result is taken (never "range", never
    # NoSuchOrdinalWeekday): those ambiguous/multi-day cases are left to
    # the day-of-week table + LLM path exactly as before, unchanged.
    #
    # Also skipped outright when the message names more than one weekday
    # ("Monday and Tuesday") — date_query_resolver.resolve() only returns
    # ONE date for the whole string (Monday's), and labeling that as "this
    # message resolves to 2026-09-07" would misleadingly suggest there's
    # only one date to extract, biasing the LLM to drop Tuesday entirely.
    # Safer to add nothing and let the day-of-week table (which the LLM's
    # own multi-date rules already handle correctly) resolve every weekday
    # named, exactly as before.
    weekday_mentions = sum(
        1 for w in date_query_resolver.WEEKDAYS
        if re.search(rf"\b{w}\b", query, re.IGNORECASE)
    )
    already_resolved_isos = {iso for _, iso in resolved_pairs}
    if weekday_mentions <= 1:
        shared_resolved = date_query_resolver.resolve(query, today)
        if isinstance(shared_resolved, dict) and shared_resolved.get("type") == "single":
            iso = shared_resolved["date"].isoformat()
            if iso not in already_resolved_isos:
                resolved_pairs.append((query.strip(), iso))

    if not resolved_pairs:
        return ""

    lines = "\n".join(f'- "{text}" -> {iso}' for text, iso in resolved_pairs)
    return f"""
The following date(s) mentioned in the CURRENT message have ALREADY been
resolved (day-first, current year assumed if none was stated) — use these
EXACT ISO values verbatim for that date, do NOT recompute or reinterpret
them:
{lines}
"""


def _build_prompt(
    query: str,
    existing_slots: dict,
    today: date,
    candidate_dates: list[str] | None = None,
) -> str:

    today_str = today.strftime("%Y-%m-%d")
    today_day = today.strftime("%A")
    day_of_week_table = _build_day_of_week_table(today)
    detected_dates_block = _build_detected_dates_block(query, today)

    existing_entries = existing_slots.get("entries") or []

    existing_str = (
        "\n".join(
            f"- date={e.get('date')}, start_time={e.get('start_time')}, "
            f"end_time={e.get('end_time')}, reason={e.get('reason')}"
            for e in existing_entries
        )
        or "none yet"
    )

    candidates_block = ""
    if candidate_dates:
        candidates_str = ", ".join(candidate_dates)
        candidates_block = f"""
The employee was previously offered a choice between these candidate
dates (none confirmed yet): {candidates_str}
If the message names one of these dates (or a day name that clearly
matches one of them), treat it as selecting that date for a new entry.
"""

    return f"""You are helping fill out one or more attendance regularization
requests through a multi-turn conversation. Today's date is {today_str}
({today_day}).

DAY-OF-WEEK REFERENCE TABLE — use this to find which date a weekday name
means. Do NOT calculate it yourself; look it up here:
{day_of_week_table}
{detected_dates_block}
Entries already collected so far (one per date):
{existing_str}
{candidates_block}
Some start_time/end_time values may have been automatically retrieved from
the employee's attendance punch records — treat those as valid collected
values already present above.

Read the employee's latest message and output ONLY a JSON object:

{{
  "action": "provide_info" | "confirm" | "cancel",
  "entries": [
    {{
      "date": "YYYY-MM-DD" or null,
      "start_time": "HH:MM" or null,
      "end_time": "HH:MM" or null,
      "reason": "<short reason text>" or null
    }}
  ],
  "employee_name": "<name>" or null
}}

Rules:

- If the message mentions MULTIPLE dates (e.g. "Monday and Tuesday"),
  output ONE entry per date, each resolved to an absolute YYYY-MM-DD
  against {today_str}.
- If the message names an explicit date (a weekday name, "yesterday",
  "today", an explicit date, or one of the pre-resolved dates above) that
  is DIFFERENT from every date already collected below, that is a NEW
  entry for THAT date — never fold the message's time/reason into an
  already-collected entry for a different date just because only one
  entry happens to be pending. A pending entry stays exactly as it was
  (untouched, still incomplete) unless the message's own date matches it.
- Only include an entry in "entries" for a date if THIS message mentions
  or changes something for that date (a new date, a time, or a reason).
  Do NOT repeat entries from "already collected" that this message
  doesn't touch.
- If the message gives one reason but multiple dates, apply that same
  reason to every new entry for those dates.
- If the message gives one time range but multiple dates, apply it to
  every new entry for those dates, unless different times are given per
  date.
- If the employee explicitly provides a different start or end time for
  a date that's already collected, output an entry with that date and
  the new value(s) — the flow will overwrite the previous value for that
  date. Explicit values always take precedence over automatically
  retrieved punch values.
- If the message provides ONLY time(s) and/or a reason, with NO date
  mentioned or implied anywhere in the message, you MUST still output
  exactly one entry for it, with "date": null. This applies equally
  whether the message gives a time, a reason, or both — never omit the
  entry entirely just because there's no date. Do NOT guess which
  existing entry it belongs to — that is handled outside this prompt.
- NEVER default an unmentioned date to today's date ({today_str}) just
  because no date was given. Only use {today_str} as an entry's date if
  the employee's message actually says "today" or otherwise clearly
  refers to the current date.
- "cancel" ONLY if the message explicitly asks to stop/abandon/withdraw
  the request — e.g. "cancel", "never mind", "forget it", "stop", "don't
  bother", "no don't submit it", "not now", or a bare "no"/"nope"/"nah"
  declining the request. A short acknowledgment like "ok", "okay",
  "alright", "fine", "sure", "got it" is NEVER a cancel — treat it as
  "provide_info" with empty entries (the employee is just acknowledging,
  not answering or cancelling).
- "confirm" ONLY if the message is a clear affirmative meant to submit
  the request as currently collected (e.g. "yes submit it", "go ahead",
  "confirm"). A message can ALSO correct/add entry details in the SAME
  breath as confirming (e.g. "date: 18/08/2026, time: 9am to 10pm, confirm
  and submit") — when it does, still extract those details into "entries"
  exactly as you would for "provide_info" AND set "action":"confirm"; do
  NOT drop the entry details just because the message also confirms.
- If the message contains no new date/time/reason information AND is
  not a clear confirm or explicit cancel, use "provide_info" with
  "entries": [] — do not guess.
- Resolve relative dates (today/yesterday/Monday/Tuesday/last week's
  Wednesday/etc.) using the DAY-OF-WEEK REFERENCE TABLE above — look the
  date up, do not compute it.
- Any slash- or dash-separated numeric date (e.g. "10/08/2026",
  "05-03-2026") is DD/MM/YYYY (day first), NEVER MM/DD/YYYY — this
  applies even when both numbers are <= 12 and the format looks
  ambiguous. Do NOT default to US month-first convention.
  - "10/08/2026" -> "2026-08-10" (10th of August, NOT October 8th)
  - "05-03-2026" -> "2026-03-05" (5th of March, NOT May 3rd)
- A date with NO year stated — either numeric ("12-08", "21/07") or a
  named-month day ("23 aug", "12 August") — is still DD/MM (day first for
  the numeric form) and uses {today_str}'s year ({today.year}), never left
  null and never defaulted to today's date:
  - "12-08" -> "{today.year}-08-12" (12th of August THIS year)
  - "23 aug" -> "{today.year}-08-23" (23rd of August THIS year)
- Times must be returned in 24-hour HH:MM format.
- A time range is start_time first, end_time second, regardless of how it's
  worded: "from <time> to <time>", "<time> to <time>", "<time> - <time>",
  "from time <time> to time <time>", or a labeled pair like "start time
  <time>, end time <time>" / "in time <time>, out time <time>". The FIRST
  time named is always start_time and the SECOND is always end_time — never
  the reverse.
  - "from 9am to 6pm" -> start_time="09:00", end_time="18:00"
  - "from time 9:30 to time 18:30" -> start_time="09:30", end_time="18:30"
- employee_name should only be set if another employee is explicitly
  named. For the employee's own attendance, employee_name must be null.
- reason should be a short paraphrase of what the employee ACTUALLY said
  (e.g. "forgot to punch out", "missed punch", "was late"). If the message
  gives a date (and/or a time) but states no reason at all anywhere, leave
  "reason": null — do NOT invent a generic filler like "regularization
  request" or "attendance regularization" just because a reason is
  eventually required; the flow will explicitly ask for it on a later turn.

Examples:

Existing:
- date=2026-08-15, start_time=09:10, end_time=18:05, reason=None

Message:
"I forgot to punch out"

Output:
{{"action":"provide_info","entries":[{{"date":"2026-08-15","start_time":null,"end_time":null,"reason":"forgot to punch out"}}],"employee_name":null}}

Existing:
none yet

Message (illustrative — if today were 2026-08-27, a Thursday, so the table
would show 2026-08-24=Monday and 2026-08-25=Tuesday):
"Regularize my missing punch for Monday and Tuesday"

Output — each weekday name resolved by LOOKING IT UP in the reference
table above, never by computing it:
{{"action":"provide_info","entries":[
  {{"date":"2026-08-24","start_time":null,"end_time":null,"reason":"missing punch"}},
  {{"date":"2026-08-25","start_time":null,"end_time":null,"reason":"missing punch"}}
],"employee_name":null}}

Existing:
- date=2026-08-15, start_time=None, end_time=None, reason=None

Message (illustrative — today is 2026-08-16, so "yesterday" is 2026-08-15
... but here the message instead names a genuinely DIFFERENT day):
"regularize my check-in for last friday"

Output — 2026-08-15 stays pending untouched; "last friday" names a
DIFFERENT date (say 2026-08-13), so it's a NEW entry, not a fold-in of
this message onto the already-collected 2026-08-15 entry:
{{"action":"provide_info","entries":[{{"date":"2026-08-13","start_time":null,"end_time":null,"reason":"missing check-in"}}],"employee_name":null}}

Existing:
- date=2026-08-15, start_time=09:10, end_time=18:05, reason=forgot to punch out

Message:
"change the end time to 7pm"

Output:
{{"action":"provide_info","entries":[{{"date":"2026-08-15","start_time":null,"end_time":"19:00","reason":null}}],"employee_name":null}}

Existing:
- date=2026-08-15, start_time=09:10, end_time=18:05, reason=forgot to punch out

Message:
"yes go ahead"

Output:
{{"action":"confirm","entries":[],"employee_name":null}}

Existing:
- date=2026-08-15, start_time=09:10, end_time=18:05, reason=forgot to punch out

Message (illustrative — corrects the date AND time while also confirming
in the same message):
"date: 18/08/2026, time: 9 am end time 10 pm, confirm and submit"

Output — the new date/time are extracted into "entries" exactly as they
would be for provide_info, AND action is still "confirm" since the
message clearly asks to submit:
{{"action":"confirm","entries":[{{"date":"2026-08-18","start_time":"09:00","end_time":"22:00","reason":null}}],"employee_name":null}}

Existing:
- date=2026-07-30, start_time=None, end_time=None, reason=None

Message:
"ok"

Output:
{{"action":"provide_info","entries":[],"employee_name":null}}

Existing:
- date=2026-07-31, start_time=None, end_time=None, reason=None

Message:
"10 se 7 bje mujhe late hua tha"

Output (no date mentioned in the message — leave date null, do NOT use {today_str}):
{{"action":"provide_info","entries":[{{"date":null,"start_time":"10:00","end_time":"19:00","reason":"was late"}}],"employee_name":null}}

Existing:
none yet

Message (illustrative — today's year is {today.year}):
"regularize my attendance for 23 aug"

Output — day+month with no year stated, resolved to THIS year (the DATE is
never left null); no reason was actually given anywhere in the message, so
"reason" stays null too — do NOT invent a generic filler like "regularization
request":
{{"action":"provide_info","entries":[{{"date":"{today.year}-08-23","start_time":null,"end_time":null,"reason":null}}],"employee_name":null}}

Current message:
{query}
"""


# ---------------------------------------------------------------------------
# Self-name normalization
# ---------------------------------------------------------------------------
#
# _build_prompt's own LLM rule ("employee_name should only be set if
# another employee is explicitly named") is impossible for the LLM to
# reliably follow — the prompt never tells it who the CALLER is, so it has
# no way to know a name it sees IS the caller's own. Confirmed live class of
# bug (same root cause already fixed in attendance.py's attendance_node):
# an employee referring to themselves by name ("regularize Mukesh's
# attendance for yesterday", said BY Mukesh) got employee_name="Mukesh" set
# on the request — post_regularization then submits it as acting ON BEHALF
# OF a named employee instead of the caller's own, ordinary self-request.
# Normalizing here, once, via SlotFlowConfig.normalize_employee_name, means
# every place target_employee is used downstream (the summary card, the
# submit payload) already has it nulled out for a genuine self-mention.

# ---------------------------------------------------------------------------
# Deterministic read of times and a reason (slot_flow's fallback_extract_entry)
# ---------------------------------------------------------------------------
#
# Only used when the LLM extraction came back with nothing. Live: "start (in)
# time 10 am, the end (out) time 7 pm, and the reason is miss punch" was cut
# off mid-JSON at the old 250-token budget, and the flow asked again for the
# three fields the employee had just typed.

_CLOCK_TIME_RE = re.compile(
    r"\b(\d{1,2})(?:[:.](\d{2}))?\s*(a\.?m\.?|p\.?m\.?)(?![a-z])|\b(\d{1,2}):(\d{2})\b",
    re.IGNORECASE,
)
_REASON_RE = re.compile(r"\breason\b\s*(?:is|was|being|:|-|=)?\s*(.+?)\s*[.!]*\s*$", re.IGNORECASE)


def _clock_times(text: str) -> list:
    times = []
    for m in _CLOCK_TIME_RE.finditer(text or ""):
        if m.group(1):
            hour, minute = int(m.group(1)), int(m.group(2) or 0)
            meridiem = m.group(3).lower().replace(".", "")
            if not 1 <= hour <= 12:
                continue
            if meridiem == "pm" and hour != 12:
                hour += 12
            if meridiem == "am" and hour == 12:
                hour = 0
        else:
            hour, minute = int(m.group(4)), int(m.group(5))
        if hour <= 23 and minute <= 59:
            times.append(f"{hour:02d}:{minute:02d}")
    return times


# "reason: <text>" / "reason is <text>" / "reason - <text>" - an explicit
# reason, taken exactly as typed (to the end of the message). Not "reason for"
# or "change the reason to ..." phrasing, which the model reads better.
_VERBATIM_REASON_RE = re.compile(r"\breason\s*(?::|-|=|\bis\b|\bwas\b)\s*(?P<r>\S.*?)\s*$",
                                 re.IGNORECASE | re.DOTALL)


# "... and reason is late arrival then submit" - the go-ahead at the END of a
# message that also edits the form. Live it was saved as part of the reason
# ("late arrival then submit") and the review card came back instead of the
# request being sent.
# A connector or comma is required, so a reason that ENDS in the word ("forgot
# to submit") keeps it.
_TRAILING_SUBMIT_RE = re.compile(
    r"(?:\s*[,;.]\s*|\s+(?:and\s+then|and|then|&)\s+)(?:please\s+|pls\s+)?"
    r"(?:submit|confirm|send)(?:\s+(?:it|this|that|the\s+request|now|please|pls))*"
    r"\s*[.!]*\s*$", re.IGNORECASE)


def _strip_trailing_submit(query: str) -> str:
    """`query` without a trailing "then submit" / "and submit it" - but never
    stripped down to nothing: a bare "submit" is the go-ahead itself."""
    stripped = _TRAILING_SUBMIT_RE.sub("", query or "")
    return stripped if stripped.strip() else (query or "")


def ends_with_submit(query: str) -> bool:
    """True when a message that changes the form also says to send it."""
    q = query or ""
    return bool(_TRAILING_SUBMIT_RE.search(q)) and bool(_strip_trailing_submit(q).strip()) \
        and _strip_trailing_submit(q) != q


def _verbatim_reason(query: str) -> dict | None:
    """{"reason": text} when the message gives the reason explicitly, else
    None. Quotes around it are dropped; a blank reason ("reason: '   '") is
    not a reason, so the flow asks for one again."""
    match = _VERBATIM_REASON_RE.search(_strip_trailing_submit(query or ""))
    if not match:
        return None
    reason = match.group("r").strip().strip("'\"“”‘’").strip().rstrip(".").strip()
    return {"reason": reason} if reason else None


# "10 - 23", "10-23", "10 to 23", "9:30 - 18" - two bare hours (24-hour, no
# am/pm) joined as a range. Only read as times when the message has no clock
# times of its own.
_BARE_HOUR_RANGE_RE = re.compile(
    r"(?<![\d/.-])(\d{1,2})(?::(\d{2}))?\s*(?:-|\u2013|\u2014|to|till|until)\s*"
    r"(\d{1,2})(?::(\d{2}))?(?![\d/.:-]|\s*(?:st|nd|rd|th|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\b)",
    re.IGNORECASE)


def _bare_hour_range(text: str):
    """(start, end, rest) for "10 - 23 late arrival" -> ("10:00", "23:00",
    "late arrival"), or None."""
    m = _BARE_HOUR_RANGE_RE.search(text or "")
    if not m:
        return None
    h1, m1, h2, m2 = int(m.group(1)), int(m.group(2) or 0), int(m.group(3)), int(m.group(4) or 0)
    if not (h1 <= 23 and h2 <= 23 and m1 <= 59 and m2 <= 59):
        return None
    rest = (text[:m.start()] + " " + text[m.end():]).strip(" ,.;:-")
    # Words that only frame the times ("from 10 - 23", "timing 10 to 23") are
    # not a reason.
    rest = re.sub(r"\b(?:from|between|time|timings?|hours?|hrs?|at|is|was|and|my|shift)\b",
                  " ", rest, flags=re.IGNORECASE)
    rest = re.sub(r"\s+", " ", rest).strip(" ,.;:-")
    return f"{h1:02d}:{m1:02d}", f"{h2:02d}:{m2:02d}", rest


def _fallback_extract_entry(query: str) -> dict | None:
    """{start_time, end_time, reason} read straight off the message — the
    first clock time is the start, the second the end (the same rule the
    prompt states), and "reason is/:" names the reason. Only what is found.

    Also a bare 24-hour range: "10 - 23 late arrival" -> 10:00 to 23:00,
    reason "late arrival" (live, the model read nothing from it)."""
    entry = {}
    times = _clock_times(query)
    if len(times) >= 2:
        entry["start_time"], entry["end_time"] = times[0], times[1]
    else:
        bare = _bare_hour_range(query)
        if bare:
            entry["start_time"], entry["end_time"], rest = bare
            # Tells slot_flow these numbers are TIMES: the model reads
            # "10 - 23" as the date 23-Oct (live: "I can't regularize a future
            # date (23 Oct 2026)").
            entry["_times_from_bare_range"] = True
            if re.search(r"[a-z]{3,}", rest or "", re.IGNORECASE) and not _REASON_RE.search(query or ""):
                entry["reason"] = rest
    reason = _REASON_RE.search(query or "")
    if reason and reason.group(1).strip():
        entry["reason"] = reason.group(1).strip()
    return entry or None


def _normalize_employee_name(target_employee: str | None, bearer_token: str | None) -> str | None:
    if not target_employee:
        return target_employee
    claims = attendance_mod._decode_jwt_claims(bearer_token)
    current_user_name = claims.get("name") or claims.get("username") or claims.get("preferred_username")
    current_user_emp_no = claims.get("emp_no")
    if attendance_mod._is_self_reference(current_user_name, current_user_emp_no, target_employee):
        return None
    return target_employee


# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------

REGULARIZATION_CONFIG = SlotFlowConfig(
    name="regularization",
    required_fields=[],
    field_labels={},
    build_prompt=_build_prompt,
    submit=_submit,
    map_submit_exception=_map_exception,
    extract_failure_message=_extract_failure_message,
    entry_fields=ENTRY_FIELDS,
    entry_field_labels=ENTRY_FIELD_LABELS,
    entry_key="date",
    format_multi_summary=_format_multi_summary,
    format_multi_success=_format_multi_success,
    is_explicit_cancel=_is_explicit_cancel,
    # "yes" / "proceed" / "approve" / "confirm & submit" on the summary card
    # confirms without an LLM call — see regularisation_guards.is_affirmative_reply.
    is_explicit_confirm=is_affirmative_reply,
    # "... reason is late arrival then submit" - the edit and the go-ahead.
    ends_with_confirm=ends_with_submit,
    fallback_extract_entry=_fallback_extract_entry,
    # An explicit "reason: ..." is submitted exactly as typed (QA TC-056).
    verbatim_fields=_verbatim_reason,
    normalize_entry_field=lambda field, value: _clean_entry_field(field, value),
    normalize_employee_name=_normalize_employee_name,
    # A named OTHER employee is refused, not filed on their behalf.
    other_employee_refusal=APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE,
    reject_future_dates=True,
    # A date the classify gate's own deterministic-only resolver couldn't
    # catch up front (a typo'd month name, an unusual phrasing) still gets
    # rejected here — via _fetch_prefill's own call into
    # _regularization_eligibility_block_reason — once the LLM extracts it.
    # Reported the SAME way regularisation_eligibility_node reports its own
    # rejections, so the intent/shape never depends on which of the two
    # caught it.
    blocked_entry_intent="regularisation_classify",
    blocked_entry_extra_data=lambda entry: {
        "regularisation_classification_status": False,
        "date": entry.get("date"),
        # Set by _fetch_prefill's duplicate-date / quota checks — the
        # existing-request card, the quota figures, the retry-and-form offer —
        # the same data the classify gate sends.
        **(entry.get("_duplicate_check") or {}),
        **(entry.get("_quota_check") or {}),
    },
)


# ---------------------------------------------------------------------------
# Structured edit support (Save button — bypasses the LLM entirely)
# ---------------------------------------------------------------------------
#
# Expected structured query shape (state["query"] is JSON text):
#   {"action": "edit_entry", "date": "2026-07-30",
#    "start_time": "10:00", "end_time": "19:00", "reason": "..."}
#   {"action": "remove_entry", "date": "2026-07-30"}
#
# The regularization FORM posts the same entry shape but with NO "action"
# key at all:
#   {"date": "2026-08-03", "start_time": "09:00",
#    "end_time": "18:30", "reason": "regularization request"}
# That used to fall through to the LLM flow, which was then asked to
# extract slots out of raw JSON text as if it were a chat sentence — it
# reliably picked up "date" and "reason" but dropped start_time/end_time,
# so a fully filled-in form came back as "I still need ... the start (in)
# time, and the end (out) time" (observed bug). A form payload carries the
# exact field names the flow stores, so it is normalized to an
# "edit_entry" below and handled deterministically instead — the LLM never
# sees it.
#
# Any field omitted/null is left unchanged. Any other query shape (plain
# string, or JSON that is neither a recognized "action" nor a form entry
# payload) falls through to the normal LLM-driven flow untouched.

_STRUCTURED_ACTIONS = {"edit_entry", "remove_entry"}

# Fields the regularization form can post. Anything outside this set means
# the JSON isn't a form payload, so it is left to the LLM flow — including
# "employee_name", which needs the caller-identity normalization
# (_normalize_employee_name) that this deterministic path has no bearer
# token to do.
_FORM_ENTRY_KEYS = {"date", "start_time", "end_time", "reason"}


_LABELLED_FIELD_RE = re.compile(
    r"^\s*(date|from\s*time|start\s*time|in\s*time|to\s*time|end\s*time|out\s*time|"
    r"shift(?:\s*timing)?|reason(?:\s*/\s*comment)?|comment)\s*:\s*(.*)$",
    re.IGNORECASE)


def _labelled_form_entry(query: str, today: date) -> dict | None:
    """{date, start_time, end_time, reason} from the form's labelled-text
    submission, or None when the message is not that shape (it needs a "Date:"
    line and at least one other field line). "Shift Timing:" is display only
    and ignored. The reason runs to the end of the message, verbatim."""
    lines = (query or "").splitlines()
    if len(lines) < 2:
        return None
    fields, reason_lines, in_reason = {}, [], False
    for line in lines:
        m = _LABELLED_FIELD_RE.match(line)
        if m:
            label = re.sub(r"\s+", "", m.group(1).lower())
            value = m.group(2).strip()
            in_reason = label.startswith(("reason", "comment"))
            if in_reason:
                reason_lines = [value]
            elif label == "date":
                fields["date"] = value
            elif label in ("fromtime", "starttime", "intime"):
                fields["start_time"] = value
            elif label in ("totime", "endtime", "outtime"):
                fields["end_time"] = value
            continue
        if in_reason:
            reason_lines.append(line.strip())
    if "date" not in fields or not (set(fields) - {"date"} or reason_lines):
        return None
    resolved = date_query_resolver.resolve(fields["date"], today)
    if not (isinstance(resolved, dict) and resolved.get("type") == "single"):
        return None
    entry = {"date": resolved["date"].isoformat()}
    for key in ("start_time", "end_time"):
        if fields.get(key):
            entry[key] = regularisation_display.time_24h(fields[key])
    reason = " ".join(x for x in reason_lines if x).strip()
    if reason:
        entry["reason"] = reason
    return entry


def _clean_form_value(value):
    """Blank/whitespace-only form fields count as "not provided" — keeping
    them as "" would store an empty value that reads as missing anyway."""
    if isinstance(value, str):
        value = value.strip()
        return value or None
    return value


_TIME_FIELDS = ("start_time", "end_time")


def _clean_entry_field(key: str, value):
    """_clean_form_value, plus times made 24-hour "HH:MM": the form and a
    typed reply say "10:00 AM" / "11 pm" / "23", and erp-api compares the
    times against the shift - "11:00 PM" must reach it as "23:00"."""
    value = _clean_form_value(value)
    if key in _TIME_FIELDS and value is not None:
        return regularisation_display.time_24h(value)
    # A reason with no letter or digit in it ("'   '", "...", "-") is blank.
    # QA TC-055: "Reason: '   '" - _verbatim_reason already reads that as no
    # reason, but the LLM extraction kept the quotes as the reason and the
    # summary offered to submit it.
    if key == "reason" and isinstance(value, str) and not re.search(r"\w", value):
        return None
    return value


def _try_parse_form_entry(parsed: dict) -> dict | None:
    """Normalizes a bare form-entry payload (no "action") into the
    "edit_entry" shape _handle_structured_action already understands.
    Returns None for anything that isn't recognizably a form entry."""
    if parsed.get("action") is not None:
        return None

    if not set(parsed) <= (_FORM_ENTRY_KEYS | {"action"}):
        return None

    cleaned = {k: _clean_entry_field(k, parsed.get(k)) for k in _FORM_ENTRY_KEYS}

    if not cleaned.get("date"):
        return None

    # A date on its own is NOT treated as a form submission: that case is
    # exactly what the normal flow's punch-record prefill exists for, and
    # routing it here would skip that lookup.
    if not any(cleaned.get(f) for f in ("start_time", "end_time", "reason")):
        return None

    return {"action": "edit_entry", **cleaned}


def _loads_query_object(query: str) -> dict | None:
    """Decodes the query into a JSON object, tolerating a payload that was
    JSON-encoded more than once on its way here.

    The form's payload reaches this node as state["query"], and depending
    on how the client serializes it, it can arrive already double-encoded
    — the query string is then a JSON *string* whose contents are the real
    JSON object (it renders as "{\\"date\\":\\"2026-08-03\\",...}",
    escapes and all). A single json.loads on that yields a str, not a
    dict, so the whole form payload was falling through to the LLM flow
    and getting extracted as if it were a chat sentence (observed bug).
    Unwrap the string layers first, then require an object.

    Anything that isn't JSON at all (an ordinary chat message) fails on
    the first decode and returns None, unchanged.
    """
    value = query.strip() if isinstance(query, str) else query

    for _ in range(3):
        try:
            value = json.loads(value)
        except (json.JSONDecodeError, TypeError, ValueError):
            return None

        if isinstance(value, dict):
            return value

        if not isinstance(value, str):
            return None

        value = value.strip()

    return None


# The review card's Confirm & Submit / Cancel buttons post raw JSON too —
# often the SAME entry fields the form itself uses (date/start_time/
# end_time/reason), just tagged with {"action": "confirm"} or
# {"action": "cancel"} instead of no "action" key at all. That shape isn't
# a recognized _STRUCTURED_ACTIONS value and _try_parse_form_entry refuses
# it outright (it only accepts a payload with NO "action" key — see its
# own docstring), so it used to fall straight through to the LLM-driven
# multi-entry flow with the entire raw JSON blob as the "message" (observed
# bug). The LLM sometimes misread that JSON — e.g. extracting only
# {"date": "..."} out of it as if it were a brand-new, mostly-empty entry —
# and _merge_entries' no-matching-date-found path REPLACES the whole
# existing entry with that near-empty one, silently discarding the
# start/end time and reason the employee had already provided and was
# trying to confirm. The card then re-asked for exactly the fields the
# employee had just filled in and clicked "Confirm & Submit" on.
_CONFIRM_CANCEL_ACTIONS = {"confirm": "confirm", "cancel": "cancel"}


def _payload_entry(parsed) -> dict | None:
    """The complete entry a card's JSON carries ({date, start_time, end_time,
    reason}, all filled), or None."""
    if not isinstance(parsed, dict):
        return None
    entry = {k: _clean_entry_field(k, parsed.get(k)) for k in ENTRY_FIELDS}
    return entry if all(entry.values()) else None


def _same_entry(a: dict, b: dict) -> bool:
    return all(str(a.get(k) or "").strip().lower() == str(b.get(k) or "").strip().lower()
               for k in ENTRY_FIELDS)


def _try_parse_confirm_or_cancel(query: str) -> str | None:
    """Recognizes a Confirm & Submit / Cancel button's JSON payload and
    reduces it to the single unambiguous word ("confirm"/"cancel") the
    slot-flow prompt already has a worked example for, instead of ever
    handing the raw JSON to the LLM. Any other fields the button also
    posted (date/start_time/end_time/reason) are intentionally ignored —
    the already-stored entries are the source of truth for a confirm."""
    parsed = _loads_query_object(query)
    if not isinstance(parsed, dict):
        return None
    return _CONFIRM_CANCEL_ACTIONS.get(parsed.get("action"))


def _try_parse_structured_action(query: str) -> dict | None:
    parsed = _loads_query_object(query)

    if parsed is None:
        return None

    if parsed.get("action") not in _STRUCTURED_ACTIONS:
        form_payload = _try_parse_form_entry(parsed)
        if form_payload is None:
            logger.info(
                "[Graph] regularisation: JSON query not recognized as a "
                "structured action or form entry (keys=%s) — falling back "
                "to the LLM flow",
                sorted(parsed),
            )
        return form_payload

    return parsed


async def _handle_structured_action(
    payload: dict,
    *,
    company_id,
    conversation_id: str,
    writer: StreamWriter,
    usage_events: list,
) -> dict:

    stored = slot_store.get_slots("regularization", company_id, conversation_id) or {}
    entries = stored.get("entries") or []
    employee_name = stored.get("employee_name")

    date_iso = payload.get("date")
    if not date_iso:
        message = "I need a date to know which entry to update."
        writer({"type": "done", "intent": "regularization_incomplete", "is_hr": True,
                "data": {"answer": message}, "message": message, "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    if payload["action"] == "remove_entry":
        entries = [e for e in entries if e.get("date") != date_iso]
    else:  # edit_entry
        # Same invariant SlotFlowConfig.reject_future_dates enforces on the
        # LLM path: regularization only ever corrects attendance that has
        # already happened, so a future date can't be accepted here either
        # (this path can create an entry, not just edit one).
        today_iso = attendance_mod._today().strftime("%Y-%m-%d")
        if date_iso > today_iso:
            message = regularisation_display.future_date_message(
                _display_date(date_iso), _display_date(today_iso))
            writer({"type": "done", "intent": "regularization_incomplete", "is_hr": True,
                    "data": {"answer": message}, "message": message, "usage_events": usage_events})
            return {"response_text": message, "usage_events": usage_events}

        updates = {
            k: payload.get(k)
            for k in ("start_time", "end_time", "reason")
            if payload.get(k) is not None
        }
        found = False
        for e in entries:
            if e.get("date") == date_iso:
                e.update(updates)
                found = True
                break
        if not found:
            entries.append({"date": date_iso, **updates})

    slot_store.set_slots(
        "regularization", company_id, conversation_id,
        {"entries": entries, "employee_name": employee_name},
    )

    def _missing_for(entry):
        return [f for f in ENTRY_FIELDS if not entry.get(f)]

    entries_missing = any(_missing_for(e) for e in entries)
    status = "incomplete" if (not entries or entries_missing) else "awaiting_confirmation"

    writer({
        "type": "regularization_card",
        "data": _build_entry_cards(REGULARIZATION_CONFIG, entries, status),
    })

    if not entries:
        message = "Done — I've removed that entry."
    elif entries_missing:
        message = "Updated — a few details are still missing before I can submit."
    else:
        message = _format_multi_summary(entries)

    data = {"answer": message}
    if status == "awaiting_confirmation":
        data["is_conceled"] = False

    writer({"type": "done", "intent": f"regularization_{status}", "is_hr": True,
            "data": data, "message": message, "usage_events": usage_events})

    return {"response_text": message, "usage_events": usage_events}


def _clear_punch_previews_if_flow_finished(company_id, conversation_id: str) -> None:
    """Called after every turn that can end the regularisation flow
    (submit, cancel, or a structured remove_entry that empties the entry
    list). Once the "regularization" slots namespace has no entries left,
    the persisted punch previews are stale for any FUTURE, unrelated
    regularisation request in this same conversation, so drop them too
    instead of leaving them to expire on their own TTL."""
    remaining = slot_store.get_slots("regularization", company_id, conversation_id) or {}
    if not remaining.get("entries"):
        slot_store.clear_slots(_PUNCH_PREVIEW_NAMESPACE, company_id, conversation_id)


# ---------------------------------------------------------------------------
# Regularisation-request classification gate (graph node)
# ---------------------------------------------------------------------------
#
# A dedicated LangGraph node wired BEFORE regularisation_node (see
# hr_graph.py's build_hr_graph) for classify_node's DIRECT route into
# regularisation only — "I want to apply regularisation for 5 September",
# "regularize my attendance for yesterday", typed with no prior attendance/
# attendance_explain lookup at all. attendance_node/attendance_explain_node's
# own hand-off (attendance.py's _handoff_to_regularisation/
# _seed_pending_regularization) already screened the date's status before
# ever routing to regularisation_node — those entries carry "_prevalidated"
# and are wired straight there, bypassing this gate entirely.
#
# Classifies whether THIS message's date is even regularisable — not already
# regularized, status Absent/Half Day Absent, and inside the company's
# regularization window — using the exact same checks
# _regularization_eligibility_block_reason already enforces mid-flow. The
# result is reported as intent
# "regularisation_classify" with a "regularisation_classification_status"
# true/false flag in the response data.
#
# Eligible does NOT fall straight into asking for a start/end time and a
# reason — the employee must explicitly reply "apply now" first (see
# _is_apply_now_confirmation below). Only once that confirmation arrives is
# the date actually seeded into the flow and control handed to
# regularisation_node. Ineligible ends the turn right here with the reason.
#
# Date resolution tries the deterministic resolver first
# (_resolve_direct_entry_date) and only falls back to a small, focused LLM
# call (_resolve_direct_entry_date_llm_fallback) when that fails — e.g. a
# typo'd month name ("7 septmber"). Without that fallback, a typo'd date
# used to slip past this gate ENTIRELY (silently passing through) and reach
# regularisation_node's own, separately typo-tolerant slot-flow instead —
# which has no "apply now" ceremony of its own, so an eligible-but-typo'd
# date walked straight into asking for a start/end time and a reason with
# no classification step at all (observed/reported).
#
# A message naming no single explicit date ("I want to apply for
# regularization", a range, several dates at once) has nothing to classify
# yet and passes straight through unchanged — regularisation_node's own
# slot-flow asks "which date(s)?" exactly as before, and the SAME classify
# step runs again on the reply that finally names one (see the "awaiting
# confirmation"/"fresh" branches below). Once an entry has actually survived
# this gate and regularisation_node starts collecting its remaining fields,
# every later turn passes straight through — a date CHANGED mid-flow still
# gets the identical eligibility check, just via
# _regularization_eligibility_block_reason inside _fetch_prefill instead of
# this gate, and without re-demanding "apply now" (that ceremony is only for
# entering a fresh request, not for correcting one already in progress).

_PENDING_CLASSIFICATION_KEY = "awaiting_apply_confirmation"
_CLASSIFIED_DATE_KEY = "classified_date"
# Several dates that passed the first-step checks together ("28 and 29 sept").
_CLASSIFIED_DATES_KEY = "classified_dates"

# Typo-tolerant: the prompt says "Reply **apply now**", and a live "aply now"
# matched nothing, left the flow and was answered as an employee lookup.
# Needs the whole "apply ... now" shape, so "apply no" or a bare "now" do not
# count as the explicit confirmation this gate exists for.
_APPLY_NOW_PATTERN = re.compile(r"\b(?:a+p+l+[iy]+|a+p+y+)\s*n+o*w+\b", re.IGNORECASE)
# A bare affirmative ("yes", "go ahead", "proceed", "confirm") only counts
# when it IS essentially the whole message — same anchoring rationale as
# this file's own _BARE_DECLINE_PATTERN: a generic word like "confirm" or
# "yes" could otherwise appear naturally inside an unrelated sentence and be
# misread as the explicit confirmation this gate requires.
#
# A bare "apply" is the same answer. Live: "apply regularize for 9 sept" ->
# "Reply apply now ..." -> "apply" matched neither pattern, fell through to
# the lone-verb check and was asked "what would you like to apply for? Leave
# or Regularization" — about the request it had just started. The other
# ways of saying go on to this prompt ("continue", "fix it now" — the
# attendance card's own button — "submit", "do it") are here for the same
# reason. Still whole-message only.
_BARE_APPLY_CONFIRM_PATTERN = re.compile(
    r"^\s*(?:yes|yep|yeah|sure|ok|okay|go\s*ahead|go\s*on|proceed|confirm|continue|"
    r"(?:a+p+l+[iy]+|a+p+y+|appy)(?:\s+(?:it|this|please|pls))?|"
    r"fix\s+it(?:\s+now)?|submit(?:\s+it)?|do\s+it|let'?s\s+(?:do\s+it|go|proceed))"
    r"\s*[.!]*\s*$",
    re.IGNORECASE,
)


def _is_apply_now_confirmation(query: str) -> bool:
    # is_affirmative_reply: the one go-ahead vocabulary the whole flow shares
    # ("yes", "proceed", "approve", "apply", ...).
    return (bool(_APPLY_NOW_PATTERN.search(query)) or bool(_BARE_APPLY_CONFIRM_PATTERN.match(query))
            or is_affirmative_reply(query))


def _resolve_direct_entry_date(query: str, today: date) -> str | None:
    """Deterministic only (no LLM call) — returns an ISO date only for an
    unambiguous SINGLE explicit date named in THIS message. The same shared
    resolver slot_flow.py's own bare-date fallback and this file's
    invalid-date guard already use elsewhere (see date_query_resolver.resolve's
    own docstring) — a range, several discontiguous dates, or no date at all
    all return None here, deferring to _resolve_direct_entry_date_llm_fallback
    below."""
    resolved = date_query_resolver.resolve(query, today)
    if isinstance(resolved, dict) and resolved.get("type") == "single":
        return resolved["date"].isoformat()
    return None


_DATE_LIST_SPLIT_RE = re.compile(r"\s*(?:,|&|\band\b|\bplus\b|\balso\b)\s*", re.IGNORECASE)
_MONTH_WORD_RE = re.compile(
    r"\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?(?:\s+\d{4})?", re.IGNORECASE)
_TRAILING_DAY_RE = re.compile(r"(?:^|\s)(\d{1,2})(?:st|nd|rd|th)?\s*$", re.IGNORECASE)
# A short span is several days to regularize ("28 sept to 30 sept"); a long one
# is not a regularization request anyone means, and is left to the flow.
_MAX_EXPANDED_RANGE_DAYS = 7


def _resolve_direct_entry_dates(query: str, today: date) -> list[str]:
    """Every date named in THIS message, when there are two or more:
    "28 sept and 29 sept", "28, 29 and 30 sept", "yesterday and today",
    "28 sept to 30 sept" (a short range, one entry per day). [] otherwise —
    a single date is _resolve_direct_entry_date's job.

    Deterministic. Exists because date_query_resolver keeps only the FIRST of
    several dates ("28 sept and 29 sept" -> 28 Sep), so the first-step checks
    looked at one date and an already-applied 29 Sep only surfaced after the
    details for it had been collected."""
    resolved = date_query_resolver.resolve(query, today)
    if isinstance(resolved, dict) and resolved.get("type") == "range":
        start, end = resolved["start_date"], resolved["end_date"]
        span = (end - start).days + 1
        if 2 <= span <= _MAX_EXPANDED_RANGE_DAYS:
            return [(start + timedelta(days=i)).isoformat() for i in range(span)]
        return []

    parts = [p for p in _DATE_LIST_SPLIT_RE.split(query or "") if p and p.strip()]
    if len(parts) < 2:
        return []
    month = _MONTH_WORD_RE.search(query or "")
    found: list[str] = []
    for part in parts:
        hit = date_query_resolver.resolve(part, today)
        if not hit and month and not _MONTH_WORD_RE.search(part):
            # "28, 29 and 30 sept": a bare day borrows the month named elsewhere.
            day = _TRAILING_DAY_RE.search(part)
            if day:
                hit = date_query_resolver.resolve(f"{day.group(1)} {month.group(0)}", today)
        if isinstance(hit, dict) and hit.get("type") == "single":
            iso = hit["date"].isoformat()
            if iso not in found:
                found.append(iso)
    return found if len(found) >= 2 else []


def _invalid_date_mention(query: str, today: date) -> str | None:
    """The text of a date that can't exist ("31 Sep 2026", "30 feb",
    "31/04/2026", "2026-02-30") named in this message - also when it is one of
    several ("28 sept and 31 sept") - or None. Deterministic, no backend call."""
    whole = date_query_resolver.resolve(query or "", today)
    if isinstance(whole, date_query_resolver.InvalidExplicitDate):
        return whole.matched_text
    month = _MONTH_WORD_RE.search(query or "")
    for part in _DATE_LIST_SPLIT_RE.split(query or ""):
        if not part or not part.strip():
            continue
        hit = date_query_resolver.resolve(part, today)
        if hit is None and month and not _MONTH_WORD_RE.search(part):
            day = _TRAILING_DAY_RE.search(part)
            if day:
                hit = date_query_resolver.resolve(f"{day.group(1)} {month.group(0)}", today)
        if isinstance(hit, date_query_resolver.InvalidExplicitDate):
            return hit.matched_text
    return None


_MONTH_NUMBERS = {name: i for i, name in enumerate(
    ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"], start=1)}


def _invalid_date_message(text: str, today: date,
                          question: str = "Which date would you like to regularize?",
                          example: str = "30 Sep 2026") -> str:
    """"'31 Sep 2026' isn't a valid date - September 2026 has only 30 days.
    Which date would you like to regularize?" - with the month's real length
    when the day and month can be read from the text."""
    why = ""
    t = (text or "").strip().lower()
    day = month = year = None
    m = re.match(r"^(\d{4})-(\d{1,2})-(\d{1,2})$", t)
    if m:
        year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3))
    else:
        m = re.match(r"^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$", t)
        if m:
            day, month = int(m.group(1)), int(m.group(2))
            year = int(m.group(3)) if m.group(3) else None
        else:
            m = re.search(r"(\d{1,2})(?:st|nd|rd|th)?\s+([a-z]{3})[a-z]*\.?(?:\s*,?\s*(\d{4}))?", t) \
                or re.search(r"([a-z]{3})[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?(?:\s*,?\s*(\d{4}))?", t)
            if m and m.group(1).isdigit():
                day, month = int(m.group(1)), _MONTH_NUMBERS.get(m.group(2))
                year = int(m.group(3)) if m.group(3) else None
            elif m:
                month, day = _MONTH_NUMBERS.get(m.group(1)), int(m.group(2))
                year = int(m.group(3)) if m.group(3) else None
    if year is not None and year < 100:
        year += 2000
    if month and 1 <= month <= 12:
        year = year or today.year
        days = calendar.monthrange(year, month)[1]
        if day and day > days:
            why = (f" - {calendar.month_name[month]} {year} has only {days} days")
    elif month:
        why = " - there's no month " + str(month)
    return (f"'{text.strip()}' isn't a valid date{why}. {question} "
            f"You can type it like \"{example}\".")


_ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")

# Messages with nothing for the LLM fallback below to even look for — never
# worth the extra call. Deliberately narrow (mirrors _BARE_APPLY_CONFIRM_
# PATTERN's own anchoring): only skips when one of these IS essentially the
# whole message, never a substring, so a genuine "cancel my request for 7
# septmber" still gets the fallback's attention for its date.
_LOOKS_DATELESS_PATTERN = re.compile(
    r"^\s*(hi|hello|hey|thanks|thank\s*you|yes|yep|yeah|no|nope|nah|ok|okay|"
    r"cancel|apply\s*now|go\s*ahead|proceed|confirm)\s*[.!?]*\s*$",
    re.IGNORECASE,
)


def _build_single_date_extraction_prompt(query: str, today: date) -> str:
    return f"""Extract the ONE explicit calendar date named in this message, if any.
Today is {today.isoformat()} ({today.strftime('%A')}).
The message may misspell words (e.g. a month name typo like "septmber") —
correct them silently before resolving.

Output ONLY this JSON object, no explanation, no markdown:
{{"date": "YYYY-MM-DD" or null}}

Rules:
- Resolve "yesterday"/"today"/a weekday name/an explicit day+month/a full
  date to an absolute YYYY-MM-DD date.
- Any numeric date is DD/MM/YYYY (day first), never MM/DD/YYYY.
- A date with no year stated uses {today.year}.
- If the message names a RANGE, SEVERAL distinct dates, or NO date at all,
  output {{"date": null}} — do not guess one.

Message: {query}"""


async def _resolve_direct_entry_date_llm_fallback(
    query: str, today: date, usage_events: list,
) -> str | None:
    """Deterministic resolution (_resolve_direct_entry_date above) requires
    exact spelling — a typo'd month name ("7 septmber") or an unusual
    phrasing it doesn't recognize silently returns None from it, which used
    to mean this gate's classification (status/window/already-regularized,
    and the "apply now" confirmation ceremony) was skipped ENTIRELY for such
    a message: it fell through to regularisation_node's own (separately
    typo-tolerant, LLM-backed) slot-flow instead, which has no equivalent
    "apply now" gate of its own — an eligible-but-typo'd date walked
    straight into asking for a start/end time and a reason with no
    classification step at all (observed/reported).

    A small, focused LLM call closes that gap: same typo tolerance as
    regularisation_node's own extraction, but scoped to ONLY the date (no
    time/reason/action to get wrong), so this gate can classify a date
    exactly like it would have if it had been spelled correctly. Returns
    None (never raises) on any failure — the caller's existing "nothing to
    classify yet, pass through" behavior is the correct fallback either way."""
    try:
        raw = await _call_llm(
            _build_single_date_extraction_prompt(query, today), max_tokens=LLM_TASK_MAX_TOKENS, model=INTENT_MODEL,
        )
    except Exception as e:
        logger.warning("[Graph] regularisation classify date fallback failed: %s", e)
        return None

    usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
    if usage:
        usage_events.append({"source": "regularisation_classify_date_fallback", "usage": usage})

    parsed = _safe_json_parse(_extract_text(raw))
    if not isinstance(parsed, dict):
        return None
    value = parsed.get("date")
    if not (isinstance(value, str) and _ISO_DATE_RE.match(value)):
        return None
    # A real calendar date only: the model happily returns "2026-09-31" for
    # "31 Sep 2026".
    try:
        datetime.strptime(value, "%Y-%m-%d")
    except ValueError:
        logger.info("[Graph] regularisation date fallback returned an impossible date %r", value)
        return None
    return value


async def _classify_and_check_eligibility(
    date_iso: str, *, bearer_token, company_id, conversation_id, writer, settings=None,
) -> str | None:
    """Runs the three-part eligibility check for one date, returning the
    block reason (None if eligible). Reused by both the fresh-classification
    branch and the "different date superseded the pending one" branch below."""
    attendance = await _get_attendance_prefill(
        bearer_token=bearer_token, date_iso=date_iso, company_id=company_id,
        conversation_id=conversation_id, writer=writer,
    )
    preview = attendance["preview"]
    if preview.get("session_rejected"):
        return SESSION_REJECTED_MESSAGE
    return await _regularization_eligibility_block_reason(
        {"date": date_iso}, preview.get("attendance_status_code"), preview.get("is_regularized", False),
        bearer_token=bearer_token, company_id=company_id, conversation_id=conversation_id,
        attendance_known=bool(preview.get("attendance_known")), settings=settings,
    )


def _ambiguous_typo_day(query: str, today):
    """(what was typed, [ISO dates it could mean]) for a day typed with a
    letter in it, else None - date_query_resolver.find_typo_day, the one
    definition classify_node also asks from. Kept here as the apply flow's
    backstop for a message that reached it without being asked about."""
    typo = date_query_resolver.find_typo_day(query, today)
    return (typo.typed, typo.options) if typo else None


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

    today = attendance_mod._today()
    stored = slot_store.get_slots("regularization", company_id, conversation_id) or {}
    # The employee's shift (GET /shift-details), sent with every reply of the
    # apply flow - see _get_shift_details. Cached, so one call per conversation.
    shift_details = await _get_shift_details(
        bearer_token=bearer_token, company_id=company_id, conversation_id=conversation_id,
        employee_name=stored.get("employee_name"))

    # NEW — never return a bare {} from this node: it's the SOURCE of a
    # conditional edge (see hr_graph.py's build_hr_graph), and at least one
    # langgraph version deployed for this project raises
    # InvalidUpdateError("Must write to at least one of [...]") when a
    # conditional-edge source writes no channels at all — confirmed live,
    # regularisation-intent requests only (every other "pass through" node
    # in this codebase either isn't a conditional-edge source or always
    # returns real content). echoing usage_events back unchanged is a
    # harmless, always-present write that satisfies that requirement on
    # every "nothing changed this turn" path below.
    def _pass_through() -> dict:
        return {"usage_events": usage_events}

    def _hold(message: str, intent: str, *, status: bool | None = None, date_iso: str | None = None,
              extra: dict | None = None) -> dict:
        data = {"answer": message, "shift": shift_details}
        if status is not None:
            data["regularisation_classification_status"] = status
        if date_iso:
            data["date"] = date_iso
        if extra:
            data.update(extra)
        writer({
            "type": "done", "intent": intent, "is_hr": True,
            "data": data, "message": message, "usage_events": usage_events,
        })
        return {"response_text": message, "usage_events": usage_events, "regularisation_blocked": True}

    async def _gate_several_dates(dates: list[str]) -> dict:
        """The first-step checks for EVERY date of "28 sept and 29 sept" -
        what can't be regularized is said now, before any details are asked."""
        settings = await _get_regularization_settings(
            bearer_token=bearer_token, company_id=company_id, conversation_id=conversation_id)
        accepted, results = [], []
        for d in dates:
            result = await _first_step_check(
                d, today, bearer_token=bearer_token, company_id=company_id,
                conversation_id=conversation_id, writer=writer, settings=settings,
                accepted=accepted)
            results.append(result)
            if result["ok"]:
                accepted.append(d)

        blocked = [r for r in results if not r["ok"]]
        notices = [r["notice"] for r in results if r["ok"] and r["notice"]]
        extra = {"dates": dates, "eligible_dates": accepted,
                 "blocked_dates": [{"date": r["date"], "reason": r["message"]} for r in blocked]}
        blocked_lines = "\n".join(f"- {r['message']}" for r in blocked)

        if not accepted:
            slot_store.clear_slots("regularization", company_id, conversation_id)
            return _hold(f"I can't take a regularization request for any of these dates:\n"
                         f"{blocked_lines}", "regularisation_classify", status=False, extra=extra)

        slot_store.set_slots("regularization", company_id, conversation_id, {
            "entries": [], _PENDING_CLASSIFICATION_KEY: True,
            _CLASSIFIED_DATE_KEY: accepted[0], _CLASSIFIED_DATES_KEY: accepted})
        last_quota = next((r["quota"] for r in reversed(results)
                           if r["ok"] and r["quota"] and r["quota"]["outcome"] == QUOTA_OK), None)
        quota_line = ""
        if last_quota:
            # Counted with the dates being requested now included.
            quota_line = (f" With {'these' if len(accepted) > 1 else 'this'}, you'll have used "
                          f"{last_quota['used'] + 1} of {last_quota['limit']} for "
                          f"{(last_quota.get('cycle') or {}).get('label') or 'this cycle'}.")
        verb = "are" if len(accepted) > 1 else "is"
        parts = []
        if blocked:
            parts.append(f"Not possible:\n{blocked_lines}")
        parts.extend(notices)
        parts.append(f"Good news — {_join_dates(accepted)} {verb} eligible for attendance "
                     f"regularization.{quota_line}{_shift_sentence(shift_details)} Reply "
                     f"**apply now** and I'll collect the remaining details (start/end time "
                     f"and a reason).")
        return _hold("\n\n".join(parts), "regularisation_classify", status=True,
                     date_iso=accepted[0], extra=extra)

    # ------------------------------------------------------------
    # Already past classification and actively being worked on (this
    # conversation already has a real, _prevalidated entry) — regularisation_
    # node's own flow, and its own mid-flow re-check inside _fetch_prefill
    # for any NEW date, own this turn from here. No "apply now" ceremony for
    # a correction to a request already in progress.
    # ------------------------------------------------------------
    if stored.get("entries"):
        return _pass_through()

    # ------------------------------------------------------------
    # A date that can't exist ("31 Sep 2026", "30 feb", "31/04/2026"): say so
    # and ask for a valid one - before any check that calls erp-api. QA: the
    # LLM date fallback turned "31 Sep 2026" into 2026-09-31 and the flow
    # carried on with it. The flow stays open, so the next reply with a real
    # date continues it (and a pending "apply now" for an earlier date is kept).
    # ------------------------------------------------------------
    invalid = _invalid_date_mention(query, today)
    if invalid:
        if not stored.get(_PENDING_CLASSIFICATION_KEY):
            slot_store.set_slots("regularization", company_id, conversation_id, {"entries": []})
        return _hold(_invalid_date_message(invalid, today), "regularisation_classify",
                     status=False, extra={"invalid_date": invalid.strip(),
                                          "requires_date_input": True})

    # ------------------------------------------------------------
    # A day typed with a letter for a digit ("sept 3o", "3o sept", "1l oct"):
    # ask which day was meant instead of guessing. Live, "sept 3o" was read as
    # 30 Sep without a word - it could as easily have been 3 Sep. Same
    # hold-open as the invalid date above, so the reply continues the flow.
    # ------------------------------------------------------------
    typo_days = _ambiguous_typo_day(query, today)
    if typo_days is not None:
        typed, options = typo_days
        if not stored.get(_PENDING_CLASSIFICATION_KEY):
            slot_store.set_slots("regularization", company_id, conversation_id, {"entries": []})
        labels = [_display_date(d) for d in options]
        if len(labels) > 1:
            message = (f"\"{typed}\" looks like a typo - did you mean "
                       f"{', '.join(labels[:-1])} or {labels[-1]}? Please reply with the date.")
        else:
            message = (f"\"{typed}\" looks like a typo - did you mean {labels[0]}? "
                       f"Please reply with the date.")
        # The "which date(s)?" question's own shape - no classification
        # status: status=False is what draws the red "Regularization Not
        # Available" card, and this is a question, not a refusal.
        return _hold(message, "regularization_incomplete",
                     extra={"input_required": "date", "date_options": options,
                            "requires_date_input": True})

    # ------------------------------------------------------------
    # Awaiting the employee's explicit "apply now" before we actually seed
    # the classified date and start collecting a start/end time and reason.
    # ------------------------------------------------------------
    if stored.get(_PENDING_CLASSIFICATION_KEY):
        classified_date = stored.get(_CLASSIFIED_DATE_KEY)

        if _is_explicit_cancel(query):
            slot_store.clear_slots("regularization", company_id, conversation_id)
            message = "No problem, I've cancelled the regularization request."
            return _hold(message, "regularisation_cancelled")

        if _is_apply_now_confirmation(query):
            # Every date that passed the first-step checks (several when the
            # request named several), not just the first.
            dates = stored.get(_CLASSIFIED_DATES_KEY) or [classified_date]
            seed = {"entries": [{"date": d, "_prevalidated": True} for d in dates]}
            if stored.get("employee_name"):
                seed["employee_name"] = stored["employee_name"]
            slot_store.set_slots("regularization", company_id, conversation_id, seed)
            return _pass_through()

        # Naming a genuinely different date supersedes the pending one —
        # re-classify against it instead of just repeating the same prompt.
        # _is_explicit_cancel/_is_apply_now_confirmation already ruled out
        # above, so an LLM fallback attempt here is never wasted on either.
        several = _resolve_direct_entry_dates(query, today)
        if several:
            return await _gate_several_dates(several)
        new_date = _resolve_direct_entry_date(query, today)
        if not new_date:
            new_date = await _resolve_direct_entry_date_llm_fallback(query, today, usage_events)
        if not new_date or new_date == classified_date:
            message = (
                f"Reply **apply now** to continue with your regularization "
                f"request for {_display_date(classified_date)}, or **cancel** to stop."
            )
            return _hold(
                message, "regularisation_classify",
                status=True, date_iso=classified_date,
            )
        date_iso = new_date
    else:
        several = _resolve_direct_entry_dates(query, today)
        if several:
            return await _gate_several_dates(several)
        date_iso = _resolve_direct_entry_date(query, today)
        if not date_iso and not _LOOKS_DATELESS_PATTERN.match(query):
            date_iso = await _resolve_direct_entry_date_llm_fallback(query, today, usage_events)

    # ------------------------------------------------------------
    # Fresh classification for an explicit date named in THIS message.
    # Nothing to classify yet (no date at all) — let regularisation_node's
    # own slot-flow ask "which date(s)?", unless this cycle's quota is already
    # used up: that is said NOW, not after the employee has named a date.
    # ------------------------------------------------------------
    if not date_iso:
        if not stored.get(_PENDING_CLASSIFICATION_KEY) and not _LOOKS_DATELESS_PATTERN.match(query):
            notice = await _dateless_quota_notice(
                today, bearer_token=bearer_token, company_id=company_id,
                conversation_id=conversation_id)
            if notice:
                asks_for_date = notice.endswith("?")
                if asks_for_date:
                    # Held open so the date reply ("18 sept") stays with this
                    # flow - with nothing stored it went to punch details.
                    slot_store.set_slots("regularization", company_id, conversation_id,
                                         {"entries": []})
                else:
                    slot_store.clear_slots("regularization", company_id, conversation_id)
                return _hold(notice, "regularisation_classify", status=asks_for_date)
        return _pass_through()

    # Step 1 of Duplicate > Eligibility > Quota (HA-697 AC-02/AC-03). A
    # Pending/Approved request on the date, or a lookup that could not
    # complete, stops here. An earlier Rejected/Cancelled/Withdrawn request is
    # a notice carried ahead of whatever the eligibility check says next.
    duplicate = await _check_duplicate_date(
        date_iso, bearer_token=bearer_token, company_id=company_id,
        conversation_id=conversation_id,
    )
    duplicate_data = _duplicate_check_data(duplicate)
    if duplicate["outcome"] in (DUPLICATE_BLOCKED, DUPLICATE_UNAVAILABLE):
        slot_store.clear_slots("regularization", company_id, conversation_id)
        return _hold(duplicate["message"], "regularisation_classify", status=False,
                     date_iso=date_iso, extra=duplicate_data)

    def _with_prior_notice(message: str) -> str:
        if duplicate["outcome"] == DUPLICATE_PRIOR:
            return f"{duplicate['message']}\n\n{message}"
        return message

    future_date_reason = _future_date_block_reason(date_iso, today)
    if future_date_reason:
        # It asks for a date on or before today, so the flow stays open for
        # the answer (an earlier date awaiting "apply now" is kept) - the
        # same hold-open as an invalid date.
        if not stored.get(_PENDING_CLASSIFICATION_KEY):
            slot_store.set_slots("regularization", company_id, conversation_id, {"entries": []})
        return _hold(_with_prior_notice(future_date_reason), "regularisation_classify",
                     status=False, date_iso=date_iso, extra=duplicate_data)

    # One /leave/balance read for the eligibility window AND the quota (step 3).
    settings = await _get_regularization_settings(
        bearer_token=bearer_token, company_id=company_id, conversation_id=conversation_id,
    )

    try:
        block_reason = await _classify_and_check_eligibility(
            date_iso, bearer_token=bearer_token, company_id=company_id,
            conversation_id=conversation_id, writer=writer, settings=settings,
        )
    except Exception:
        logger.exception(
            "[Graph] regularisation eligibility classification failed for %s — "
            "failing open, letting regularisation_node's own mid-flow check "
            "decide instead",
            date_iso,
        )
        slot_store.clear_slots("regularization", company_id, conversation_id)
        return _pass_through()

    if block_reason:
        if _asks_for_another_date(block_reason):
            # "You can't regularize future dates ... please give me a date on
            # or before today" asks for another date, so the flow stays open
            # for it - the same hold-open as an invalid date. Cleared, a bare
            # "2 oct" reply went to the shift lookup.
            slot_store.set_slots("regularization", company_id, conversation_id, {"entries": []})
        else:
            slot_store.clear_slots("regularization", company_id, conversation_id)
        return _hold(_with_prior_notice(block_reason), "regularisation_classify",
                     status=False, date_iso=date_iso, extra=duplicate_data)

    # Step 3 (AC-05): quota, counted from the rows the duplicate check fetched.
    # Exhausted, or a settings lookup that failed, stops here.
    quota = _check_quota(date_iso, duplicate.get("rows"), settings)
    duplicate_data = {**duplicate_data, **_quota_check_data(quota)}
    if quota["outcome"] in (QUOTA_EXHAUSTED, QUOTA_UNAVAILABLE):
        slot_store.clear_slots("regularization", company_id, conversation_id)
        return _hold(_with_prior_notice(quota["message"]), "regularisation_classify",
                     status=False, date_iso=date_iso, extra=duplicate_data)

    # Eligible — hold here and ask for the explicit "apply now" rather than
    # walking straight into collecting a start/end time and a reason.
    slot_store.set_slots(
        "regularization", company_id, conversation_id,
        {"entries": [], _PENDING_CLASSIFICATION_KEY: True, _CLASSIFIED_DATE_KEY: date_iso},
    )
    quota_line = f" {quota['message']}" if quota["outcome"] == QUOTA_OK else ""
    message = (
        f"Good news — {_display_date(date_iso)} is eligible for attendance "
        f"regularization.{quota_line}{_shift_sentence(shift_details)} Reply **apply now** and "
        f"I'll collect the remaining details (start/end time and a reason)."
    )
    return _hold(_with_prior_notice(message), "regularisation_classify", status=True,
                 date_iso=date_iso, extra=duplicate_data)


_ASKS_FOR_A_DATE_RE = re.compile(
    r"\b(?:give\s+me|tell\s+me|share|pick|choose)\b[^.]*\bdate\b|\bdate\s+instead\b", re.IGNORECASE)


def _asks_for_another_date(message: str) -> bool:
    """True when a refusal invites the employee to name a different date."""
    return bool(_ASKS_FOR_A_DATE_RE.search(message or ""))


async def _first_step_check(date_iso: str, today: date, *, bearer_token, company_id,
                            conversation_id, writer, settings, accepted: list[str]) -> dict:
    """Duplicate > Eligibility > Quota for ONE date of a several-date request -
    the same checks, in the same order, as the single-date gate.

    `accepted` are the earlier dates of this same message that passed: they
    count toward the quota as if already pending, so "28, 29 and 30 sept" with
    one request left is told about the 2nd and 3rd now, not at submit.

    {"date", "ok", "message" (why not, or None), "notice" (an earlier
    Rejected/Cancelled request on the date, or None), "quota"}."""
    out = {"date": date_iso, "ok": False, "message": None, "notice": None, "quota": None}
    duplicate = await _check_duplicate_date(
        date_iso, bearer_token=bearer_token, company_id=company_id,
        conversation_id=conversation_id)
    if duplicate["outcome"] in (DUPLICATE_BLOCKED, DUPLICATE_UNAVAILABLE):
        out["message"] = duplicate["message"]
        return out
    if duplicate["outcome"] == DUPLICATE_PRIOR:
        out["notice"] = duplicate["message"]

    reason = _future_date_block_reason(date_iso, today)
    if not reason:
        try:
            reason = await _classify_and_check_eligibility(
                date_iso, bearer_token=bearer_token, company_id=company_id,
                conversation_id=conversation_id, writer=writer, settings=settings)
        except Exception:
            # Same fail-open as the single-date gate: regularisation_node's own
            # mid-flow check (in _fetch_prefill) still decides for this date.
            logger.exception("[Graph] regularisation eligibility check failed for %s", date_iso)
            reason = None
    if reason:
        out["message"] = reason
        return out

    rows = list(duplicate.get("rows") or []) + [
        {"apply_date": d, "status_name": "pending"} for d in accepted]
    quota = _check_quota(date_iso, rows if duplicate.get("rows") is not None else None, settings)
    out["quota"] = quota
    if quota["outcome"] in (QUOTA_EXHAUSTED, QUOTA_UNAVAILABLE):
        out["message"] = quota["message"]
        return out
    out["ok"] = True
    return out


def _join_dates(isos: list[str]) -> str:
    shown = [_display_date(d) for d in isos]
    return shown[0] if len(shown) == 1 else f"{', '.join(shown[:-1])} and {shown[-1]}"


async def _dateless_quota_notice(today: date, *, bearer_token, company_id,
                                 conversation_id) -> str | None:
    """Before asking "which date?": when the CURRENT payroll cycle's quota is
    already used up, say so now rather than after the employee has named a
    date. None when there is quota left, nothing to enforce, or the check
    can't be made (the date's own checks still run once a date is given).

    A date in the PREVIOUS cycle may still be possible while it is inside the
    back-date window, so that is offered rather than refusing outright."""
    settings = await _get_regularization_settings(
        bearer_token=bearer_token, company_id=company_id, conversation_id=conversation_id)
    cycle, limit = settings.get("cycle"), settings.get("limit")
    if not settings.get("available") or cycle is None or limit is None:
        return None
    current = payroll_cycle.cycle_for(cycle, today)
    if current is None:
        return None
    try:
        result = await attendance_client.get_my_regularizations(
            bearer_token, company_id=company_id, conversation_id=conversation_id)
    except Exception:
        return None
    body = result.get("body") if isinstance(result, dict) else None
    rows = ((body or {}).get("data") or {}).get("regularizations") if isinstance(body, dict) else None
    if not isinstance(rows, list):
        return None
    used = regularisation_display.count_quota_used(rows, current)
    if used < limit:
        return None

    exhausted = (f"Your regularization quota for {current.label()} has already been used "
                 f"({used} of {limit}), so dates from {_display_date(current.start.isoformat())} "
                 f"onwards can't be regularized.")
    window = settings.get("window_days")
    if window:
        earliest = today - timedelta(days=window - 1)
        if earliest < current.start:
            last_open = current.start - timedelta(days=1)
            return (f"{exhausted} You can still regularize a date from "
                    f"{_display_date(earliest.isoformat())} to {_display_date(last_open.isoformat())}"
                    f" (the previous cycle) - which date would you like to regularize?")
    return f"{exhausted} I can't take a new regularization request right now."


def _route_after_regularisation_eligibility(state: HRState) -> str:
    if state.get("regularisation_blocked"):
        return END
    return "regularisation_node"


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

async def regularisation_node(
    state: HRState,
    writer: StreamWriter,
) -> dict:

    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    usage_events = list(state.get("usage_events", []))

    # Pre-loaded with whatever punch previews were already fetched in
    # earlier turns of this SAME conversation (see _PUNCH_PREVIEW_NAMESPACE
    # above) so they survive into the confirm turn instead of resetting to
    # empty on every node invocation.
    punch_previews: dict[str, dict] = (
        slot_store.get_slots(_PUNCH_PREVIEW_NAMESPACE, company_id, conversation_id) or {}
    )

    # The employee's shift from GET /shift-details (shift_name / start_time /
    # end_time), on every reply of this flow. A manager applying for a report
    # gets that report's shift.
    shift_details = await _get_shift_details(
        bearer_token=bearer_token, company_id=company_id, conversation_id=conversation_id,
        employee_name=(slot_store.get_slots("regularization", company_id, conversation_id)
                       or {}).get("employee_name"))

    # ================================================================
    # Safe writer
    # ================================================================

    def wrapped_writer(event: dict):
        try:
            if isinstance(event, dict) and event.get("type") == "done":
                stored_slots = (
                    slot_store.get_slots(
                        "regularization",
                        company_id,
                        conversation_id,
                    )
                    or {}
                )

                current_entries = (
                    stored_slots.get("entries")
                    or []
                )

                data = event.get("data")

                if not isinstance(data, dict):
                    data = {}

                data["filled_details"] = current_entries
                data["shift"] = shift_details

                data["punch_details"] = (
                    punch_previews.get(
                        current_entries[0]["date"]
                    )
                    if (
                        len(current_entries) == 1
                        and current_entries[0].get("date")
                        in punch_previews
                    )
                    else punch_previews
                )

                event["data"] = data

            writer(event)

        except Exception:
            # Never expose writer/enrichment errors to frontend
            logger.exception(
                "[Graph] Failed to process regularisation writer event"
            )

            # Try sending a safe error event
            try:
                writer({
                    "type": "done",
                    "intent": "regularization_error",
                    "is_hr": True,
                    "data": {
                        "answer": (
                            "I couldn't complete your regularization request right now — please try again in a moment."
                        ),
                        "node_type": "error",
                    },
                    "message": (
                        "I couldn't complete your regularization request right now — please try again in a moment."
                    ),
                    "usage_events": usage_events,
                })
            except Exception:
                logger.exception(
                    "[Graph] Failed to send regularisation writer error"
                )

    # ================================================================
    # Prefill fetch
    # ================================================================

    async def _fetch_prefill(
        entry: dict,
        w: StreamWriter,
    ) -> dict:

        try:
            date_iso = entry.get("date")

            if not date_iso:
                return {}

            # Duplicate-date check first (HA-697 AC-02/AC-03/AC-08) — the same
            # check regularisation_eligibility_node runs on a first mention,
            # here for a date changed mid-flow or handed off by attendance/
            # attendance_explain (whose "_prevalidated" screening never looked
            # at existing requests). Blocked or unavailable drops the entry via
            # slot_flow's "_blocked" handling, before any punch fetch: nothing
            # else is collected for a date that cannot proceed.
            duplicate = await _check_duplicate_date(
                date_iso, bearer_token=bearer_token, company_id=company_id,
                conversation_id=conversation_id,
            )
            if duplicate["outcome"] in (DUPLICATE_BLOCKED, DUPLICATE_UNAVAILABLE):
                entry["_blocked"] = True
                entry["_block_reason"] = duplicate["message"]
                entry["_duplicate_check"] = _duplicate_check_data(duplicate)
                return {}
            if duplicate["outcome"] == DUPLICATE_PRIOR:
                w({"type": "regularization_duplicate_notice",
                   "message": duplicate["message"],
                   "data": _duplicate_check_data(duplicate)})

            attendance = await _get_attendance_prefill(
                bearer_token=bearer_token,
                date_iso=date_iso,
                company_id=company_id,
                conversation_id=conversation_id,
                writer=w,
            )

            # The shift shown on the punch preview is the one from
            # /shift-details when it was readable; punch-details' own
            # per-day shift object is the fallback.
            if shift_details:
                attendance["preview"]["shift"] = {
                    "name": shift_details.get("shift_name"),
                    "shift_name": shift_details.get("shift_name"),
                    "start_time": shift_details.get("start_time"),
                    "end_time": shift_details.get("end_time"),
                }

            # erp-api refused the token: nothing more to collect for a request
            # that can't be submitted (see _get_attendance_prefill).
            if attendance["preview"].get("session_rejected"):
                entry["_blocked"] = True
                entry["_block_reason"] = SESSION_REJECTED_MESSAGE
                return {}

            punch_previews[date_iso] = attendance["preview"]

            # Persist immediately so it's available to a LATER turn (e.g.
            # the "yes submit it" confirm reply, which re-enters this node
            # without ever calling _fetch_prefill again — see
            # _PUNCH_PREVIEW_NAMESPACE above).
            slot_store.set_slots(
                _PUNCH_PREVIEW_NAMESPACE, company_id, conversation_id, punch_previews,
            )

            w({
                "type": "regularization_prefill_preview",
                "data": attendance["preview"],
            })

            # NEW — direct-entry eligibility gate (see
            # _regularization_eligibility_block_reason's docstring). Mutates
            # `entry` in place: slot_flow.py's multi-entry loop passes this
            # same dict by reference and drops any entry marked "_blocked"
            # right after this call, surfacing "_block_reason" as a warning
            # instead of asking for start/end time and a reason on a date
            # that was never eligible to begin with.
            settings = await _get_regularization_settings(
                bearer_token=bearer_token, company_id=company_id,
                conversation_id=conversation_id,
            )
            block_reason = await _regularization_eligibility_block_reason(
                entry,
                attendance["preview"].get("attendance_status_code"),
                attendance["preview"].get("is_regularized", False),
                bearer_token=bearer_token,
                company_id=company_id,
                conversation_id=conversation_id,
                attendance_known=bool(attendance["preview"].get("attendance_known")),
                settings=settings,
            )
            if block_reason:
                entry["_blocked"] = True
                entry["_block_reason"] = block_reason
                return attendance["slot_prefill"]

            # Step 3 (AC-05/AC-08): quota for THIS date's cycle — runs for a
            # "_prevalidated" hand-off too, since attendance's screening never
            # looked at the quota.
            quota = _check_quota(date_iso, duplicate.get("rows"), settings)
            if quota["outcome"] in (QUOTA_EXHAUSTED, QUOTA_UNAVAILABLE):
                entry["_blocked"] = True
                entry["_block_reason"] = quota["message"]
                entry["_quota_check"] = _quota_check_data(quota)

            return attendance["slot_prefill"]

        except Exception:
            logger.exception(
                "[Graph] Failed to fetch regularisation prefill "
                "for date=%s",
                entry.get("date") if isinstance(entry, dict) else None,
            )

            # Do not expose internal exception details
            try:
                w({
                    "type": "regularization_prefill_error",
                    "message": (
                        "I couldn't fetch the attendance details "
                        "for this date. Please try again."
                    ),
                })
            except Exception:
                logger.exception(
                    "[Graph] Failed to send prefill error event"
                )

            # Returning {} allows slot flow to continue without
            # exposing the underlying exception.
            return {}

    # ================================================================
    # Main node
    # ================================================================

    try:

        # ------------------------------------------------------------
        # Confirm & Submit / Cancel button — reduce its JSON payload to a
        # plain "confirm"/"cancel" message BEFORE anything else touches it,
        # so neither the structured-action parser nor (if that falls
        # through) the slot-flow LLM ever sees the raw JSON. See
        # _try_parse_confirm_or_cancel's docstring for the data-loss bug
        # this avoids.
        # ------------------------------------------------------------

        # The form's labelled TEXT submission ("Date: 04 Oct 2026 / From Time:
        # 3:00 PM / To Time: 8:00 PM / Shift Timing: ... / Reason / Comment:
        # ...") read as the form JSON it stands for. Live, the model was given
        # it raw, read nothing (four clock times, two of them the shift's) and
        # answered "I still need the start time, end time and reason".
        labelled = _labelled_form_entry(state["query"], attendance_mod._today())
        if labelled:
            logger.info("[Graph] regularisation: labelled form text read as %s",
                        {k: v for k, v in labelled.items() if k != "reason"})
            state = {**state, "query": json.dumps(labelled)}

        parsed_payload = _loads_query_object(state["query"])
        payload_entry = _payload_entry(parsed_payload)
        stored_entries = (slot_store.get_slots("regularization", company_id, conversation_id)
                          or {}).get("entries") or []
        payload_action = parsed_payload.get("action") if isinstance(parsed_payload, dict) else None

        # The confirmation card posting back EXACTLY the request already
        # stored and complete, with no "action": that is Confirm & Submit, not
        # a save. Read as a save it re-showed "Shall I go ahead and submit
        # this?" every time, and the request could never be submitted from
        # the card (live).
        if (payload_action is None and payload_entry and len(stored_entries) == 1
                and _same_entry(payload_entry, stored_entries[0])):
            logger.info("[Graph] regularisation: card re-posted the stored entry unchanged "
                        "— treating it as Confirm & Submit")
            state = {**state, "query": json.dumps({"action": "confirm"})}

        # Confirm & Submit carrying the request's fields, with NOTHING stored:
        # the stored entry was lost between turns (Redis unreachable — see
        # slot_store's in-process fallback). The employee is confirming the
        # values on the card in front of them, so those are submitted; the
        # prefill fetch re-runs every check for the date on the way, and
        # erp-api revalidates at submission regardless.
        elif payload_action == "confirm" and payload_entry and not stored_entries:
            logger.warning("[Graph] regularisation: Confirm & Submit with no stored entry — "
                           "submitting the fields the card sent")
            slot_store.set_slots("regularization", company_id, conversation_id,
                                 {"entries": [dict(payload_entry)], "employee_name": None})

        # Confirm & Submit from the FORM, carrying the times and reason the
        # employee filled in, for a date already stored. Reduced to a plain
        # "confirm" below, those fields were dropped and the stored entry -
        # often just the date - was confirmed instead ("I still need the start
        # time, end time and reason", every time). The form's values for that
        # same date are what the employee is submitting.
        elif payload_action == "confirm" and payload_entry and stored_entries:
            merged, changed = [], False
            for entry in stored_entries:
                if str(entry.get("date") or "") == str(payload_entry.get("date") or ""):
                    updated = {**entry, **payload_entry}
                    changed = changed or not _same_entry(updated, entry)
                    merged.append(updated)
                else:
                    merged.append(entry)
            if changed:
                logger.info("[Graph] regularisation: Confirm & Submit carried the form's "
                            "fields for %s — applying them", payload_entry.get("date"))
                stored = slot_store.get_slots("regularization", company_id, conversation_id) or {}
                slot_store.set_slots("regularization", company_id, conversation_id,
                                     {**stored, "entries": merged})

        confirm_or_cancel = _try_parse_confirm_or_cancel(state["query"])
        if confirm_or_cancel:
            logger.info(
                "[Graph] regularisation: button JSON resolved to action=%s "
                "— using a plain '%s' message for the slot flow",
                confirm_or_cancel, confirm_or_cancel,
            )
            state = {**state, "query": confirm_or_cancel}

        # ------------------------------------------------------------
        # Structured action
        # ------------------------------------------------------------

        structured = _try_parse_structured_action(
            state["query"]
        )

        if structured:
            try:
                structured_result = await _handle_structured_action(
                    structured,
                    company_id=company_id,
                    conversation_id=conversation_id,
                    writer=wrapped_writer,
                    usage_events=usage_events,
                )
                _clear_punch_previews_if_flow_finished(company_id, conversation_id)
                return structured_result

            except Exception:
                logger.exception(
                    "[Graph] Structured regularisation action failed"
                )

                error_message = (
                    "I couldn't process your regularization request right now — please try again in a moment."
                )

                try:
                    writer({
                        "type": "done",
                        "intent": "regularization_error",
                        "is_hr": True,
                        "data": {
                            "answer": error_message,
                            "node_type": "error",
                        },
                        "message": error_message,
                        "usage_events": usage_events,
                    })
                except Exception:
                    logger.exception(
                        "[Graph] Failed to send structured "
                        "regularisation error"
                    )

                return {
                    "response_text": error_message,
                    "usage_events": usage_events,
                }

        # ------------------------------------------------------------
        # Configure slot flow with prefill callback
        # ------------------------------------------------------------

        config = replace(
            REGULARIZATION_CONFIG,
            fetch_entry_prefill=_fetch_prefill,
            # A refusal the form can fix (shift/timing, out time before in
            # time, reason too long) brings the form back with just those
            # fields to correct, instead of "Regularization not submitted".
            correctable_refusal=lambda error, entry=None: _form_correction(
                error, shift_details, entry),
            # Replaces erp-api's sentence on the final card when the refusal
            # is one no correction can clear (see _shift_refusal_is_unfixable).
            # Wired HERE rather than on the base config because it needs this
            # turn's resolved shift, which module-level
            # _extract_failure_message has no access to.
            extract_failure_message=lambda entry, body: _submit_failure_message(
                entry, body, shift_details),
            # A time later today that hasn't come yet cannot be regularized:
            # said BEFORE sending, not after erp-api refuses it.
            pre_submit_check=_pre_submit_problem,
            # Typed times outside the assigned shift are corrected to it, and
            # the employee told so - see _align_entry_to_shift.
            # Typed in chat only: times the card's own form sent are the
            # employee's explicit choice there, and erp-api's refusal brings
            # the form back for them (see _shift_correction).
            align_entry=(None if (state.get("query") or "").lstrip().startswith("{")
                         else lambda entry: _align_entry_to_shift(entry, shift_details)),
        )

        # ------------------------------------------------------------
        # Load stored regularisation slots
        # ------------------------------------------------------------

        try:
            stored = (
                slot_store.get_slots(
                    "regularization",
                    company_id,
                    conversation_id,
                )
                or {}
            )

            candidate_dates = stored.get(
                "candidate_dates"
            )

        except Exception:
            logger.exception(
                "[Graph] Failed to load regularisation slots"
            )

            stored = {}
            candidate_dates = None

        # ------------------------------------------------------------
        # Explicit "start a new request" — reset to a blank slate BEFORE
        # anything below ever treats `stored` as "already collected" (see
        # _is_explicit_new_request's own comment for the observed bug this
        # closes: a stale/finished entry from an earlier turn otherwise
        # keeps getting silently re-displayed instead of the flow
        # restarting from "which date(s)?"). Also drops the cached punch
        # previews (same cleanup _clear_punch_previews_if_flow_finished
        # does once a flow ends) since they're tied to the OLD date(s) and
        # must not leak into the fresh request's prefill.
        # ------------------------------------------------------------

        if (stored.get("entries") or stored.get("candidate_dates")) and _is_explicit_new_request(state["query"]):
            logger.info(
                "[Graph] regularisation: explicit new-request phrasing "
                "detected — resetting pending entries before this turn "
                "is processed"
            )
            slot_store.set_slots(
                "regularization", company_id, conversation_id,
                {"entries": [], "employee_name": None},
            )
            slot_store.clear_slots(_PUNCH_PREVIEW_NAMESPACE, company_id, conversation_id)
            punch_previews.clear()
            stored = {}
            candidate_dates = None

        # ------------------------------------------------------------
        # Reject an explicit date ATTEMPT that isn't a real calendar date
        # ("10/45/2026", "31/02/2026", "30 feb") — but ONLY while no entry
        # is pending yet (this message is the FIRST answer to "which
        # date(s)?"). Once an entry already exists, the employee is far
        # more likely answering the START/END TIME question instead — and
        # a dash-separated clock time typo ("10-45" for 10:45) or shorthand
        # time range ("9-6" for 9 to 6) matches the exact same DD-MM shape
        # this check looks for. Running it unconditionally on every
        # message (observed regression) misfired on a time answer and
        # rejected it outright as "not a valid date", silently discarding
        # the start/end time the employee had actually just provided.
        # ------------------------------------------------------------

        if not stored.get("entries"):
            invalid_date = date_query_resolver.resolve(state["query"], attendance_mod._today())
            if isinstance(invalid_date, date_query_resolver.InvalidExplicitDate):
                error_message = (
                    f"'{invalid_date.matched_text}' isn't a valid date — please "
                    f"check the day and month (day first, e.g. DD/MM/YYYY) and try again."
                )
                writer({
                    "type": "done",
                    "intent": "regularization_incomplete",
                    "is_hr": True,
                    "data": {"answer": error_message, "shift": shift_details},
                    "message": error_message,
                    "usage_events": usage_events,
                })
                return {"response_text": error_message, "usage_events": usage_events}

        # ------------------------------------------------------------
        # Run slot flow
        # ------------------------------------------------------------

        try:
            result = await run_slot_flow(
                config,
                state,
                wrapped_writer,
                candidate_dates=candidate_dates,
            )

            _clear_punch_previews_if_flow_finished(company_id, conversation_id)

            return result

        except Exception:
            logger.exception(
                "[Graph] Regularisation slot flow failed"
            )

            error_message = (
                "I couldn't process your regularization request right now — please try again in a moment."
            )

            try:
                writer({
                    "type": "done",
                    "intent": "regularization_error",
                    "is_hr": True,
                    "data": {
                        "answer": error_message,
                        "node_type": "error",
                    },
                    "message": error_message,
                    "usage_events": usage_events,
                })

            except Exception:
                logger.exception(
                    "[Graph] Failed to send regularisation "
                    "slot-flow error"
                )

            return {
                "response_text": error_message,
                "usage_events": usage_events,
            }

    # ================================================================
    # GLOBAL SAFETY NET
    # ================================================================

    except Exception:
        logger.exception(
            "[Graph] Unexpected unhandled error "
            "in regularisation_node"
        )

        error_message = (
            "I couldn't process your regularization request right now — please try again in a moment."
        )

        try:
            writer({
                "type": "done",
                "intent": "regularization_error",
                "is_hr": True,
                "data": {
                    "answer": error_message,
                    "node_type": "error",
                },
                "message": error_message,
                "usage_events": usage_events,
            })

        except Exception:
            logger.exception(
                "[Graph] Failed to send regularisation "
                "error event"
            )

        return {
            "response_text": error_message,
            "usage_events": usage_events,
        }



def _build_regularisation_pending_hint(entries: list, has_free_text_pending: bool) -> str:
    """Tells the intent classifier about an in-progress regularisation
    request so it can tell a genuine continuation apart from a fresh,
    unrelated query — used only as the fallback once fast_classify and the
    deterministic checks in classify_node's mid-flow regularisation block
    (see 'existing_regularization_slots') can't confidently decide either
    way.

    The two states need OPPOSITE framing, not just different wording:
    - Still missing a field: the classifier needs ENCOURAGEMENT to read a
      bare "10am to 7pm" or "forgot to punch out" as 'regularisation' — on
      its own that fragment carries no keyword at all.
    - Already complete, awaiting confirmation: by the time this hint is
      built, the deterministic confirm/cancel check already ran and MISSED
      (see the mid-flow block) — so encouraging 'regularisation' here would
      just make the classifier repeat that miss. What it actually needs is
      the OPPOSITE nudge: this request is disambiguated background state,
      not a reason to bias classification of the current message. Without
      this explicit override, the generic "short follow-up of an earlier
      HR question -> matching intent" instruction elsewhere in the prompt
      (plus the review card still sitting in recent conversation context)
      pulls the model back toward 'regularisation' anyway whenever the new
      message is topically close — confirmed live: "why was I marked
      absent on the 18th", asked right after the regularisation review
      card for the 18th, kept getting classified as 'regularisation'
      instead of 'attendance_explain' purely because it named the same
      date, corrupting the still-pending entry's prefilled times in the
      process (see slot_flow.py's merge behavior)."""
    dates = ", ".join(e.get("date") for e in entries if e.get("date")) or "an unspecified date"
    if has_free_text_pending:
        return (
            "IMPORTANT — PENDING FLOW: The user has an UNFINISHED attendance regularisation "
            f"request in progress for {dates}, still missing a time or a reason. If the current "
            "query supplies a date, time, or reason — or otherwise continues answering that "
            "request — classify it as 'regularisation'. Only classify it as something else if "
            "it is clearly a new, unrelated question or request.\n\n"
        )
    return (
        "IMPORTANT — PENDING FLOW: The user has a COMPLETE attendance regularisation request "
        f"for {dates} sitting unconfirmed in the background. It was already checked for an "
        "explicit confirm ('yes'/'submit'/'go ahead') or cancel ('no'/'cancel'/'never mind') "
        "reply and this message is NEITHER — so do NOT classify it as 'regularisation' just "
        "because it mentions the same date or general attendance topic, and IGNORE the "
        "'short follow-up' guidance elsewhere for this message. Classify it strictly by what "
        "the user is actually asking. Example: a question about WHY a day was marked a "
        "certain way is 'attendance_explain', not 'regularisation', even for the exact same "
        "date as the pending request.\n\n"
    )
