"""services/attendance_explain.py

Attendance-Explain (FR-04.1 / FR-04.2) — explains WHY a specific day was
classified Present/Half Day/Late/Absent/Missing Punch, distinct from the
plain "attendance" intent (live record lookup, services/attendance.py) and
from "punch_details" (raw punch/shift/work-hours display,
services/punch_details.py).

Combines two confirmed real erp-api endpoints:
  - erp_client.get_attendance_status()  -> the authoritative classification
                                            LABEL (Present/Half Day/Late/
                                            Absent/Missing Punch)
  - erp_client.get_punch_time()         -> supporting evidence: shift timing
                                            + raw punch check-in/check-out
                                            records

Neither endpoint returns a grace-period threshold or a rule-engine-computed
variance/delta string, so that one piece of FR-04.1/04.2 still can't be
rendered — the node says so explicitly rather than computing it itself
(AC5 forbids Helix AI from independently calculating grace periods,
thresholds, or deviations). Punch-details is supporting evidence only: if
it's unavailable, the node still answers with the status label alone
rather than blocking the whole response.
"""
import re
import difflib
import logging
from datetime import date, timedelta
from typing import Optional

from langgraph.types import StreamWriter

import services.erp_client as erp_client
from services.ai_service import (
    _call_llm,
    _extract_text,
    _safe_json_parse,
    _normalize_usage,
    INTENT_MODEL,
)

from services.attendance import (
    _seed_pending_regularization,
    _is_regularizable,
    _wants_regularization,
    _handoff_to_regularisation,
    _build_attendance_date_extraction_prompt,
    _resolve_date_expression,
    _resolve_explicit_date_deterministic,
)
# Reused so a regularisation offer made HERE seeds the same date-only
# slot_store entry attendance_node seeds for its own offer, and so BOTH
# nodes agree on which status is actually regularizable — attendance.py's
# _is_regularizable checks the RAW erp-api label against HALF_DAY_ABSENT_STATUS
# = ["Half Day Absent"] specifically, not the "late"/"absent" slugs below
# (those two only pick which _ATTENDANCE_NEXT_ACTION_PROMPTS text to show;
# "Half Day Absent" itself slugifies to "half_day_absent", which isn't
# "late" or "absent" at all). Without this shared check, regularisation_node's
# punch-time prefetch (services/regularisation_node.py's _fetch_prefill,
# which only fires for an entry that already has a date) has nothing to
# fetch for, and a follow-up "Fix it Now" after THIS node's offer lands on
# a review card with no date and no prefilled check-in/check-out —
# confirmed live.
from services.attendance import _seed_pending_regularization, _is_regularizable, _today

logger = logging.getLogger(__name__)

_ADVERSE_ATTENDANCE_STATUSES = {"half_day_absent", "missing_punch"}

# Keyed by status — the specific, relevant follow-up action for that adverse
# outcome (AC6). Anything not in _ADVERSE_ATTENDANCE_STATUSES (present, half
# day) gets no next-action prompt at all.
#
# "late" and plain "absent" deliberately do NOT get the regularization
# offer — attendance.py's _is_regularizable/HALF_DAY_ABSENT_STATUS treats
# ONLY "Half Day Absent" as regularizable, so offering it for those two
# would invite a request the flow doesn't actually seed a date for,
# reproducing the exact broken-review-card bug "half_day_absent" was just
# fixed for. If they need their own follow-up action later, it must be
# something other than the regularization offer.
_ATTENDANCE_NEXT_ACTION_PROMPTS = {
    "half_day_absent": "Would you like to apply for Attendance Regularization?",
    "missing_punch": "Would you like to check your attendance details?",
}

# erp-api returns human-readable Title Case labels ("Present", "Half Day",
# "Missing Punch"); normalized here to match the slugs used by
# _ATTENDANCE_NEXT_ACTION_PROMPTS / _ADVERSE_ATTENDANCE_STATUSES above.
# "half day absent" is listed explicitly (not left to the fallback
# key.replace(" ", "_") below) because it's the one status that also has to
# line up with attendance.py's _is_regularizable/HALF_DAY_ABSENT_STATUS —
# both attendance_node and this node read the SAME erp-api endpoint
# (/api/v1/ai/attendance/query, see erp_client.get_attendance_query vs
# get_attendance_status), so "Half Day Absent" is a real label this node
# sees too, not just attendance_node's. Without this entry it fell through
# to the fallback anyway (same slug value), but wasn't in
# _ADVERSE_ATTENDANCE_STATUSES above — so next_action, and therefore the
# regularisation-slot seeding below, silently never fired for it at all.
_ATTENDANCE_STATUS_SLUGS = {
    "present": "present",
    "half day": "half_day",
    "half day absent": "half_day_absent",
    "late": "late",
    "absent": "absent",
    "missing punch": "missing_punch",
}


