"""services/punch_details.py

Punch Times & Work Hours (FR-03.2) — surfaces the employee's OWN recorded
check-in/check-out punch times, the shift timing applicable that day, and
the system-computed work hours, for a single specified day.

Strict scope: display only. Never explains classification/status reasoning
(a separate story) and never edits/corrects punch data. Work hours are
NEVER computed here — only ever the value erp-api itself returns.
"""
import os
import re
import logging
from datetime import date, datetime, timedelta
from typing import Optional
from zoneinfo import ZoneInfo

from langgraph.types import StreamWriter

import services.erp_client as erp_client
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
# Used here for its EXPRESSION SCHEMA and its date arithmetic
# (resolve_expression_to_dates), which the LLM's symbolic extraction below
# feeds directly. Its own regex matchers are no longer this file's primary
# path — they run only as the LLM-outage safety net in
# _resolve_requested_date. See the "Date resolution" section for why the
# split lands where it does.
import services.date_query_resolver as date_query_resolver
import services.last_resolved_date_state as last_resolved_date_state
import services.punch_date_suggestion_state as punch_date_suggestion_state
from services.regularisation_display import shift_hhmm, time_24h

logger = logging.getLogger(__name__)


def _today() -> date:
    """Company-local calendar date (QUOTA_TIMEZONE env var, same one
    quota_service.py already uses — default UTC) — NOT the server
    process's own system-clock date, which can differ by hours depending
    on where it happens to be hosted (confirmed live: server-local date
    lagged Asia/Kolkata by half a day, corrupting every "yesterday"/
    "tomorrow" resolution below). Re-reads the env var on every call, same
    as quota_service.py's _get_timezone(), so it stays test-friendly and
    reflects runtime env changes."""
    return datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))).date()


class AmbiguousDateRange:
    """The query named a date RANGE ("last week", "this month", "from 1 Aug
    to 5 Aug") rather than one specific day. punch_details is strictly
    single-day (see the module docstring) — silently narrowing a range to
    one of its ends, or letting it fall through to erp-api's own
    default-to-today, would answer for a day the employee never actually
    asked about. Surfaced here so punch_details_node can ask which
    particular day 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. punch_details is
    strictly single-day, so — same rationale as AmbiguousDateRange above —
    surfaced here so punch_details_node can ask which ONE of them they
    mean instead of silently picking one, narrowing to a range, or falling
    through to erp-api's own default-to-today (which, for a weekday-based
    query, may not even be the right DAY of the week)."""

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


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


def _describe_day(iso_date: str, today: date) -> str:
    """"today" / "yesterday" / "16 Aug 2026" — the day named the way the
    person who just asked about it would name it.

    Only the EMPTY-RESULT sentences use this. Telling someone "no punch
    records for 2026-09-21" when they typed "punch in details" reads as a
    lookup failure against a date they never mentioned; "no punch records
    for today" reads as the answer to the question they actually asked.
    The structured payload still carries the ISO date unchanged — this is
    presentation only."""
    try:
        parsed = datetime.strptime(iso_date, "%Y-%m-%d").date()
    except (ValueError, TypeError):
        return str(iso_date)
    delta = (parsed - today).days
    if delta == 0:
        return "today"
    if delta == -1:
        return "yesterday"
    return parsed.strftime("%d %b %Y")


# ── Date resolution ─────────────────────────────────────────────────────────
#
# The LLM reads EVERY punch query's date phrasing — there is no regex
# pattern-matching layer in front of it any more. What the LLM never does
# is calendar arithmetic: it classifies the phrase into a symbolic
# expression ("the Friday before an anchor one month back") and
# date_query_resolver.resolve_expression_to_dates turns that symbol into a
# real date in pure, unit-tested Python.
#
# That split is deliberate and is the one thing kept from the previous
# design. An LLM asked outright for a date always returns a confident,
# well-formed YYYY-MM-DD; when its weekday/month math is wrong it is
# SILENTLY wrong, with no signal a caller can gate on. Both of this
# repo's date layers already record live incidents of exactly that (see
# date_query_resolver.py's own "confirmed live" comments, and
# leave_action_service.py's "do not rely only on the LLM to calculate
# dates"). Classification the LLM is good at; arithmetic it is not, and
# arithmetic is the part that is cheap and exact to do here.
#
# The symbolic schema below is date_query_resolver's OWN expression schema
# — the same dicts its deterministic matchers emit — so an LLM extraction
# and a deterministic match remain interchangeable inputs to the same
# resolver, exactly as that module's docstring intends. Deliberately NOT
# attendance.py's _resolve_date_expression: that one reimplements the same
# arithmetic over a stale 18-type subset, and would silently drop the 15
# expression shapes (weekday_ago/relative_ago, weekday_retrospective,
# week_qualified_weekday, ordinal_weekday_of_month, last_to_last_*, bare
# year, ...) this file needs.

