"""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 calendar
import difflib
import logging
from datetime import date, datetime, timedelta
from typing import Optional

from langgraph.types import StreamWriter

import services.erp_client as erp_client
from services.ai_service import (
    LLM_TASK_MAX_TOKENS,
    _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,
)
# Shared deterministic date-phrase resolver — replaces this file's own
# hand-rolled copy of punch_details.py's resolver (explicit dates,
# ordinal-weekday-of-month, week-qualified weekday, last-to-last-month,
# etc.), plus adds a NoSuchOrdinalWeekday case this file didn't previously
# distinguish from "nothing matched at all" — see attendance_explain_node's
# own handling of it below. Also already covers everything
# _resolve_explicit_date_deterministic (imported above, for the LLM-prompt
# extraction path only) handles, so the deterministic layer below no
# longer needs that import for itself.
import services.date_query_resolver as date_query_resolver
import services.last_resolved_date_state as last_resolved_date_state
# 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
from services.regularisation_display import shift_hhmm, time_24h

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"{time_24h(shift['start_time'])}–{time_24h(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=LLM_TASK_MAX_TOKENS, 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


# "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


class AmbiguousDateRange:
    """The query named a date RANGE ("last week", "this month", "from 1 Aug
    to 5 Aug") rather than one specific day. attendance_explain answers for
    exactly ONE day at a time (why THAT day was marked a given status), so
    picking one day out of the range — or defaulting to today, which isn't
    even necessarily inside the range — would silently answer a question
    the employee never asked. Distinguished from a plain unresolved date so
    attendance_explain_node can ask which specific date they mean instead
    of guessing. Same rationale as date_query_resolver.NoSuchOrdinalWeekday
    (see its own docstring) — a different unresolvable shape, same fix."""

    def __init__(self, start_date: date, end_date: date):
        self.start_date = start_date
        self.end_date = end_date


class AmbiguousMultipleDates:
    """The query named several DISCONTIGUOUS specific dates ("the last 2
    Tuesdays") rather than one day or a continuous range. Same rationale
    as AmbiguousDateRange above — attendance_explain answers for exactly
    ONE day, so surfaced here to ask which ONE they mean instead of
    silently picking one or defaulting to today."""

    def __init__(self, dates: list[date]):
        self.dates = dates


class NoDateMentioned:
    """The query never named a date at all ("what was the reason for my
    absence?", "why was I marked absent?"). attendance.py's own extractor
    intentionally defaults a genuinely date-less query to TODAY for
    attendance_node's "show my attendance"/"check my attendance" style
    queries (see its own comment on etype == "unknown") — a reasonable
    default there, since asking generically about "my attendance" with no
    date plausibly means "right now". attendance_explain instead answers
    WHY a status was assigned for a SPECIFIC day; silently assuming "today"
    for a question that named no day at all would answer a question the
    employee never asked, same rationale as AmbiguousDateRange above.
    Surfaced here so attendance_explain_node can ask which date they mean
    instead of guessing."""
    pass


# A row of the attendance table the range answer shows: "| 27 Oct 2026 |
# Tuesday | Not Recorded |". Read from the answer TEXT, not the card JSON
# history_text appends: that JSON is capped and a month's rows lose their
# last days - the ones a "why" is usually about.
_CARD_ROW_RE = re.compile(
    r"^\|\s*(\d{1,2}\s+[A-Za-z]{3}\s+\d{4})\s*\|\s*[A-Za-z]+\s*\|\s*([^|]+?)\s*\|\s*$", re.MULTILINE)

# Statuses nobody asks "why" about when they ask about "it".
_ROUTINE_STATUSES = {"present", "off", "weekly off", "holiday", "upcoming", "on leave", "leave"}

# "How do I fix it?", "can I correct this", "what should I do about it".
FIX_IT_RE = re.compile(
    r"\b(?:fix|correct|rectify|resolve|sort\s+out|update|regulari[sz]e)\s+(?:it|this|that|them|these|those)\b"
    r"|\bget\s+(?:it|this|that)\s+(?:fixed|corrected|sorted|updated)\b"
    r"|\bwhat\s+(?:can|should|do)\s+i\s+do\b",
    re.IGNORECASE)


def days_on_the_last_attendance_card(context: list) -> list[tuple[str, str]]:
    """(iso date, status) for every row of the most recent attendance table in
    the conversation, within the last three answers - a "Sure - which date?"
    reply may sit between the table and the question."""
    answers = [m.get("content") or "" for m in reversed(context or []) if m.get("role") == "assistant"]
    for text in answers[:3]:
        rows = _CARD_ROW_RE.findall(text)
        if rows:
            out = []
            for shown, status in rows:
                try:
                    out.append((datetime.strptime(" ".join(shown.split()), "%d %b %Y").date().isoformat(),
                                status.strip()))
                except ValueError:
                    continue
            return out
        one_day = _single_day_on_the_answer(text)
        if one_day:
            return [one_day]
    return []


_ONE_DAY_DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b|\b(\d{1,2}\s+[A-Za-z]{3}\s+\d{4})\b")
_ONE_DAY_NOT_RECORDED_RE = re.compile(
    r"not\s+recorded|no\s+attendance\s+was\s+recorded|couldn'?t\s+find\s+an?\s+attendance\s+record",
    re.IGNORECASE)
_ONE_DAY_STATUS_RE = re.compile(r"(?:marked|status(?:\s+is)?|shows?)\s*:?\s*\*\*([^*]{2,30})\*\*", re.IGNORECASE)


def _single_day_on_the_answer(text: str):
    """(iso date, status) of a one-day attendance answer ("No attendance was
    recorded for you on Wednesday, 2026-10-28", "You were marked **Present** on
    27 Oct 2026"). 10k eval (28 Oct): "How do I fix it?" under one went to the
    policy documents ("I do not have this information") - only a table was read."""
    if "attendance" not in text.lower() and "marked" not in text.lower():
        return None
    if "upcoming date" in text.lower():
        return None
    m = _ONE_DAY_DATE_RE.search(text)
    if not m:
        return None
    try:
        iso = (m.group(1) or datetime.strptime(" ".join(m.group(2).split()), "%d %b %Y").date().isoformat())
    except ValueError:
        return None
    if _ONE_DAY_NOT_RECORDED_RE.search(text):
        return iso, "Not Recorded"
    s = _ONE_DAY_STATUS_RE.search(text)
    return (iso, s.group(1).strip()) if s else None


def day_asked_about_on_the_card(query: str, context: list) -> list[str]:
    """The day(s) of the last attendance table a dateless question means.

    UAT, 27 Oct: under a week's table with one "Not Recorded" day, "Why is it
    showing Not Recorded?" was asked "which date would you like to know
    about?", and "How do I fix it?" then went to the policy documents ("I do
    not have this information"). The status the question names picks the day;
    "it"/"this" picks the one day that is not routine (Present, Off...)."""
    rows = days_on_the_last_attendance_card(context)
    if not rows:
        return []
    q = (query or "").lower()
    named = [iso for iso, status in rows if status.lower() in q]
    if named:
        return named
    return [iso for iso, status in rows if status.lower() not in _ROUTINE_STATUSES]


async def _resolve_attendance_date(query: str, context: list):
    """Resolves which calendar day the user means. Deterministic weekday/
    today/yesterday/ordinal-weekday-of-month/explicit-date resolution
    first (via the shared services/date_query_resolver.py module); only
    falls back to an LLM call for phrasings that genuinely need NLU.
    Defaults to today when even that can't resolve it — the actual status
    always comes from erp-api regardless.

    Returns (date_iso_string, usage_events) in the normal case, or
    (date_query_resolver.NoSuchOrdinalWeekday, []) when the query named a
    real month/year but asked for an nth-occurrence weekday that month
    doesn't have (e.g. a 5th Wednesday) — attendance_explain_node checks
    for that case and answers it directly rather than defaulting to today
    with no indication the actual question was never resolved.

    _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)."""
    today = _today()

    relative_day_offset = _resolve_relative_day_offset(query.lower())
    if relative_day_offset is not None:
        return (today + timedelta(days=relative_day_offset)).isoformat(), []

    resolved = date_query_resolver.resolve(query, today)
    if isinstance(resolved, (date_query_resolver.NoSuchOrdinalWeekday, date_query_resolver.InvalidExplicitDate)):
        return resolved, []
    if resolved and resolved.get("type") == "single":
        return resolved["date"].isoformat(), []
    if resolved and resolved.get("type") == "range":
        return AmbiguousDateRange(resolved["start_date"], resolved["end_date"]), []
    if resolved and resolved.get("type") == "multiple":
        return AmbiguousMultipleDates(resolved["dates"]), []

    usage_events: list = []
    try:
        prompt = _build_attendance_date_extraction_prompt(query, today)
        raw = await _call_llm(prompt, max_tokens=LLM_TASK_MAX_TOKENS, 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})

        if isinstance(parsed, dict) and parsed.get("type") == "unknown":
            # The LLM explicitly found no date reference in the query at
            # all — don't let _resolve_date_expression silently fold this
            # into today (see NoDateMentioned's own docstring for why that
            # default, correct for attendance.py's own callers, is wrong
            # here).
            return NoDateMentioned(), usage_events

        resolved_llm = (
            _resolve_date_expression(parsed, today, date_query_resolver.detect_week_start_override(query) or 0)
            if isinstance(parsed, dict) else None
        )
        if resolved_llm and resolved_llm.get("type") == "range":
            return AmbiguousDateRange(resolved_llm["start_date"], resolved_llm["end_date"]), usage_events
        date = (
            resolved_llm["date"].isoformat()
            if resolved_llm and resolved_llm.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)

    # The query named no date at all ("what was the reason for my
    # absence?") — before asking, check whether a specific date was just
    # established earlier in this conversation (e.g. a bare date query
    # answered as a calendar fact one turn ago, then "yes, explain that"
    # with no date of its own — confirmed live/reported for the sibling
    # punch_details flow; same fix here). Falls back to asking if nothing
    # was recently resolved, same as before.
    if isinstance(date, NoDateMentioned):
        carried_over = last_resolved_date_state.consume_last_resolved_date(company_id, conversation_id)
        on_card = day_asked_about_on_the_card(query, state.get("context", []))
        if len(on_card) == 1:
            date = on_card[0]
        elif carried_over and (not on_card or carried_over in on_card):
            date = carried_over
        elif on_card:
            dates_str = ", ".join(datetime.strptime(d, "%Y-%m-%d").strftime("%d %b %Y") for d in on_card)
            return _finish(f"Which of these days would you like to know about: {dates_str}?")
        else:
            return _finish("Sure — which date would you like to know about?")

    # The query named a real month/year but asked for an nth-occurrence
    # weekday that month doesn't have (e.g. "5th Wednesday" when it only
    # has 4) — answer that directly rather than defaulting to today with
    # no indication the actual question was never resolved.
    if isinstance(date, date_query_resolver.NoSuchOrdinalWeekday):
        r = date
        # NOTE: can't build this via the `date` class here — the local
        # variable `date` above (the resolved-date STRING/sentinel) shadows
        # the module-level `datetime.date` import for the rest of this
        # function's scope, so calendar.month_name is used instead of
        # date(r.year, r.month, 1).strftime(...).
        month_label = f"{calendar.month_name[r.month]} {r.year}"
        weekday_label = r.weekday_name.capitalize()
        actual_count = date_query_resolver.count_weekday_occurrences(
            r.year, r.month, date_query_resolver.WEEKDAYS[r.weekday_name],
        )
        message = (
            f"{month_label} doesn't have a {r.ordinal_word.capitalize()} {weekday_label} — "
            f"that month only has {actual_count} {weekday_label}s."
        )
        return _finish(message)

    # The query contains an explicit date ATTEMPT that isn't a real
    # calendar date ("10/45/2026", "31/02/2026", "30 feb") — say so
    # directly rather than defaulting to today with no indication the
    # entered date was invalid.
    if isinstance(date, date_query_resolver.InvalidExplicitDate):
        return _finish(
            f"'{date.matched_text}' isn't a valid date — please check the "
            f"day and month (day first, e.g. DD/MM/YYYY) and try again."
        )

    # The query named a RANGE ("last week", "this month") rather than one
    # specific day. This node explains a single day's status, so ask which
    # date within that range they mean instead of silently picking one (or
    # worse, defaulting to today — see AmbiguousDateRange's own docstring).
    if isinstance(date, AmbiguousDateRange):
        start_label = date.start_date.strftime("%d %b %Y")
        end_label = date.end_date.strftime("%d %b %Y")
        message = (
            f"I can only provide these details for one particular day at a "
            f"time — which date between {start_label} and {end_label} "
            f"would you like to know about?"
        )
        return _finish(message)

    # The query named several DISCONTIGUOUS specific dates ("the last 2
    # Tuesdays") rather than one day. Ask which particular one they mean
    # instead of silently picking one or defaulting to today.
    if isinstance(date, AmbiguousMultipleDates):
        dates_str = ", ".join(d.strftime("%d %b %Y") for d in date.dates)
        message = (
            f"I can only provide these details for one particular day at a "
            f"time — which of these dates would you like to know about: "
            f"{dates_str}?"
        )
        return _finish(message)

    # A concrete date was resolved this turn (explicitly, via carry-over
    # above, or otherwise) — refresh the cross-turn memory so a LATER
    # dateless follow-up can still recover it.
    last_resolved_date_state.set_last_resolved_date(company_id, conversation_id, date)

    logger.info("[AttendanceExplain] query=%r -> resolved date=%s", query, date)

    # This route explains PAST and TODAY only. An attendance record cannot
    # exist for a day that has not happened, so "why was I marked X
    # tomorrow" is incoherent — erp-api would answer "Upcoming" with an
    # empty record, which then read as a generic "unavailable, try again"
    # error below. Refuse it up front (and skip the pointless erp call),
    # same as the manager attendance-explanation route.
    from datetime import date as _date
    try:
        _resolved = _date.fromisoformat(date)
    except (TypeError, ValueError):
        _resolved = None
    if _resolved is not None and _resolved > _today():
        weekday = _resolved.strftime("%A")
        logger.info("[AttendanceExplain] resolved date %s is in the future - refusing", date)
        return _finish(
            f"{weekday}, {date} hasn't happened yet, so there's no attendance recorded for it. "
            f"Ask me about a day that has already passed, or today.",
            extra_data={"date": date, "is_future": True},
        )

    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.")

    body_data = result["body"].get("data")
    records = body_data.get("records") if isinstance(body_data, dict) else None
    record = next((r for r in (records or []) if r.get("date") == date), None)

    # AC7's spirit — never invent a status erp-api didn't actually return.
    # Three distinct "no status" cases, not one catch-all:
    if not record or not record.get("status"):
        weekday = _resolved.strftime("%A") if _resolved is not None else None
        when = f"{weekday}, {date}" if weekday else date

        if records is None:
            # data/records key missing entirely — the call didn't really
            # answer. This is the only genuine "try again later" case.
            logger.warning("[AttendanceExplain] unusable body for date=%s: data=%r", date, body_data)
            return _finish("Attendance explanation details are currently unavailable. Please try again later.")

        # erp-api answered; that day simply has nothing on file (a weekend,
        # a not-yet-processed day, a genuine gap). Not an error, and NOT
        # "unavailable" — say so plainly, same wording shape as the manager
        # attendance-explanation route.
        logger.info("[AttendanceExplain] no attendance row for date=%s (erp returned %d record(s))",
                    date, len(records))
        # Why "Not Recorded", and - asked or offered on the card ("Fix it
        # now") - that there is nothing to fix yet (UAT UV-02, 27 Oct: "How do
        # I fix it?" got the policy "I do not have this information").
        today_note = (" Today's attendance may simply not have been processed yet."
                      if _resolved is not None and _resolved == _today() else "")
        message = (
            f"No attendance was recorded for you on {when} - that's why it shows Not Recorded. "
            f"The attendance system has no entry for that day yet.{today_note}\n\n"
            f"It can't be fixed right now: there's no attendance data for that day, so there's "
            f"nothing to regularize yet. Once the day's attendance is recorded, ask me again - "
            f"if it shows Absent or Half Day Absent, I can help you regularize it."
        )
        return _finish(
            message,
            extra_data={"date": date, "day": weekday, "status": None},
        )

    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, offer_only=True)

    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": shift_hhmm(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})