def _slugify_attendance_status(label: str) -> str:
    key = (label or "").strip().lower()
    return _ATTENDANCE_STATUS_SLUGS.get(key, key.replace(" ", "_"))


def _classify_attendance_status(status_label: str) -> Optional[str]:
    """"Half Day Absent" -> "Missing Punch" (erp-api's own status label maps
    onto the story's Missing Punch category); every other status -> None.
    Deterministic lookup only — never inferred."""
    if (status_label or "").strip().lower() == "half day absent":
        return "Missing Punch"
    return None


def _render_attendance_card(date: str, day: str, status_label: str, punch_data: Optional[dict]) -> str:
    """Pure string formatting of erp-api's own status label plus (when
    available) shift timing and raw punch records — no computed reasoning,
    grace period, or variance is added, since erp-api doesn't return any of
    those (see the module-level docstring)."""
    when = f"{date} ({day})" if day else date
    lines = [f"Your attendance for {when} was marked **{status_label}**."]

    if punch_data:
        shift = punch_data.get("shift") or {}
        shift_bits = []
        if shift.get("name"):
            shift_bits.append(shift["name"])
        if shift.get("start_time") and shift.get("end_time"):
            shift_bits.append(f"{shift['start_time']}–{shift['end_time']}")
        if shift_bits:
            lines.append("Scheduled shift: " + ", ".join(shift_bits))

        punches = punch_data.get("punches") or []
        if punches:
            punch_lines = [
                f"  #{p.get('punch_number')}: check-in {p.get('check_in') or 'missing'}, "
                f"check-out {p.get('check_out') or 'missing'}"
                for p in punches
            ]
            lines.append("Recorded punches:\n" + "\n".join(punch_lines))
        else:
            lines.append("Recorded punches: none found for this date.")

        work_hours = punch_data.get("work_hours") or {}
        if work_hours.get("available") and work_hours.get("value"):
            lines.append(f"Total work hours: {work_hours['value']}")

    lines.append(
        "The exact grace-period threshold and rule-engine variance behind this "
        "classification aren't available from the attendance system yet."
    )
    return "\n\n".join(lines)


def _build_status_reason(status_label: str, target_date: str, punch_data: Optional[dict]) -> Optional[str]:
    """Purely observational — states facts already present in erp-api's own
    response (punch presence/absence/completeness, the is_regularized flag,
    whether the date is in the future). Deliberately does NOT compare punch
    timestamps against shift start/end to conclude WHY a status (Present/
    Late/Absent/...) was assigned — that would be exactly the locally-
    computed classification logic AC5 forbids. Returns None when there's no
    fact-based basis to report (e.g. punch-details itself was unavailable),
    never a guess."""
    from datetime import date as _date

    try:
        if _date.fromisoformat(target_date) > _today():
            return "This date is in the future, so no attendance has been recorded yet."
    except (TypeError, ValueError):
        pass

    if not punch_data:
        return None

    attendance_info = punch_data.get("attendance") or {}
    if attendance_info.get("is_regularized"):
        return "This attendance record was manually regularized."

    punches = punch_data.get("punches") or []
    punch_status = punch_data.get("punch_status")

    if not punches or punch_status == "no_records":
        return "No punch records were found for this date."

    complete = [p for p in punches if p.get("complete")]
    incomplete = [p for p in punches if not p.get("complete")]

    if incomplete and not complete:
        return (f"{len(incomplete)} punch session(s) were recorded but incomplete "
                f"(missing a check-in or check-out).")
    if incomplete:
        return (f"{len(complete)} complete and {len(incomplete)} incomplete punch "
                f"session(s) were recorded for this date.")
    return f"{len(complete)} punch session(s) were recorded for this date."