# Every expression type date_query_resolver.resolve_expression_to_dates
# can actually resolve, plus "unknown". Anything outside this set coming
# back from the LLM is treated as no extraction at all rather than passed
# through — same "never let a malformed value escape" guarantee
# ai_service.extract_structured_date_fields gives for its own enums.
_DATE_EXPRESSION_TYPES = frozenset({
    "today", "yesterday", "tomorrow", "single_offset",
    "explicit_single", "explicit_range", "from_explicit_to_today", "invalid_explicit_date",
    "weekday", "weekday_retrospective", "next_weekday", "week_qualified_weekday",
    "weekday_ago", "last_n_weekdays", "ordinal_weekday_of_month",
    "relative_ago", "relative_days", "upcoming_days", "relative_months",
    "this_week", "last_week", "last_to_last_week", "next_week", "last_week_to_next_week",
    "this_month", "last_month", "last_to_last_month", "next_month_bare", "last_month_to_next_month",
    "explicit_month", "this_year", "last_year", "explicit_year",
    "financial_year", "financial_year_first_day", "financial_year_last_day",
    "unknown",
})
_AGO_UNITS = frozenset({"day", "week", "month", "year"})
_ORDINAL_WORDS = frozenset(set(date_query_resolver.ORDINAL_WEEKDAY_WORDS) | {"last"})
_ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")