# Backstop against the LLM inferring WHY a status was assigned (e.g.
# comparing punch time to shift time to conclude lateness) despite being
# explicitly told not to — models don't follow such instructions with 100%
# reliability. If any of these appear in the generated reason, it's
# discarded in favor of the deterministic _build_status_reason text (AC5
# enforcement, not just a prompt instruction).
_FORBIDDEN_REASONING_PATTERNS = [
    re.compile(r"\bgrace\s*period\b", re.IGNORECASE),
    re.compile(r"\b(exceeded|exceeding)\b", re.IGNORECASE),
    re.compile(r"\bvariance\b", re.IGNORECASE),
    re.compile(r"\bdeviation\b", re.IGNORECASE),
    re.compile(r"\b(late|early)\s+by\b", re.IGNORECASE),
    re.compile(r"\bminutes?\s+(late|early|after|before)\b", re.IGNORECASE),
    re.compile(r"\bbecause\s+(you|your)\b[\w\s]{0,40}?\b(check|punch|shift|late|early|arrived)\b", re.IGNORECASE),
]


def _message_smuggles_computed_reasoning(text: str) -> bool:
    return any(p.search(text) for p in _FORBIDDEN_REASONING_PATTERNS)


def _build_status_reason_prompt(status_label: str, deterministic_reason: str) -> str:
    """Facts-only NLG prompt whose ONLY job is to rephrase the status AND
    the deterministic reason (already fact-checked by _build_status_reason)
    together into one natural sentence for the "reason" field. The LLM is
    never shown raw shift/punch timestamps here, so it has nothing to
    compare and nothing to compute from even if it tried."""
    return f"""Write ONE short, natural sentence that reports BOTH the attendance status AND the fact below together, for display next to a status badge in an HR app.

Status: {status_label}
FACT (rephrase this exactly — do not add to it or explain it further): {deterministic_reason}

HARD RULES — violating any of these is a failure:
1. Your sentence MUST mention the status ("{status_label}") AND rephrase the FACT above — both, together, naturally, as a single sentence.
2. Do not add any new information, times, or numbers not already in the FACT.
3. NEVER explain WHY the status was assigned beyond what the FACT already states. Never mention shift times, grace periods, thresholds, policy rules, or minutes early/late/over.
4. Do NOT use words like "late by", "early by", "exceeded", "variance", "deviation", "grace period", or start with "because you...".
5. Exactly ONE sentence. No greeting, no closing, no offer to help further — just the status and the fact, rephrased naturally.
6. Output ONLY that one sentence — no JSON, no markdown fences, no preamble.

Write the sentence now."""


async def _generate_status_reason_via_llm(
    status_label: str, deterministic_reason: Optional[str],
) -> tuple[Optional[str], Optional[dict]]:
    """Best-effort natural-language rephrasing of the status + the
    deterministic, already fact-checked reason together — populates the
    "reason" field only, never "answer"/"message" (those stay fully
    deterministic, see _render_attendance_card). Returns (None, None) when
    there's no deterministic reason to rephrase, on any call failure, on
    empty output, or if the output smuggles in computed reasoning (AC5
    backstop) — callers fall back to the deterministic reason string in
    every case, never block the response on this."""
    if not deterministic_reason:
        return None, None
    try:
        prompt = _build_status_reason_prompt(status_label, deterministic_reason)
        raw = await _call_llm(prompt, max_tokens=100, model=INTENT_MODEL)
        text = _extract_text(raw).strip()
        usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
    except Exception as e:
        logger.warning(f"[AttendanceExplain] LLM reason generation failed: {e}")
        return None, None

    if not text:
        return None, None
    if _message_smuggles_computed_reasoning(text):
        logger.warning(
            "[AttendanceExplain] LLM reason contained forbidden reasoning language, discarding: %r",
            text[:200],
        )
        return None, None
    return text, usage


_WEEKDAY_NAMES = {
    "monday": 0, "tuesday": 1, "wednesday": 2, "thursday": 3,
    "friday": 4, "saturday": 5, "sunday": 6,
}

# ── Compound "<year/month qualifier> + <ordinal weekday>" resolution ────────
# "last month's first Friday", "last year first month last Friday". Ported
# from services/punch_details.py's resolver of the same name — see that
# module for the fuller design notes. All real date arithmetic, never
# handed to an LLM.
_ORDINAL_WEEKDAY_WORDS = {
    "first": 1, "1st": 1, "second": 2, "2nd": 2, "third": 3, "3rd": 3, "fourth": 4, "4th": 4,
    "fifth": 5, "5th": 5,
}
_ORDINAL_WEEKDAY_PATTERN = re.compile(
    r"\b(first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|last)\s+(?:for\s+|on\s+|of\s+)?("
    + "|".join(_WEEKDAY_NAMES) + r")\b",
    re.IGNORECASE,
)
_LAST_YEAR_PATTERN = re.compile(r"\blast\s+year\b", re.IGNORECASE)
_THIS_YEAR_PATTERN = re.compile(r"\bthis\s+year\b", re.IGNORECASE)
_EXPLICIT_YEAR_PATTERN = re.compile(r"\b((?:19|20)\d{2})\b")

_MONTH_NAMES = {
    "january": 1, "jan": 1, "february": 2, "feb": 2, "march": 3, "mar": 3, "april": 4, "apr": 4,
    "may": 5, "june": 6, "jun": 6, "july": 7, "jul": 7, "august": 8, "aug": 8,
    "september": 9, "sep": 9, "sept": 9, "october": 10, "oct": 10, "november": 11, "nov": 11,
    "december": 12, "dec": 12,
}
_EXPLICIT_MONTH_NAME_PATTERN = re.compile(r"\b(" + "|".join(_MONTH_NAMES.keys()) + r")\b", re.IGNORECASE)
_ORDINAL_MONTH_WORDS = {
    "first": 1, "1st": 1, "second": 2, "2nd": 2, "third": 3, "3rd": 3, "fourth": 4, "4th": 4,
    "fifth": 5, "5th": 5, "sixth": 6, "6th": 6, "seventh": 7, "7th": 7, "eighth": 8, "8th": 8,
    "ninth": 9, "9th": 9, "tenth": 10, "10th": 10, "eleventh": 11, "11th": 11, "twelfth": 12, "12th": 12,
}
_ORDINAL_MONTH_PATTERN = re.compile(
    r"\b(first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|sixth|6th|seventh|7th|eighth|8th|"
    r"ninth|9th|tenth|10th|eleventh|11th|twelfth|12th)\s+month\b",
    re.IGNORECASE,
)
_LAST_MONTH_PATTERN = re.compile(r"\blast\s+month\b", re.IGNORECASE)
_THIS_MONTH_PATTERN = re.compile(r"\bthis\s+month\b", re.IGNORECASE)

# Signals a month/year qualifier is present elsewhere in the query that the
# bare weekday loop further down must NOT swallow — see
# _resolve_year_month_weekday below for the actual compound resolution.
_MONTH_YEAR_QUALIFIER_PATTERN = re.compile(
    r"\b(last|this|next)\s+(month|year)\b|"
    r"\b(19|20)\d{2}\b|"
    r"\b(january|february|march|april|may|june|july|august|september|october|november|december|"
    r"jan|feb|mar|apr|jun|jul|aug|sep|sept|oct|nov|dec)\b",
    re.IGNORECASE,
)
_LAST_WEEK_QUALIFIER_PATTERN = re.compile(r"\blast\s+week\b", re.IGNORECASE)
_THIS_WEEK_QUALIFIER_PATTERN = re.compile(r"\bthis\s+week\b", re.IGNORECASE)


def _last_day_of_month(year: int, month: int) -> int:
    next_month_first = date(year + 1, 1, 1) if month == 12 else date(year, month + 1, 1)
    return (next_month_first - timedelta(days=1)).day


def _nth_weekday_of_month(year: int, month: int, weekday: int, n: int) -> Optional[date]:
    first = date(year, month, 1)
    day = 1 + ((weekday - first.weekday()) % 7) + (n - 1) * 7
    if day > _last_day_of_month(year, month):
        return None
    return date(year, month, day)


def _last_weekday_of_month(year: int, month: int, weekday: int) -> date:
    last = date(year, month, _last_day_of_month(year, month))
    return last - timedelta(days=(last.weekday() - weekday) % 7)