def _build_date_expression_prompt(query: str, today: date) -> str:
    return f"""You classify the date REFERENCE in an employee's punch-times question.
You must NOT calculate any date yourself — output only the symbolic reference.
Python does all the calendar arithmetic afterwards.

Today is {today.isoformat()} ({today.strftime('%A')}).
The employee may misspell words ("yestarday", "fryday", "las week") — correct them silently.

Output ONLY this JSON object. No explanation, no markdown, no code fences.

{{
  "type": "<one of the types listed below>",
  "weekday": "monday|tuesday|wednesday|thursday|friday|saturday|sunday" or null,
  "weeks_ago": integer or null,
  "n_days": integer or null,
  "n_months": integer or null,
  "n_units": integer or null,
  "unit": "day|week|month|year" or null,
  "ordinal_word": "first|second|third|fourth|fifth|last" or null,
  "month": integer 1-12 or null,
  "year": integer or null,
  "explicit_date": "YYYY-MM-DD" or null,
  "explicit_start": "YYYY-MM-DD" or null,
  "explicit_end": "YYYY-MM-DD" or null,
  "week_starts_on": "monday|...|sunday" or null
}}

ONE SPECIFIC DAY:
- "today" / "yesterday" / "tomorrow" -> that type, all other fields null.
- "single_offset" -> a day offset no other type covers; n_days signed ("day before yesterday"=-2).
- "explicit_single" -> a stated calendar date; set explicit_date.
- "weekday" -> "last friday" (weeks_ago=1), "last to last friday" (weeks_ago=2),
  "this friday" (weeks_ago=0). Set weekday.
- "weekday_retrospective" -> a BARE weekday with no qualifier at all ("punch time on friday").
  Set weekday. Attendance is retrospective, so this means the most recent one.
- "next_weekday" -> "next friday" (weeks_ago=1), "next to next friday" (weeks_ago=2).
- "week_qualified_weekday" -> the weekday of a named CALENDAR WEEK: "last week friday"
  (weeks_ago=1), "this week friday" (0), "next week friday" (-1). NOT the same as "last friday".
- "weekday_ago" -> a weekday scoped by a backward count: "friday one month ago"
  (weekday=friday, n_units=1, unit=month), "monday 2 weeks back" (n_units=2, unit=week).
- "ordinal_weekday_of_month" -> "second friday of august", "last wednesday of last month".
  Set weekday + ordinal_word, and month/year for the month meant (year null if not stated).

SEVERAL SPECIFIC DAYS:
- "last_n_weekdays" -> "the last 2 tuesdays"; set weekday and n_days=the COUNT.

A RANGE OF DAYS:
- "relative_ago" -> a backward count with NO weekday: "one month ago" (n_units=1, unit=month),
  "3 days ago" (n_units=3, unit=day), "2 weeks back" (n_units=2, unit=week).
- "relative_days" -> "last 7 days"; n_days=7. PAST, including today.
- "upcoming_days" -> "next 3 days"; n_days=3. FUTURE, excluding today.
- "relative_months" -> "last 2 months"; n_months=2.
- "this_week" / "last_week" / "last_to_last_week" / "next_week" / "last_week_to_next_week".
- "this_month" / "last_month" / "last_to_last_month" / "next_month_bare" / "last_month_to_next_month".
- "explicit_month" -> a NAMED month with no day number ("august", "june 2025");
  set month, and year only if stated.
- "explicit_range" -> "from X to Y"; set explicit_start and explicit_end.
- "from_explicit_to_today" -> "from X till today"; set explicit_date.
- "this_year" / "last_year" / "explicit_year" (set year).
- "financial_year" -> "this financial year"/"this fiscal year" (weeks_ago=0),
  "last financial year"/"last fiscal year" (weeks_ago=1). India convention: 1 April - 31 March.

ONE SPECIFIC DAY WITHIN A FINANCIAL YEAR:
- "financial_year_first_day" -> "first day of this/last financial year" -> 1 April.
  weeks_ago=0 for "this", 1 for "last".
- "financial_year_last_day" -> "last day of this/last financial year" -> 31 March.
  weeks_ago=0 for "this", 1 for "last".

OTHER:
- "invalid_explicit_date" -> the query clearly ATTEMPTS a calendar date that does not exist
  ("31/02/2026", "30 feb", "10/45/2026"). Set explicit_date to the text as written.
- "unknown" -> the query names NO date reference at all ("what were my punch times").

CRITICAL — slash/dash numeric dates are DD/MM/YYYY (day first), NEVER MM/DD/YYYY,
even when both numbers are <= 12 and it looks ambiguous:
- "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 ("12-08", "23 aug") uses {today.year}. Never output null just
because the year was omitted.

If the employee states their own week start ("last week starting sunday"), set week_starts_on.
When a phrase does not clearly match exactly one type, use "unknown" rather than guessing.

Employee query: {query}"""


def _coerce_int(value) -> Optional[int]:
    return value if isinstance(value, int) and not isinstance(value, bool) else None


def _coerce_choice(value, allowed: frozenset) -> Optional[str]:
    return value.lower() if isinstance(value, str) and value.lower() in allowed else None


def _coerce_iso(value) -> Optional[str]:
    return value if isinstance(value, str) and _ISO_DATE_RE.match(value) else None


def _normalize_date_expression(parsed) -> Optional[dict]:
    """Validates the LLM's raw JSON into a date_query_resolver expression
    dict, or None if it isn't one. Every field is enum/type-checked rather
    than passed through: a malformed value must degrade to "not
    extracted", never reach the arithmetic as a silently wrong input."""
    if not isinstance(parsed, dict):
        return None
    etype = _coerce_choice(parsed.get("type"), _DATE_EXPRESSION_TYPES)
    if etype is None:
        return None

    expression = date_query_resolver._expr(
        etype,
        weekday=_coerce_choice(parsed.get("weekday"), frozenset(date_query_resolver.WEEKDAYS)),
        weeks_ago=_coerce_int(parsed.get("weeks_ago")),
        n_days=_coerce_int(parsed.get("n_days")),
        n_months=_coerce_int(parsed.get("n_months")),
        n_units=_coerce_int(parsed.get("n_units")),
        unit=_coerce_choice(parsed.get("unit"), _AGO_UNITS),
        month=_coerce_int(parsed.get("month")),
        year=_coerce_int(parsed.get("year")),
        explicit_date=_coerce_iso(parsed.get("explicit_date")),
        explicit_start=_coerce_iso(parsed.get("explicit_start")),
        explicit_end=_coerce_iso(parsed.get("explicit_end")),
    )
    # Two resolver fields are internal (underscore-prefixed) rather than
    # part of the public schema, so they're mapped here from the plainer
    # names the prompt asks for.
    ordinal_word = _coerce_choice(parsed.get("ordinal_word"), _ORDINAL_WORDS)
    if ordinal_word:
        expression["_ordinal_word"] = ordinal_word
    if etype == "invalid_explicit_date":
        raw_text = parsed.get("explicit_date")
        expression["_matched_text"] = raw_text if isinstance(raw_text, str) else ""
    return expression


async def _extract_date_expression_via_llm(query: str, today: date, usage_events: list):
    """Returns (expression, week_start), or (None, 0) when the call itself
    failed or produced nothing usable — the caller distinguishes those two
    cases, since "the LLM said there's no date here" ("unknown") and "the
    LLM was unreachable" must not be treated the same way."""
    try:
        raw = await _call_llm(
            _build_date_expression_prompt(query, today), max_tokens=LLM_TASK_MAX_TOKENS, model=INTENT_MODEL,
        )
    except Exception as e:
        logger.warning(f"[PunchDetails] date expression extraction failed: {e}")
        return None, 0

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

    parsed = _safe_json_parse(_extract_text(raw))
    expression = _normalize_date_expression(parsed)
    week_start = 0
    if isinstance(parsed, dict):
        named = _coerce_choice(parsed.get("week_starts_on"), frozenset(date_query_resolver.WEEKDAYS))
        if named:
            week_start = date_query_resolver.WEEKDAYS[named]
    return expression, week_start


def _expression_to_requested_date(expression: dict, today: date, week_start: int = 0):
    """Maps a date_query_resolver expression onto this node's own return
    contract: an ISO date string for one specific day, None for "let
    erp-api apply its own default", or one of the four "can't answer this
    as a single day" markers punch_details_node reports directly.

    "today" collapses to None on purpose, matching this file's long-
    standing choice to let erp-api apply its own default-to-today rather
    than pinning an explicit date on a query that didn't need one. So does
    "unknown" — a query with no date reference at all is a plain "what
    were my punch times", which has always meant today."""
    etype = expression.get("type")
    if etype in ("today", "unknown"):
        return None

    resolved = date_query_resolver.resolve_expression_to_dates(expression, today, week_start)
    if isinstance(resolved, (date_query_resolver.NoSuchOrdinalWeekday, date_query_resolver.InvalidExplicitDate)):
        return resolved
    if not isinstance(resolved, dict):
        return None
    if resolved.get("type") == "single":
        return resolved["date"].isoformat()
    if resolved.get("type") == "range":
        return AmbiguousDateRange(resolved["start_date"], resolved["end_date"])
    if resolved.get("type") == "multiple":
        return AmbiguousMultipleDates(resolved["dates"])
    return None


_SIMPLE_RELATIVE_DAY_RE = re.compile(r"\b(?:today|yesterday)\b", re.IGNORECASE)
_SHIFTED_DAY_RE = re.compile(r"\d|\b(?:before|after|prior|since|until|till|last|next|ago)\b",
                             re.IGNORECASE)


def _names_one_simple_day(query: str) -> bool:
    """Exactly one "today"/"yesterday" (or "the day before yesterday"), with
    nothing that shifts or adds to it ("2 days before yesterday", "yesterday
    and today", "since yesterday")."""
    text = re.sub(r"\bday\s+before\s+yesterday\b", "yesterday", query or "", flags=re.IGNORECASE)
    if len(_SIMPLE_RELATIVE_DAY_RE.findall(text)) != 1:
        return False
    return not _SHIFTED_DAY_RE.search(text)