def _resolve_year_month_weekday(query: str, today: date) -> Optional[str]:
    """"last month's first Friday", "last year first month last Friday".
    Requires an ORDINAL word directly before the weekday name AND at least
    one year/month qualifier elsewhere in the query; a bare ordinal
    weekday with no scoping returns None here."""
    text = query.lower()

    ordinal_weekday_match = _ORDINAL_WEEKDAY_PATTERN.search(text)
    if not ordinal_weekday_match:
        return None
    ordinal_word = ordinal_weekday_match.group(1).lower()
    target_weekday = _WEEKDAY_NAMES[ordinal_weekday_match.group(2).lower()]

    explicit_year = _EXPLICIT_YEAR_PATTERN.search(text)
    has_last_year = bool(_LAST_YEAR_PATTERN.search(text))
    has_this_year = bool(_THIS_YEAR_PATTERN.search(text))
    has_year_qualifier = bool(explicit_year or has_last_year or has_this_year)

    explicit_month = _EXPLICIT_MONTH_NAME_PATTERN.search(text)
    ordinal_month = _ORDINAL_MONTH_PATTERN.search(text)
    has_last_month = bool(_LAST_MONTH_PATTERN.search(text))
    has_this_month = bool(_THIS_MONTH_PATTERN.search(text))
    has_month_qualifier = bool(explicit_month or ordinal_month or has_last_month or has_this_month)

    if not has_year_qualifier and not has_month_qualifier:
        return None

    month_year_delta = 0
    if explicit_month:
        month = _MONTH_NAMES[explicit_month.group(1).lower()]
    elif ordinal_month:
        month = _ORDINAL_MONTH_WORDS[ordinal_month.group(1).lower()]
    elif has_last_month:
        if has_year_qualifier:
            month = 12
        elif today.month == 1:
            month, month_year_delta = 12, -1
        else:
            month = today.month - 1
    else:
        month = today.month

    if explicit_year:
        year = int(explicit_year.group(1))
    elif has_last_year:
        year = today.year - 1
    elif has_this_year:
        year = today.year
    else:
        year = today.year + month_year_delta

    if ordinal_word == "last":
        target = _last_weekday_of_month(year, month, target_weekday)
    else:
        target = _nth_weekday_of_month(year, month, target_weekday, _ORDINAL_WEEKDAY_WORDS[ordinal_word])

    return target.isoformat() if target else None


# "day before "/"day after " each shift the named day by one more (so "day
# after tomorrow" = +2, "day before yesterday" = -2, "day after yesterday"
# = 0 — colloquial for today) — applied as a uniform +-1 delta on top of the
# bare word's own offset. Ported from punch_details.py's resolver of the
# same name, typo tolerance included (difflib, cutoff swept there against
# real typos and common query vocabulary with no false positives at 0.8).
_RELATIVE_DAY_WORDS = ["yesterday", "tomorrow", "today"]
_RELATIVE_DAY_BASE_OFFSETS = {"yesterday": -1, "today": 0, "tomorrow": 1}
_RELATIVE_DAY_PREFIX_DELTAS = {"before": -1, "after": 1}
_RELATIVE_DAY_PATTERN = re.compile(
    r"\b(day\s+(?:before|after)\s+)?(yesterday|tomorrow|today)\b", re.IGNORECASE,
)
_RELATIVE_DAY_TYPO_CUTOFF = 0.8
_RELATIVE_DAY_TYPO_TOKEN_PATTERN = re.compile(
    r"\b(day\s+(?:before|after)\s+)?([a-z]{4,10})\b", re.IGNORECASE,
)


def _resolve_relative_day_offset(text: str) -> Optional[int]:
    m = _RELATIVE_DAY_PATTERN.search(text)
    if m:
        prefix, word = m.group(1), m.group(2).lower()
    else:
        prefix = word = None
        for tm in _RELATIVE_DAY_TYPO_TOKEN_PATTERN.finditer(text):
            token = tm.group(2).lower()
            close = difflib.get_close_matches(
                token, _RELATIVE_DAY_WORDS, n=1, cutoff=_RELATIVE_DAY_TYPO_CUTOFF,
            )
            if close:
                prefix, word = tm.group(1), close[0]
                break
        if word is None:
            return None

    offset = _RELATIVE_DAY_BASE_OFFSETS[word]
    if prefix:
        offset += _RELATIVE_DAY_PREFIX_DELTAS[prefix.strip().split()[1].lower()]
    return offset