async def _resolve_requested_date(query: str, today: date, usage_events: list):
    """The single date-resolution entry point. The LLM classifies every
    query; date_query_resolver's deterministic matchers are consulted ONLY
    when the LLM call itself could not be made or came back unusable.

    That fallback is a safety net for an LLM outage, not a first pass:
    without it an unreachable model would leave requested_date at None,
    and erp-api's own default is TODAY — silently answering an unrelated
    day, the exact failure mode this file guards against everywhere else
    (see NoSuchOrdinalWeekday/InvalidExplicitDate handling in the node)."""
    # "today" / "yesterday" / "day before yesterday" each name exactly one
    # day, so they are read here rather than asked of the model, which read
    # "yesterday" as today in one of many identical runs (QA sheet, a
    # manager's "show my punch details for yesterday" -> 2026-10-07). Only
    # when the resolver finds that one single day; anything else - a range,
    # a second date, an ordinal - still goes to the model.
    if _names_one_simple_day(query):
        simple = date_query_resolver.resolve(query, today)
        if isinstance(simple, dict) and simple.get("type") == "single":
            return simple["date"].isoformat()

    expression, week_start = await _extract_date_expression_via_llm(query, today, usage_events)
    if expression is not None:
        return _expression_to_requested_date(expression, today, week_start)

    logger.warning("[PunchDetails] falling back to deterministic date resolution for: %s", query)
    fallback = date_query_resolver.resolve_query_to_expression(query, today)
    if not fallback:
        return None
    return _expression_to_requested_date(
        fallback, today, date_query_resolver.detect_week_start_override(query) or 0,
    )


def _format_sessions(sessions: list) -> str:
    parts = []
    for i, s in enumerate(sessions, start=1):
        check_in, check_out = s.get("check_in"), s.get("check_out")
        if s.get("complete") and check_in and check_out:
            parts.append(f"Session {i}: {check_in} to {check_out}")
        elif check_in and not check_out:
            parts.append(f"Session {i}: checked in at {check_in} — check-out not recorded")
        elif check_out and not check_in:
            parts.append(f"Session {i}: checked out at {check_out} — check-in not recorded")
    return "; ".join(parts)



# "before 9th sept" / "after 9th sept": the date is an ANCHOR, not the day
# asked for. QA: "pls show me checkin checkout before 9th sept" came back with
# the 9th's own punches. This node answers one day, so it offers the adjacent
# day and asks rather than guessing between "the 8th" and "everything up to
# the 8th". "the day before yesterday" / "the day after 9th" already name one
# day exactly and are left to the resolver.
_RELATIVE_ANCHOR_RE = re.compile(
    r"(?<!\bday )(?<!\bdays )\b(before|after|prior\s+to)\s+(?!yesterday\b|today\b|tomorrow\b|that\b|this\b|it\b)",
    re.IGNORECASE)


def _relative_anchor(query: str):
    """(-1 | +1, the query with the preposition turned into "on"), or None."""
    m = _RELATIVE_ANCHOR_RE.search(query or "")
    if not m:
        return None
    step = 1 if m.group(1).lower() == "after" else -1
    return step, query[:m.start()] + "on " + query[m.end():]


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

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

    today = _today()

    # ── Answer to "Did you mean <date>?" (see _RELATIVE_ANCHOR_RE) ──────────
    # classify_node routes a bare yes/no here while the offer is pending.
    # Single-use either way: consumed here, and cleared by classify_node when
    # the next message is about something else.
    offered = punch_date_suggestion_state.get_state(company_id, conversation_id)
    offered_date = None
    if offered:
        punch_date_suggestion_state.clear_state(company_id, conversation_id)
        if punch_date_suggestion_state.is_yes(query):
            offered_date = offered.get("date")
        elif punch_date_suggestion_state.is_no(query):
            return _finish("No problem — which date would you like the punch details for?")

    relative = None if offered_date else _relative_anchor(query)
    if offered_date:
        requested_date = offered_date
    else:
        requested_date = await _resolve_requested_date(
            relative[1] if relative else query, today, usage_events)

    if relative and isinstance(requested_date, str):
        anchor = date.fromisoformat(requested_date)
        suggested = anchor + timedelta(days=relative[0])
        side = "after" if relative[0] > 0 else "before"
        if suggested > today:
            return _finish(
                f"{_format_date_for_display(suggested.isoformat())}, the day {side} "
                f"{_format_date_for_display(anchor.isoformat())}, hasn't happened yet, so there's "
                f"no punch data for it — I can only show a past or current day."
            )
        punch_date_suggestion_state.set_state(company_id, conversation_id, suggested.isoformat())
        # classify_node remembered the anchor (the 9th) as "the date just
        # discussed". It is the one day NOT asked for: a later dateless
        # punch question must not quietly answer it.
        last_resolved_date_state.clear_last_resolved_date(company_id, conversation_id)
        return _finish(
            f"I can show punch details for one day at a time. Did you mean "
            f"{_format_date_for_display(suggested.isoformat())}, the day {side} "
            f"{_format_date_for_display(anchor.isoformat())}? Reply yes to see it, "
            f"or tell me another date."
        )

    # 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 falling through to the
    # erp_client path below, which would otherwise silently call it with
    # date=None (erp-api's own default is TODAY) and answer an unrelated
    # day with no indication the actual question was never resolved.
    if isinstance(requested_date, date_query_resolver.NoSuchOrdinalWeekday):
        r = requested_date
        month_label = date(r.year, r.month, 1).strftime("%B %Y")
        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 falling through to the erp_client path below,
    # which would otherwise silently call it with date=None (erp-api's own
    # default is TODAY) and answer an unrelated day with no indication the
    # entered date was invalid.
    if isinstance(requested_date, date_query_resolver.InvalidExplicitDate):
        return _finish(
            f"'{requested_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."
        )

    # The query named a RANGE ("last week", "this month") rather than one
    # specific day. This node is strictly single-day, so ask which day
    # within that range they mean instead of silently narrowing it (or
    # worse, falling through to erp-api's own default-to-today).
    if isinstance(requested_date, AmbiguousDateRange):
        start_label = requested_date.start_date.strftime("%d %b %Y")
        end_label = requested_date.end_date.strftime("%d %b %Y")
        message = (
            f"I can only provide punch details for one particular day at a "
            f"time — which date between {start_label} and {end_label} "
            f"would you like?"
        )
        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 answering for today.
    if isinstance(requested_date, AmbiguousMultipleDates):
        dates_str = ", ".join(_format_date_for_display(d.isoformat()) for d in requested_date.dates)
        message = (
            f"I can only provide punch details for one particular day at a "
            f"time — which of these dates would you like: {dates_str}?"
        )
        return _finish(message)

    if requested_date:
        # A concrete date WAS resolved this turn — refresh the cross-turn
        # memory so a LATER dateless follow-up ("now show me attendance
        # too") can still recover it.
        last_resolved_date_state.set_last_resolved_date(company_id, conversation_id, requested_date)
    else:
        # This message names no date of its own — before falling through
        # to erp-api's own default-to-today, check whether a specific date
        # was just established earlier in this conversation (e.g. "4th
        # Wednesday of August 2026" answered as a calendar fact, then "yes,
        # give me punch details" with no date of its own — confirmed live/
        # reported: this silently defaulted to today instead of the date
        # just discussed). Single-use: consuming it clears it, so it only
        # ever applies to the one immediate follow-up, not indefinitely.
        carried_over = last_resolved_date_state.consume_last_resolved_date(company_id, conversation_id)
        if carried_over:
            requested_date = carried_over

    # Punches can only exist for a day that has already happened — a
    # future date ("upcoming Monday", an explicit date ahead of today)
    # has no punch data yet, so answering it at all (even "no punch
    # records found") would misleadingly read as if the day were already
    # over and the employee simply didn't punch. Checked deterministically
    # here rather than left to erp-api, which has no reason to know or
    # say the date hasn't happened yet.
    if requested_date and requested_date > today.isoformat():
        return _finish(
            f"{_format_date_for_display(requested_date)} hasn't happened yet, so "
            f"there's no punch data for it — I can only show punch details for a "
            f"past or current day."
        )

    writer({"type": "fetching_punch_details", "message": "Checking your punch details..."})
    try:
        result = await erp_client.get_punch_details(
            bearer_token, date=requested_date, company_id=company_id, conversation_id=conversation_id,
        )
    except erp_client.ErpApiTimeout:
        return _finish("I couldn't reach the attendance 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 as e:
        # erp-api's own words whenever it sent any — "Attendance is locked for
        # this date", "No punch data available for this employee". Reporting a
        # business answer as an outage is wrong twice over: it blames the
        # infrastructure, and it invites a retry that can never succeed. This
        # is the exact reason a plain "punch in details" came back as "I'm
        # unable to reach the attendance system right now" over and over.
        # The infrastructure sentence survives only for the case it describes:
        # erp-api genuinely did not reply (connection error, proxy error page).
        return _finish(erp_client.unavailable_message(
            e, "I'm unable to reach the attendance system right now — please try again shortly."))

    body = result["body"]
    if not body.get("success", True):
        asked_for = _describe_day(requested_date or today.isoformat(), today)
        return _finish(
            body.get("message")
            or f"I couldn't pull up your punch details for {asked_for} just now — "
               f"please try again, or give me another date to check."
        )

    data = body.get("data", {}) or {}
    display_date = data.get("requested_date") or requested_date or today.isoformat()
    # HH:MM - no seconds are sent or shown ("09:00", not "09:00:00").
    shift = shift_hhmm(data.get("shift") or {})
    # erp-api's real /attendance/punch-details response returns this list
    # under "punches" (confirmed live) — "sessions" kept as a fallback in
    # case an older/other deployment still uses that name.
    sessions = data.get("punches") or data.get("sessions") or []
    work_hours = data.get("work_hours") or {}

    shift_desc = ""
    if shift.get("name"):
        shift_desc = (f" Shift: {shift['name']} ({time_24h(shift.get('start_time')) or '?'}–"
                      f"{time_24h(shift.get('end_time')) or '?'}).")

    # AC7 — non-working day / no punch records at all for the day. Only
    # "day_status" is used as the reason — confirmed live against a real
    # ordinary no-punch day (2026-08-18: day_status null, punch_status
    # "no_records") and a real regularized-but-punchless day (2026-08-14:
    # day_status still null, but attendance.attendance = "P", a raw
    # single-letter status code). Deliberately NOT falling back to
    # attendance.attendance — it's an internal code (P/A/WO/...), not a
    # human-readable day type, and would render as nonsense like "as it was
    # a P." work_hours.reason is also excluded — it duplicates the
    # top-level "no records" message rather than naming a day type.
    #
    # The sentence names the day the way the ASKER would ("today", not
    # "2026-09-21") and, when there is no day_status to explain the gap,
    # offers the one move that can actually change the answer — naming a
    # different date. "No punch records found for 2026-09-21." told someone
    # who typed "punch in details" neither what was looked up nor what to do
    # next. The word "punch" stays in every branch on purpose: it is one of
    # classify_node's _HR_CONTEXT_SIGNALS, and a no-records day emits no
    # "Shift:" line, so this sentence is the only thing keeping a bare-date
    # follow-up ("18 aug") routed back to punch details instead of being
    # read as a brand-new off-topic question.
    if not sessions:
        reason = data.get("day_status")
        day_phrase = _describe_day(display_date, today)
        if reason:
            message = (f"I couldn't find any punch records for {day_phrase} — "
                       f"it was a {reason}, so none were expected.{shift_desc}")
        else:
            message = (f"I couldn't find any punch records for {day_phrase} — "
                       f"no check-in or check-out was logged that day.{shift_desc} "
                       f"If you meant a different day, just tell me the date and "
                       f"I'll check that one.")
        return _finish(
            message,
            extra_data={"requested_date": display_date, "shift": shift},
        )

    sessions_desc = _format_sessions(sessions)

    # AC3 — hours shown ONLY when erp-api marks them available. Never
    # computed locally — this story's core trust boundary.
    if work_hours.get("available"):
        msg = (f"Punch details for {display_date} — {sessions_desc}.{shift_desc} "
               f"Total work hours: {work_hours.get('value')}.")
        return _finish(msg, extra_data={
            "requested_date": display_date, "shift": shift, "sessions": sessions, "work_hours": work_hours,
        })

    # AC4 — incomplete: show what exists, explicitly no hours value shown.
    msg = (f"Punch details for {display_date} — {sessions_desc}.{shift_desc} "
           f"Work hours aren't available since a punch is missing.")
    return _finish(msg, extra_data={"requested_date": display_date, "shift": shift, "sessions": sessions})