def _resolve_relative_date_deterministically(query: str) -> Optional[str]:
    """Handles "today" / "yesterday" / "tomorrow" / "day before yesterday" /
    "day after tomorrow" (typo-tolerant) / weekday names ("Monday", "last
    Monday", "next Monday", "last week Monday") with plain date arithmetic
    — zero risk of the off-by-a-day errors an LLM can make doing this kind
    of calculation (confirmed live: gpt-4o-mini resolved a bare "Monday" to
    a Sunday). Returns None for anything else (explicit dates, month/year-
    qualified compounds, ordinals, etc.), which falls through to the
    LLM-based extraction below — that class of reference genuinely needs
    NLU, this one doesn't."""
    from datetime import timedelta as _timedelta
    text = query.lower()
    today = _today()

    relative_day_offset = _resolve_relative_day_offset(text)
    if relative_day_offset is not None:
        return (today + _timedelta(days=relative_day_offset)).isoformat()

    # A month/year qualifier changes what a weekday name means — resolve it
    # properly via _resolve_year_month_weekday rather than letting the bare
    # weekday loop below confidently match the wrong day. Only defer to the
    # LLM fallback if that compound resolver itself can't find an ordinal
    # weekday to anchor on (e.g. a bare "last month" with no day named).
    if _MONTH_YEAR_QUALIFIER_PATTERN.search(text):
        return _resolve_year_month_weekday(query, today)

    # "last week Wednesday" / "this week Friday" — NOT the same as bare
    # "last Wednesday" below; they can disagree by a full week depending on
    # what day today is (said on a Thursday, "last Wednesday" is
    # yesterday, but "last week Wednesday" is the prior calendar week).
    has_last_week = bool(_LAST_WEEK_QUALIFIER_PATTERN.search(text))
    has_this_week = bool(_THIS_WEEK_QUALIFIER_PATTERN.search(text))
    if has_last_week or has_this_week:
        for name, weekday_idx in _WEEKDAY_NAMES.items():
            if not re.search(rf"\b{name}\b", text):
                continue
            this_monday = today - _timedelta(days=today.weekday())
            week_monday = this_monday - _timedelta(days=7) if has_last_week else this_monday
            return (week_monday + _timedelta(days=weekday_idx)).isoformat()
        return None

    for name, weekday_idx in _WEEKDAY_NAMES.items():
        if not re.search(rf"\b{name}\b", text):
            continue
        if re.search(rf"\bnext\s+{name}\b", text):
            delta = (weekday_idx - today.weekday()) % 7 or 7
            return (today + _timedelta(days=delta)).isoformat()
        # Bare "Monday" or "last Monday" — attendance is always retrospective
        # (never a future date), so both mean the most recent occurrence,
        # including today itself if today IS that weekday.
        delta = (today.weekday() - weekday_idx) % 7
        return (today - _timedelta(days=delta)).isoformat()

    return None


async def _resolve_attendance_date(query: str, context: list) -> tuple[str, list]:
    """Resolves which calendar day the user means. Deterministic weekday/
    today/yesterday resolution first (see above); only falls back to an LLM
    call for phrasings that genuinely need NLU (explicit dates like "June
    2nd 2026"). Defaults to today when even that can't resolve it — the
    actual status always comes from erp-api regardless.

    _build_attendance_date_extraction_prompt/_resolve_date_expression are
    attendance.py's SYMBOLIC extractor — it takes `today` (a date), not a
    conversation `context`, and returns {"type": ...} for Python-side
    resolution, never a flat {"date": ...} string. A previous version of
    this function called the old (since-removed) ai_service.py extractor,
    which had that flat-date contract; after the merge that dropped it,
    this got wired to attendance.py's extractor by name only, without
    updating the call — passing `context` where `today` was expected threw
    inside the prompt builder every time, silently swallowed below, always
    falling back to today's date regardless of what was actually asked
    (observed bug: an explicit date like "12-08" always came back as
    today)."""
    deterministic = _resolve_relative_date_deterministically(query)
    if deterministic:
        return deterministic, []

    today = _today()

    # Explicit numeric (DD/MM(/YYYY)) or day+named-month dates are a closed,
    # unambiguous shape — resolved locally rather than trusting the LLM to
    # follow the day-first/current-year rules every time (see the module
    # docstring above and attendance.py's own deterministic layer, which
    # this reuses directly).
    explicit = _resolve_explicit_date_deterministic(query, today)
    if explicit:
        resolved = _resolve_date_expression(explicit, today)
        if resolved and resolved.get("type") == "single":
            return resolved["date"].isoformat(), []

    usage_events: list = []
    try:
        prompt = _build_attendance_date_extraction_prompt(query, today)
        raw = await _call_llm(prompt, max_tokens=200, model=INTENT_MODEL)
        parsed = _safe_json_parse(_extract_text(raw))
        usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
        if usage:
            usage_events.append({"source": "attendance_date_extraction", "usage": usage})
        resolved = _resolve_date_expression(parsed, today) if isinstance(parsed, dict) else None
        date = (
            resolved["date"].isoformat()
            if resolved and resolved.get("type") == "single"
            else None
        )
    except Exception as e:
        logger.warning(f"[AttendanceExplain] date extraction failed: {e}")
        date = None

    return date or today.isoformat(), usage_events


async def attendance_explain_node(state: dict, writer: StreamWriter) -> dict:
    query = state["query"]
    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", []))

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

    date, date_usage = await _resolve_attendance_date(query, state.get("context", []))
    usage_events.extend(date_usage)
    logger.info("[AttendanceExplain] query=%r -> resolved date=%s", query, date)

    writer({"type": "fetching_attendance", "message": "Checking your attendance record..."})
    try:
        result = await erp_client.get_attendance_status(
            bearer_token, date, date, company_id=company_id, conversation_id=conversation_id,
        )
    except erp_client.ErpApiTimeout:
        return _finish("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 caught first, or the general clause below
    # silently swallows every 401 into the wrong message.
    except erp_client.ErpApiUnauthorized:
        return _finish("Sorry, your session has expired — please log in again to continue.")
    except erp_client.ErpApiUnavailable:
        return _finish("I'm unable to reach the HR system right now — please try again shortly.")

    records = result["body"].get("data", {}).get("records") or []
    record = next((r for r in records if r.get("date") == date), None)

    # AC7's spirit — never invent a status erp-api didn't actually return.
    if not record or not record.get("status"):
        logger.warning(
            "[AttendanceExplain] no record for resolved date=%s | "
            "erp-api returned %d record(s), dates=%s",
            date, len(records), [r.get("date") for r in records],
        )
        return _finish("Attendance explanation details are currently unavailable. Please try again later.")

    logger.info("[AttendanceExplain] date=%s -> status=%s", date, record["status"])

    status_label = record["status"]
    status_slug = _slugify_attendance_status(status_label)
    day = record.get("day", "")

    # Punch-details is supporting evidence only — the answer already has its
    # required anchor (the status label) from get_attendance_status above,
    # so a failure here degrades to a status-only answer rather than
    # blocking the whole response.
    punch_data = None
    try:
        punch_result = await erp_client.get_punch_time(
            bearer_token, company_id=company_id, conversation_id=conversation_id, date=date,
        )
        punch_data = punch_result["body"].get("data")
    except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized) as e:
        logger.warning("[AttendanceExplain] punch-details unavailable, degrading to status-only: %s", e)

    message = _render_attendance_card(date, day, status_label, punch_data)

    next_action = _ATTENDANCE_NEXT_ACTION_PROMPTS.get(status_slug) if status_slug in _ADVERSE_ATTENDANCE_STATUSES else None
    if next_action:
        message = f"{message}\n\n{next_action}"
        if _is_regularizable(status_label):
            # Mirrors attendance.py's own pre-seeding ahead of its identical
            # offer — puts the date in slot_store now, before the user even
            # replies, so regularisation_node's punch-time prefill has a
            # date to work with on the very next turn. Checked against the
            # RAW status label (matching attendance.py's own definition),
            # not status_slug — see the import comment above.
            _seed_pending_regularization(company_id, conversation_id, date_iso=date)

    deterministic_reason = _build_status_reason(status_label, date, punch_data)
    llm_reason, reason_usage = await _generate_status_reason_via_llm(status_label, deterministic_reason)
    if reason_usage:
        usage_events.append({"source": "attendance_reason_generation", "usage": reason_usage})
    reason = llm_reason or deterministic_reason

    classification = _classify_attendance_status(status_label)

    card_data = {"date": date, "day": day, "status": status_label, "classification": classification}
    if reason:
        card_data["reason"] = reason
    if punch_data:
        card_data.update({
            "shift": punch_data.get("shift"),
            "punches": punch_data.get("punches"),
            "work_hours": punch_data.get("work_hours"),
        })
    writer({"type": "attendance_explanation", "data": card_data})
    return _finish(message, extra_data={**card_data, "next_action": next_action})
