import base64
import calendar
import json
import os
import re
import difflib
from datetime import date, datetime, timedelta
from typing import Optional
from zoneinfo import ZoneInfo
from schema.agent import HRState
from services import attendance_service  # the only place that knows about URLs/mock vs live
from services import slot_store
from services.name_parsing import split_employee_names
from langgraph.types import StreamWriter
import logging
from langgraph.graph import END
import services.leave_slot_service as leave_slot_service
import services.permission_service as permission_service

from services.ai_service import (
    LLM_TASK_MAX_TOKENS,
    _call_llm,
    _extract_text,
    _safe_json_parse,
    _normalize_usage,

    INTENT_MODEL,

)
# Shared deterministic date-phrase resolver — see attendance_node's Step 1
# for how this is wired in as a pre-LLM check. Its {"type": "single"/
# "range", ...} output shape was deliberately designed to match
# _resolve_date_expression's own return shape below, so a deterministic hit
# can be used as `query_params` directly with no translation step.
import services.date_query_resolver as date_query_resolver
import services.last_resolved_date_state as last_resolved_date_state
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 today/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()


ATTENDANCE_MAX_INLINE_RANGE_DAYS = 31

# Roles allowed to view attendance of someone other than themselves.
# NOTE: adjust to match your actual JWT role values. Values are compared
# as strings after normalization (see _is_authorized_for_target), so this
# set covers both numeric role_id-style values and role-name strings —
# add whatever your token actually issues.
PRIVILEGED_ROLES = {"1", "2", "3", "4"}

# Matches "regularize"/"regularise"/"regularization"/"regularisation" (and
# casual misspellings like "regularise it") — used to detect that the SAME
# message which asked about attendance is also asking to act on it.
_REGULARIZE_PATTERN = re.compile(r"regulari[sz]", re.IGNORECASE)

HALF_DAY_ABSENT_STATUS = ["Half Day Absent"]

def _is_regularizable(status: Optional[str]) -> bool:
    return status in HALF_DAY_ABSENT_STATUS

def _wants_regularization(query: str) -> bool:
    return bool(_REGULARIZE_PATTERN.search(query))


def _seed_pending_regularization(company_id, conversation_id: str, *, date_iso=None,
                                  employee_name=None, candidate_dates=None,
                                  offer_only: bool = False) -> None:
    # offer_only: seeded for the "Would you like to check the regularization
    # process?" / "Fix it now" OFFER under an attendance answer, which the
    # user has not taken up. classify_node reads only an acceptance as part of
    # the flow; anything else is classified normally. Pilot run (28 Oct): with
    # the entry waiting on a reason, "nice", "machine learning" and "levae
    # balance" after a Half Day Absent table were each taken as the reason.
    # "_prevalidated": True — this date's status was already confirmed
    # regularizable (Absent/Half Day Absent) by the caller's own
    # _is_regularizable/absent_isos check before this ever ran, so
    # regularisation_node.py's own direct-entry eligibility gate (attendance
    # status + regularization window) skips re-checking it. See that gate's
    # docstring in regularisation_node.py for the gap it actually closes —
    # a regularization request that never went through attendance_node/
    # attendance_explain_node at all.
    entries = [{"date": date_iso, "_prevalidated": True}] if date_iso else []
    seed = {"entries": entries}
    if offer_only:
        seed["_offer_only"] = True
    if employee_name:
        seed["employee_name"] = employee_name
    if candidate_dates:
        seed["candidate_dates"] = candidate_dates
    slot_store.set_slots("regularization", company_id, conversation_id, seed)
    leave_slot_service.clear_slots(company_id, conversation_id)  # NEW


def _handoff_to_regularisation(writer: StreamWriter, attendance_msg: str, usage_events: list,
                                company_id, conversation_id: str, *, date_iso: str,
                                employee_name: Optional[str] = None) -> dict:
    """Same-turn handoff: the user's query already named/implied a specific
    date AND asked to regularize it in the same message (e.g. "was I
    absent yesterday, regularize it"). Seeds the date directly — skipping
    the "which date" question entirely — then hands control to
    regularisation_node via the graph's conditional edge.

    Writes the multi-entry shape ({"entries": [...]}) that
    regularisation_node / slot_flow.py's entry_fields mode expects.

    Deliberately does NOT call a "done" writer event or return via
    _finish(): this node isn't finishing the turn, regularisation_node is.
    The attendance answer is streamed as a plain "chunk" so the user still
    sees it before regularisation_node's own message follows."""
    # "_prevalidated": True — same-turn handoff means this date's status was
    # JUST confirmed regularizable by the caller (see
    # _seed_pending_regularization's own comment on this flag).
    seed = {"entries": [{"date": date_iso, "_prevalidated": True}]}
    if employee_name:
        seed["employee_name"] = employee_name
    slot_store.set_slots("regularization", company_id, conversation_id, seed)
    writer({"type": "chunk", "content": attendance_msg})
    return {"response_text": attendance_msg, "usage_events": usage_events, "route_to": "regularisation_node"}


def _route_after_attendance(state: HRState) -> str:
    """Same-turn handoff: attendance_node sets route_to="regularisation_node"
    when the user's query already asked to regularize a now-known date in
    the same message (see attendance.py's _handoff_to_regularisation).
    Otherwise the turn ends normally after the attendance answer — any
    next-turn continuation is picked up by classify_node's Fast-path 0.6
    instead."""
    if state.get("route_to") == "regularisation_node":
        return "regularisation_node"
    return END


async def _fetch_multi_employee_attendance(
    target_employees: list[str],
    query_params: dict,
    today: date,
    bearer_token: str,
    company_id,
    conversation_id: str,
    writer: StreamWriter,
    finish,
) -> dict:
    """Fans a single query naming several employees ("attendance for geo3,
    geo5 and geo9") out into one erp-api lookup per name, then combines the
    per-employee results into one answer. No same-turn regularization
    handoff on this path — regularizing several other people's attendance
    isn't a single-message action the way regularizing your own is, so
    wants_reg is simply not consulted here."""
    writer({
        "type": "fetching_attendance",
        "message": f"Checking attendance for {len(target_employees)} employees...",
    })

    is_range = query_params["type"] == "range"
    is_summary = False
    start_date = end_date = None
    if is_range:
        start_date, end_date = query_params["start_date"], query_params["end_date"]
        is_summary = (end_date - start_date).days + 1 > ATTENDANCE_MAX_INLINE_RANGE_DAYS

    sections: list[str] = []
    per_employee: dict[str, dict] = {}
    not_found: list[str] = []

    for name in target_employees:
        try:
            if not is_range:
                result = await attendance_service.get_attendance_single(
                    bearer_token, target_date=query_params["date"],
                    company_id=company_id, conversation_id=conversation_id,
                    employee_name=name,
                )
            elif is_summary:
                result = await attendance_service.get_attendance_summary(
                    bearer_token, start_date=start_date, end_date=end_date,
                    company_id=company_id, conversation_id=conversation_id,
                    employee_name=name,
                )
            else:
                result = await attendance_service.get_attendance_range(
                    bearer_token, start_date=start_date, end_date=end_date,
                    company_id=company_id, conversation_id=conversation_id,
                    employee_name=name,
                )
        except attendance_service.ErpApiTimeout:
            return finish("I couldn't reach the HR system in time — please try again in a moment.")
        except attendance_service.ErpApiUnauthorized:
            return finish("Sorry, your session has expired — please log in again to continue.")
        except attendance_service.ErpApiUnavailable:
            return finish("I'm unable to reach the HR system right now — please try again shortly.")
        except Exception:
            logger.exception("[Graph] Unexpected error fetching multi-employee attendance for %r", name)
            return finish("I couldn't fetch attendance right now — please try again in a moment.")

        data = result.get("data", {}) or {}

        if data.get("search_matched") is False:
            not_found.append(name)
            sections.append(f"**{name}**: No employee found with the name '{name}'.")
            continue

        if not result.get("success", True):
            sections.append(f"**{name}**: {result.get('message') or 'Could not fetch attendance.'}")
            continue

        if not is_range:
            msg, rows = _format_single_date(query_params["date"], data.get("status"), today)
            sections.append(f"**{name}**: {msg}")
            per_employee[name] = {"rows": rows}
        elif is_summary:
            sections.append(f"**{name}**:\n{_format_long_range_summary(start_date, end_date, data)}")
            per_employee[name] = {
                k: v for k, v in data.items()
                if k not in ("search_matched", "action_required", "employees")
            }
        else:
            msg, rows, _absent_isos = _format_date_range(start_date, end_date, data.get("records", []), today)
            sections.append(f"**{name}**:\n{msg}")
            per_employee[name] = {"rows": rows}

    combined_message = "\n\n".join(sections)

    writer({
        "type": "attendance_multi_employee",
        "data": {"employees": per_employee, "not_found": not_found},
    })

    return finish(
        combined_message,
        intent="attendance_multi_employee",
        extra_data={"employees": per_employee, "not_found": not_found, "node_type": "multi_status"},
    )


async def attendance_node(state: HRState, 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,
        intent: str = "attendance",
        extra_data: Optional[dict] = None,
    ) -> dict:
        data = {"answer": message}

        if extra_data:
            data.update(extra_data)

        try:
            writer({
                "type": "done",
                "intent": intent,
                "is_hr": True,
                "data": data,
                "message": message,
                "usage_events": usage_events,
            })
        except Exception:
            # Never expose writer/SSE errors to frontend
            logger.exception(
                "[Graph] Failed to write attendance done event"
            )

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

    try:
        # ============================================================
        # Step 1: Extract date params + target employee
        # ============================================================

        today = _today()

        # Deterministic pre-resolution — try the shared date_query_resolver
        # module BEFORE ever calling the LLM. Gated on
        # _looks_like_named_employee_query so this never risks silently
        # dropping a named-employee query's name: the LLM call is the ONLY
        # place employee_name gets extracted, so any query that looks like
        # it might name someone still goes straight to the LLM path
        # unchanged, exactly as before.
        #
        # Restores a capability this node had LOST entirely on this branch:
        # attendance_node used to have its own deterministic layer
        # (referenced in surrounding comments as
        # "_resolve_attendance_type_deterministic"), but that dispatcher no
        # longer exists anywhere in this file — only its now-orphaned
        # helper functions/regexes remained, and Step 1 called the LLM
        # unconditionally for every single query. That meant EVERY query,
        # including trivially unambiguous ones ("yesterday", "last
        # Friday"), depended on the LLM correctly following its own
        # extraction schema every time — exactly the class of risk this
        # file's own surrounding comments describe fixing elsewhere
        # ("short/typo'd/Hinglish queries... where the LLM classification
        # step sometimes picked the wrong symbolic type").
        deterministic_query_params = None
        if not _looks_like_named_employee_query(query):
            deterministic = date_query_resolver.resolve(query, today)

            if isinstance(deterministic, date_query_resolver.NoSuchOrdinalWeekday):
                r = deterministic
                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],
                )
                return _finish(
                    f"{month_label} doesn't have a {r.ordinal_word.capitalize()} {weekday_label} — "
                    f"that month only has {actual_count} {weekday_label}s."
                )

            # 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 LLM-fallback path
            # below, which has no reason to recognize the same invalid
            # numbers as a date at all and would just answer as if none
            # were given, with no indication the entered date was invalid.
            if isinstance(deterministic, date_query_resolver.InvalidExplicitDate):
                return _finish(
                    f"'{deterministic.matched_text}' isn't a valid date — "
                    f"please check the day and month (day first, e.g. "
                    f"DD/MM/YYYY) and try again."
                )

            if deterministic and deterministic.get("type") in ("single", "range"):
                deterministic_query_params = deterministic

        # if deterministic_query_params is not None:
        parsed = {"employee_name": None}
        # else:
        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,
                })

        except Exception:
            logger.exception(
                "[Graph] Attendance date extraction failed"
            )
            parsed = {}

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

        # ============================================================
        # Step 1b: Ownership guardrail
        # ============================================================

        target_employees = _split_employee_names(parsed.get("employee_name"))
        target_employee = target_employees[0] if len(target_employees) == 1 else None

        claims = _decode_jwt_claims(bearer_token)

        current_user_name = (
            claims.get("name")
            or claims.get("username")
            or claims.get("preferred_username")
        )

        current_user_role = (
            claims.get("role")
            or claims.get("roles")
            or claims.get("role_id")
        )

        # Multiple distinct employees named at once ("attendance for geo3,
        # geo5 and geo9") is inherently a cross-employee request — there's
        # no "matches my own name" escape hatch for a list, so it's gated
        # on privileged role alone, same bar _is_authorized_for_target
        # applies to a single named employee.
        # PRIVILEGED_ROLES below is a numeric role_id set ({"1","2","3","4"}),
        # which the live tokens do not match: the sample manager token carries
        # role_id "5" with role_name "manager", so a real manager failed this
        # check and was told to "check with HR or your manager" about their own
        # report's attendance. The shared rule (manager, HR or admin, from
        # erp-api's is_manager/is_hr or the JWT role NAME) is asked first and
        # the numeric set is left in place behind it as the narrower fallback.
        _may_see_target = permission_service.may_view_team(state, claims=claims) is True

        if len(target_employees) > 1 and not _may_see_target and not _is_privileged_role(current_user_role):
            logger.info(
                "[Graph] attendance access denied (multi-employee): "
                "user='%s' role='%s' requested=%r",
                current_user_name, current_user_role, target_employees,
            )
            return _finish(
                "I can only show your own attendance. For another "
                "employee's attendance, please check with HR or your manager.",
                intent="attendance_denied",
            )

        current_user_emp_no = claims.get("emp_no")

        if len(target_employees) <= 1 and not _may_see_target and not _is_authorized_for_target(
            current_user_name,
            current_user_role,
            target_employee,
            current_user_emp_no,
        ):
            logger.info(
                "[Graph] attendance access denied: "
                "user='%s' role='%s' requested='%s'",
                current_user_name,
                current_user_role,
                target_employee,
            )

            return _finish(
                "I can only show your own attendance. For another "
                "employee's attendance, please check with HR or your manager.",
                intent="attendance_denied",
            )

        # The authorization check above already treats a name OR emp_no
        # matching the caller's own JWT identity as authorized — but every
        # erp_client call below still forwarded target_employee AS-IS,
        # meaning "show my attendance for <own name/emp_no>" went through
        # erp-api's name-SEARCH path instead of the plain self-scoped one
        # (bearer_token alone, no employee_name) that "show my attendance"
        # with no name at all uses. That search path isn't guaranteed to
        # behave identically to the self path — a near-miss on erp-api's
        # own matching, or another employee sharing a similar name, could
        # return the wrong (or no) data for what is unambiguously a
        # self-query. Normalizing here, once, means every downstream
        # employee_name=target_employee call gets the same reliable self
        # path a nameless query already gets.
        if target_employee and _is_self_reference(current_user_name, current_user_emp_no, target_employee):
            target_employee = None

        # ============================================================
        # Step 1c: Normalize dates
        # ============================================================

        # The LLM found NO date reference at all ("show my attendance") —
        # before letting _normalize_attendance_dates collapse that to
        # today (its own documented default for this file), 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 a dateless follow-up naming this topic —
        # confirmed live/reported for the sibling punch_details/
        # attendance_explain flows; same fix here). Only relevant on the
        # LLM-extraction path — the deterministic layer never produces
        # "unknown" itself.
        if deterministic_query_params is None and isinstance(parsed, dict) and parsed.get("type") == "unknown":
            carried_over = last_resolved_date_state.consume_last_resolved_date(company_id, conversation_id)
            if carried_over:
                deterministic_query_params = {"type": "single", "date": _parse_iso_date(carried_over)}

        query_params = deterministic_query_params or _normalize_attendance_dates(
            parsed,
            today,
            date_query_resolver.detect_week_start_override(query) or 0,
        )

        if not query_params:
            return _finish(
                "I couldn't figure out which date or date range you're "
                "asking about — could you rephrase, e.g. "
                "'was I present yesterday' or 'my attendance this week'?"
            )

        # A concrete single date was resolved this turn — refresh the
        # cross-turn memory so a LATER dateless follow-up can still
        # recover it. Ranges are skipped: "the date we were discussing"
        # isn't well-defined for a multi-day span.
        if query_params.get("type") == "single":
            last_resolved_date_state.set_last_resolved_date(
                company_id, conversation_id, query_params["date"].isoformat(),
            )

        wants_reg = _wants_regularization(query)

        # ============================================================
        # Step 1d: MULTIPLE named employees in one query
        # ============================================================
        # Handled as its own path rather than threaded through every
        # branch below: regularization is inherently a single-person,
        # same-turn action, so it isn't offered here — a manager asking
        # about several reports at once just gets each of their statuses.

        if len(target_employees) > 1:
            return await _fetch_multi_employee_attendance(
                target_employees,
                query_params,
                today,
                bearer_token,
                company_id,
                conversation_id,
                writer,
                _finish,
            )

        # ============================================================
        # Step 2: SINGLE DATE
        # ============================================================

        if query_params["type"] == "single":

            writer({
                "type": "fetching_attendance",
                "message": "Checking your attendance...",
            })

            try:
                result = await attendance_service.get_attendance_single(
                    bearer_token,
                    target_date=query_params["date"],
                    company_id=company_id,
                    conversation_id=conversation_id,
                    employee_name=target_employee,
                )

            except attendance_service.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 attendance_service.ErpApiUnauthorized:
                return _finish("Sorry, your session has expired — please log in again to continue.")

            except attendance_service.ErpApiUnavailable:
                return _finish(
                    "I'm unable to reach the HR system right now — "
                    "please try again shortly."
                )

            except Exception:
                logger.exception(
                    "[Graph] Unexpected error fetching "
                    "single-date attendance"
                )

                return _finish(
                    "I couldn't fetch your attendance right now — please try again in a moment."
                )

            if not result.get("success", True):
                return _finish(
                    result.get("message")
                    or "I couldn't fetch your attendance right now."
                )

            if target_employee and result.get("data", {}).get("search_matched") is False:
                return _finish(
                    f"No employee found with the name '{target_employee}'.",
                    intent="attendance_employee_not_found",
                )

            raw_status = result.get("data", {}).get("status")

            msg, rows = _format_single_date(
                query_params["date"],
                raw_status,
                today,
            )

            date_iso = query_params["date"].strftime("%Y-%m-%d")

            # ========================================================
            # Same-turn regularization handoff
            # ========================================================

            if wants_reg:
                return _handoff_to_regularisation(
                    writer,
                    msg,
                    usage_events,
                    company_id,
                    conversation_id,
                    date_iso=date_iso,
                    employee_name=target_employee,
                )

            writer({
                "type": "attendance_single",
                "data": {
                    "rows": rows
                },
            })

            if rows and _is_regularizable(rows[0]["status"]):
                _seed_pending_regularization(
                    company_id,
                    conversation_id,
                    date_iso=date_iso,
                    employee_name=target_employee,
                    offer_only=True,
                )

            return _finish(
                msg + _attendance_followup(rows),
                extra_data={
                    "rows": rows,
                    "node_type": "status",
                },
            )

        # ============================================================
        # Step 3: DATE RANGE
        # ============================================================

        start_date = query_params["start_date"]
        end_date = query_params["end_date"]

        span_days = (
            end_date - start_date
        ).days + 1

        # ============================================================
        # Step 3a: Inline range <= 31 days
        # ============================================================

        if span_days <= ATTENDANCE_MAX_INLINE_RANGE_DAYS:

            writer({
                "type": "fetching_attendance",
                "message": "Checking your attendance...",
            })

            try:
                result = await attendance_service.get_attendance_range(
                    bearer_token,
                    start_date=start_date,
                    end_date=end_date,
                    company_id=company_id,
                    conversation_id=conversation_id,
                    employee_name=target_employee,
                )

            except attendance_service.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 attendance_service.ErpApiUnauthorized:
                return _finish("Sorry, your session has expired — please log in again to continue.")

            except attendance_service.ErpApiUnavailable:
                return _finish(
                    "I'm unable to reach the HR system right now — "
                    "please try again shortly."
                )

            except Exception:
                logger.exception(
                    "[Graph] Unexpected error fetching "
                    "attendance range"
                )

                return _finish(
                    "I couldn't fetch your attendance right now — please try again in a moment."
                )

            if not result.get("success", True):
                return _finish(
                    result.get("message")
                    or "I couldn't fetch your attendance right now."
                )

            if target_employee and result.get("data", {}).get("search_matched") is False:
                return _finish(
                    f"No employee found with the name '{target_employee}'.",
                    intent="attendance_employee_not_found",
                )

            records = result.get(
                "data",
                {}
            ).get(
                "records",
                []
            )

            msg, rows, absent_isos = _format_date_range(
                start_date,
                end_date,
                records,
                today,
            )

            # ========================================================
            # Regularization requested
            # ========================================================

            if wants_reg:

                # Exactly one absent date
                if len(absent_isos) == 1:
                    return _handoff_to_regularisation(
                        writer,
                        msg,
                        usage_events,
                        company_id,
                        conversation_id,
                        date_iso=absent_isos[0],
                        employee_name=target_employee,
                    )

                writer({
                    "type": "attendance_range",
                    "data": {
                        "rows": rows
                    },
                })

                # Multiple absent dates
                if len(absent_isos) > 1:

                    _seed_pending_regularization(
                        company_id,
                        conversation_id,
                        employee_name=target_employee,
                        candidate_dates=absent_isos,
                    )

                    ask = (
                        "\n\nYou were absent on multiple days in "
                        "this range — which date would you like "
                        "to regularize?"
                    )

                    return _finish(
                        msg + ask,
                        extra_data={
                            "rows": rows,
                            "node_type": "status",
                        },
                    )

                # No absent dates
                return _finish(
                    msg
                    + "\n\nYou weren't marked absent in this period, "
                      "so there's nothing to regularize.",
                    extra_data={
                        "rows": rows,
                        "node_type": "status",
                    },
                )

            # ========================================================
            # Normal attendance range response
            # ========================================================

            writer({
                "type": "attendance_range",
                "data": {
                    "rows": rows
                },
            })

            if len(absent_isos) == 1:
                _seed_pending_regularization(
                    company_id,
                    conversation_id,
                    date_iso=absent_isos[0],
                    employee_name=target_employee,
                    offer_only=True,
                )

            elif absent_isos:
                _seed_pending_regularization(
                    company_id,
                    conversation_id,
                    employee_name=target_employee,
                    candidate_dates=absent_isos,
                    offer_only=True,
                )

            return _finish(
                msg + _attendance_followup(rows),
                extra_data={
                    "rows": rows,
                    "node_type": "status",
                },
            )

        # ============================================================
        # Step 4: Long-range attendance summary
        # ============================================================

        writer({
            "type": "fetching_attendance_summary",
            "message": "Summarizing your attendance...",
        })

        try:
            result = await attendance_service.get_attendance_summary(
                bearer_token,
                start_date=start_date,
                end_date=end_date,
                company_id=company_id,
                conversation_id=conversation_id,
                employee_name=target_employee,
            )

        except attendance_service.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 attendance_service.ErpApiUnauthorized:
            return _finish("Sorry, your session has expired — please log in again to continue.")

        except attendance_service.ErpApiUnavailable:
            return _finish(
                "I'm unable to reach the HR system right now — "
                "please try again shortly."
            )

        except Exception:
            logger.exception(
                "[Graph] Unexpected error fetching "
                "attendance summary"
            )

            return _finish(
                "I couldn't fetch your attendance summary right now — please try again in a moment."
            )

        if not result.get("success", True):
            return _finish(
                result.get("message")
                or "I couldn't fetch your attendance summary right now."
            )

        if target_employee and result.get("data", {}).get("search_matched") is False:
            return _finish(
                f"No employee found with the name '{target_employee}'.",
                intent="attendance_employee_not_found",
            )

        summary = result.get("data", {})

        msg = _format_long_range_summary(
            start_date,
            end_date,
            summary,
        )

        # erp-api's summary payload reports aggregate stats only — it never
        # echoes back which date range was actually queried, so the
        # frontend has no way to show/highlight the selected period
        # alongside the numbers. Added explicitly here from the range this
        # node itself resolved (start_date/end_date), the same values
        # _format_long_range_summary was just given.
        selected = {
            "start_date": start_date.isoformat(),
            "end_date": end_date.isoformat(),
        }

        writer({
            "type": "attendance_summary",
            "data": {**summary, "selected": selected},
        })

        return _finish(
            msg,
            intent="attendance_summary",
            extra_data={
                **summary,
                "selected": selected,
                "node_type": "summary",
            },
        )

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

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

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

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

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

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

# ── Helpers (pure formatting/parsing logic, no API calls) ──────────────────

def _normalize_attendance_dates(parsed: dict, today: date) -> Optional[dict]:
    # BUG FIX: guard against parsed being None/non-dict (e.g. malformed
    # LLM output). Previously this called parsed.get(...) unconditionally
    # and would raise AttributeError, crashing the node instead of
    # returning None and hitting the "couldn't figure out the date"
    # fallback message in attendance_node.
    if not isinstance(parsed, dict):
        return None
    try:
        if parsed.get("type") == "single" and parsed.get("date"):
            return {"type": "single", "date": _parse_iso_date(parsed["date"])}
        if parsed.get("type") == "range" and parsed.get("start_date") and parsed.get("end_date"):
            start = _parse_iso_date(parsed["start_date"])
            end = _parse_iso_date(parsed["end_date"])
            if start > end:
                start, end = end, start
            return {"type": "range", "start_date": start, "end_date": end}
    except (ValueError, TypeError):
        pass
    return None


def _parse_iso_date(value: str) -> date:
    return datetime.strptime(value, "%Y-%m-%d").date()


def _resolve_attendance_status(record_date: date, raw_status: Optional[str], today: date) -> str:
    if record_date > today:
        return "Upcoming"
    if not raw_status:
        return "Not Recorded"
    return raw_status


def _format_single_date(target_date: date, raw_status: Optional[str], today: date) -> tuple[str, list[dict]]:
    status = _resolve_attendance_status(target_date, raw_status, today)
    day_name = target_date.strftime("%A")
    date_str = target_date.strftime("%d %b %Y")

    if status == "Upcoming":
        msg = f"{date_str} ({day_name}) is an upcoming date, so there's no attendance record yet."
    elif status == "Not Recorded":
        # Same voice as punch_details' own empty-result sentence — it says
        # what was looked up and that nothing was there, rather than reading
        # as a lookup that failed. Deliberately NO "try another date" nudge
        # appended here, unlike punch_details: this string is also composed
        # into the multi-employee list as "**{name}**: {msg}", where the
        # nudge would repeat once per person.
        msg = (f"I couldn't find an attendance record for {date_str} ({day_name}) — "
               f"nothing was logged for that day.")
    else:
        msg = f"You were marked **{status}** on {date_str} ({day_name})."

    return msg, [{"date": date_str, "day": day_name, "status": status}]


def _format_date_range(start_date: date, end_date: date, records: list[dict],
                        today: date) -> tuple[str, list[dict], list[str]]:
    by_date = {r.get("date"): r.get("status") for r in records if r.get("date")}
    rows, lines, absent_isos = [], ["| Date | Day | Status |", "|------|-----|--------|"], []

    current = start_date
    while current <= end_date:
        iso = current.strftime("%Y-%m-%d")
        raw_status = by_date.get(iso)
        status = _resolve_attendance_status(current, raw_status, today)
        day_name = current.strftime("%A")
        date_str = current.strftime("%d %b %Y")
        rows.append({"date": date_str, "day": day_name, "status": status})
        lines.append(f"| {date_str} | {day_name} | {status} |")
        if _is_regularizable(status):
            absent_isos.append(iso)
        current += timedelta(days=1)

    msg = "Here's your attendance for the requested period:\n\n" + "\n".join(lines)
    return msg, rows, absent_isos


def _format_long_range_summary(start_date: date, end_date: date, summary: dict) -> str:
    return (
        f"Your requested range ({start_date.strftime('%d %b %Y')} – {end_date.strftime('%d %b %Y')}) "
        f"spans more than {ATTENDANCE_MAX_INLINE_RANGE_DAYS} days, so here's a summary instead of "
        f"a full daily breakdown:\n\n"
        f"- **Present:** {summary.get('present_count', 0)}\n"
        f"- **Absent:** {summary.get('absent_count', 0)}\n"
        f"- **Leave:** {summary.get('leave_count', 0)}\n\n"
        f"For day-by-day details, open the Attendance module."
    )


def _attendance_followup(rows: list[dict]) -> str:
    absent = [r for r in rows if _is_regularizable(r["status"])]
    if not absent:
        return ""
    if len(absent) == 1:
        return f"\n\nWould you like to check the regularization process for {absent[0]['date']}?"
    return (
        f"\n\nYou were marked absent on {len(absent)} day(s) in this period. "
        f"Would you like to check the regularization process for any of these?"
    )

# ── Ownership guardrail helpers ─────────────────────────────────────────────

def _decode_jwt_claims(bearer_token: Optional[str]) -> dict:
    """
    Reads identity claims (name, role) out of the JWT payload without
    verifying the signature — signature/expiry verification is assumed to
    already have happened upstream (auth middleware). This is used purely
    for the "am I allowed to see this person's attendance" guardrail.

    NOTE: swap the claim keys read in attendance_node() (e.g. "name",
    "role") if your token schema uses different field names.
    """
    if not bearer_token:
        return {}
    try:
        token = bearer_token.split(" ", 1)[-1] if bearer_token.lower().startswith("bearer ") else bearer_token
        payload_segment = token.split(".")[1]
        padded = payload_segment + "=" * (-len(payload_segment) % 4)
        decoded = base64.urlsafe_b64decode(padded.encode("utf-8"))
        return json.loads(decoded)
    except Exception as e:
        logger.warning(f"[Graph] failed to decode JWT for attendance guardrail: {e}")
        return {}


def _names_match(current_name: Optional[str], target_name: Optional[str]) -> bool:
    # BUG FIX (security): the previous version used raw substring
    # containment ("a in b or b in a"), which lets e.g. "Sam" pass as a
    # match for "Samantha Iyer", or "Ali" match "Alison" — a real
    # cross-employee data exposure risk in an authorization check. This
    # now requires the normalized names to be exactly equal, OR every
    # whitespace-separated token of the shorter name to appear as a whole
    # token in the longer name (so "John Smith" still matches "John" or
    # "Smith" alone, but "Sam" no longer matches "Samantha").
    if not current_name or not target_name:
        return False

    norm = lambda s: " ".join(s.strip().lower().split())
    a, b = norm(current_name), norm(target_name)

    if a == b:
        return True

    a_tokens, b_tokens = set(a.split()), set(b.split())
    shorter, longer = (a_tokens, b_tokens) if len(a_tokens) <= len(b_tokens) else (b_tokens, a_tokens)

    return bool(shorter) and shorter.issubset(longer)


def _is_privileged_role(current_role) -> bool:
    roles = current_role if isinstance(current_role, (list, set, tuple)) else [current_role]
    # BUG FIX: compare as normalized strings so numeric role_id values
    # (e.g. int 1 from a JWT) still match PRIVILEGED_ROLES' string entries.
    return any(r is not None and str(r).strip().lower() in PRIVILEGED_ROLES for r in roles)


def _matches_own_emp_no(current_emp_no: Optional[str], target: Optional[str]) -> bool:
    """Exact, case-insensitive match against the caller's own employee
    number (e.g. JWT "emp_no": "geo2") — unlike _names_match, no token-
    subset logic applies here: an emp_no is a short, company-unique code by
    construction, not a human name with first/last-name parts, so only an
    exact match after normalization counts."""
    if not current_emp_no or not target:
        return False
    return str(current_emp_no).strip().lower() == str(target).strip().lower()


def _is_self_reference(current_name: Optional[str], current_emp_no: Optional[str],
                        target: Optional[str]) -> bool:
    """True when `target` (an employee_name string extracted from a query)
    actually refers to the CALLER themselves — either their own name or
    their own employee number. Two employees might share a first/last name
    token (_names_match already guards against that), but sharing the same
    emp_no is impossible — it's a unique code — so that check needs no such
    caution."""
    return _names_match(current_name, target) or _matches_own_emp_no(current_emp_no, target)


def _is_authorized_for_target(current_name: Optional[str], current_role,
                               target_employee: Optional[str],
                               current_emp_no: Optional[str] = None) -> bool:
    """
    Allows the query through if:
      - no specific employee was named (i.e. they're asking about themselves), OR
      - the caller has a privileged role (HR/admin/manager), OR
      - the named employee matches the caller's own name or employee number
        from the JWT.
    """
    if not target_employee:
        return True

    if _is_privileged_role(current_role):
        return True

    return _is_self_reference(current_name, current_emp_no, target_employee)


# Re-exported under this name for backward compatibility with call sites
# and tests written before this moved into the shared name_parsing module
# (shift_query.py needs the identical splitting rules).
_split_employee_names = split_employee_names


# ── Step 1: LLM extracts SYMBOLIC expression + employee_name (no arithmetic) ──

def _build_attendance_date_extraction_prompt(query: str, today: date) -> str:
    """
    Extracts WHAT the user is referring to (symbolically) and who, but never
    computes actual dates — all date arithmetic happens in Python afterwards
    via _resolve_date_expression(). This keeps results deterministic and
    robust to misspellings without relying on the LLM to do weekday/week
    math, which is unreliable.
    """
    today_str = today.strftime("%Y-%m-%d")
    today_day = today.strftime("%A")

    return f"""You extract date REFERENCES (not actual dates) from an employee's attendance question.
Today is {today_str} ({today_day}). The user may misspell words
(e.g. "mondey", "las week", "fryday", "form") — correct these silently.

Do NOT calculate any date yourself. Only classify the reference using this schema:

{{
  "type": "today | yesterday | tomorrow | weekday | next_weekday | relative_days | upcoming_days | relative_months |
           this_week | last_week | this_month | last_month | explicit_month | explicit_single | explicit_range |
           from_explicit_to_today | unknown",
  "weekday": "monday|tuesday|...|sunday" or null,
  "weeks_ago": integer or null,     // for "weekday" type: "last monday"=1, "last to last week monday"=2, "this monday"=0
  "n_days": integer or null,        // for "relative_days": "last 7 days" -> 7. For "upcoming_days": "next 3 days" -> 3
  "n_months": integer or null,      // for "relative_months": "last 2 months" -> 2
  "month": integer 1-12 or null,    // for "explicit_month": the named month, e.g. "june" -> 6
  "year": integer or null,          // for "explicit_month": ONLY if a year was explicitly stated, else null
  "explicit_date": "YYYY-MM-DD" or null,        // for explicit_single / from_explicit_to_today
  "explicit_start": "YYYY-MM-DD" or null,       // for explicit_range
  "explicit_end": "YYYY-MM-DD" or null,         // for explicit_range
  "employee_name": string or null   // null if user means themselves ("my", "I", "me", no name given).
                                     // If MULTIPLE employees are named, join them verbatim with commas
                                     // (e.g. "geo3, geo5, geo9") — never pick just one.
}}

RULES:
- "today"/"yesterday"/"tomorrow" -> that type, everything else null.
- "last <weekday>" -> type "weekday", weeks_ago=1.
- "last to last week <weekday>" / "<weekday> before last" -> type "weekday", weeks_ago=2.
- "this <weekday>" -> type "weekday", weeks_ago=0.
- "next <weekday>" -> type "next_weekday" (a FUTURE date — never confuse with "this <weekday>").
- "last N days" -> type "relative_days", n_days=N (a PAST range: the N most recent days INCLUDING today).
- "next N days" / "upcoming N days" / "coming N days" -> type "upcoming_days", n_days=N — a FUTURE range,
  the N days AFTER today, NOT including today itself. NEVER map this onto "relative_days" just because
  both mention "N days" — that type is PAST-only and would silently answer about the wrong days entirely.
- "last N months" -> type "relative_months", n_months=N.
- A bare "N months" with NO "last"/"past"/"previous" qualifier (e.g. "two months attendance",
  "show 2 months data", "attendance for 3 months") still means the PAST N months ending today —
  map it onto "relative_months" the same as "last N months". Do NOT classify this as "unknown"
  just because the qualifier word is missing.
- "this week" -> type "this_week". "last week" -> type "last_week".
- "this month" -> type "this_month". "last month" -> type "last_month".
- A bare NAMED month with no specific day number (e.g. "june month", "attendance for august", "march
  report") -> type "explicit_month", month set to that month's number, year set ONLY if a year was
  separately stated (e.g. "june 2025"), otherwise null (Python fills in the current year). Never map a
  named month onto "last_month"/"this_month" — those are ONLY for the literal words "last/this month".
- An explicit calendar date (e.g. "21 July 2026", "21/07/2026") -> explicit_single, explicit_date set.
- Two explicit dates ("from X to Y", "between X and Y") -> explicit_range.
- One explicit date + "till/until today" -> from_explicit_to_today, explicit_date set.
- If NO date reference is identifiable at all -> type "unknown".
- If the user names another employee, set employee_name to that name; otherwise null.
- If the user names SEVERAL employees (e.g. "geo3, geo5 and geo9", "attendance for John and Priya"),
  set employee_name to ALL of them joined by commas, preserving each name exactly as written.

CRITICAL — slash/dash numeric dates are DD/MM/YYYY (day first), NEVER MM/DD/YYYY,
even when both numbers are <= 12 and the format looks ambiguous:
- "10/08/2026" -> explicit_date "2026-08-10" (10th of August, NOT October 8th)
- "05-03-2026" -> explicit_date "2026-03-05" (5th of March, NOT May 3rd)
- A slash/dash numeric date with only TWO components, no year (e.g. "12-08", "21/07") is
  still DD/MM (day first) — use {today_str}'s year ({today.year}) since none was stated:
  "12-08" -> explicit_date "{today.year}-08-12" (12th of August THIS year, NOT the 8th of December).
- A day + NAMED month with a specific day number but no year stated (e.g. "23 aug", "12 August") ->
  explicit_single, using {today_str}'s year ({today.year}) — NEVER left as type "unknown" and NEVER
  defaulted to today's date just because no year was given:
  "23 aug" -> explicit_date "{today.year}-08-23" (23rd of August THIS year).

EXAMPLES:
"was I present yesterday" -> {{"type":"yesterday","weekday":null,"weeks_ago":null,"n_days":null,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"attendance last monday" -> {{"type":"weekday","weekday":"monday","weeks_ago":1,"n_days":null,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"mondey last to last week" -> {{"type":"weekday","weekday":"monday","weeks_ago":2,"n_days":null,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"was Shahid present last fryday" -> {{"type":"weekday","weekday":"friday","weeks_ago":1,"n_days":null,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":"Shahid"}}
"attendance for geo3, geo5 and geo9 today" -> {{"type":"today","weekday":null,"weeks_ago":null,"n_days":null,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":"geo3, geo5, geo9"}}
"attendance for next monday" -> {{"type":"next_weekday","weekday":"monday","weeks_ago":null,"n_days":null,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"show my attendance this week" -> {{"type":"this_week","weekday":null,"weeks_ago":null,"n_days":null,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"attendance last 7 days" -> {{"type":"relative_days","weekday":null,"weeks_ago":null,"n_days":7,"n_months":null,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"attendance for the upcoming 2 days" -> {{"type":"upcoming_days","weekday":null,"weeks_ago":null,"n_days":2,"n_months":null,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"show attendance for the last 2 months" -> {{"type":"relative_months","weekday":null,"weeks_ago":null,"n_days":null,"n_months":2,"month":null,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"give my attendance june month" -> {{"type":"explicit_month","weekday":null,"weeks_ago":null,"n_days":null,"month":6,"year":null,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"attendance for august 2025" -> {{"type":"explicit_month","weekday":null,"weeks_ago":null,"n_days":null,"month":8,"year":2025,"explicit_date":null,"explicit_start":null,"explicit_end":null,"employee_name":null}}
"check attendace form 21 july 2026 ....?" -> {{"type":"explicit_single","weekday":null,"weeks_ago":null,"n_days":null,"month":null,"year":null,"explicit_date":"2026-07-21","explicit_start":null,"explicit_end":null,"employee_name":null}}
"why was i absent on 12-08" -> {{"type":"explicit_single","weekday":null,"weeks_ago":null,"n_days":null,"month":null,"year":null,"explicit_date":"{today.year}-08-12","explicit_start":null,"explicit_end":null,"employee_name":null}}
"was i present on 23 aug" -> {{"type":"explicit_single","weekday":null,"weeks_ago":null,"n_days":null,"month":null,"year":null,"explicit_date":"{today.year}-08-23","explicit_start":null,"explicit_end":null,"employee_name":null}}
"check attendance from 21 July 2026 till today" -> {{"type":"from_explicit_to_today","weekday":null,"weeks_ago":null,"n_days":null,"month":null,"year":null,"explicit_date":"2026-07-21","explicit_start":null,"explicit_end":null,"employee_name":null}}
"check attendance from 21 july 2026 to 25 july 2026" -> {{"type":"explicit_range","weekday":null,"weeks_ago":null,"n_days":null,"month":null,"year":null,"explicit_date":null,"explicit_start":"2026-07-21","explicit_end":"2026-07-25","employee_name":null}}

OUTPUT ONLY THE JSON OBJECT. No explanation. No markdown. No code fences.

Current User Query: {query}"""


# ── Step 2: Python resolves the symbolic expression into real dates ──────────

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


def _first_of_month_offset(today: date, months_back: int) -> date:
    """First day of the month `months_back` months before today's month."""
    total = (today.year * 12 + (today.month - 1)) - months_back
    year, month0 = divmod(total, 12)
    return date(year, month0 + 1, 1)


def _resolve_weekday(today: date, weekday_name: str, weeks_ago: int) -> Optional[date]:
    weekday_name = (weekday_name or "").lower()
    if weekday_name not in WEEKDAYS:
        return None
    target = WEEKDAYS[weekday_name]

    if weeks_ago == 0:
        # "this monday" -> Monday of the current week
        return today - timedelta(days=today.weekday() - target)

    # Most recent occurrence strictly before today, then step back extra weeks
    delta = (today.weekday() - target) % 7
    delta = delta or 7
    most_recent = today - timedelta(days=delta)
    return most_recent - timedelta(weeks=(weeks_ago or 1) - 1)


# ── Deterministic pre-resolution of common date references ──────────────────
# Same idea as punch_details.py's _resolve_date_deterministic /
# attendance_explain.py's _resolve_relative_date_deterministically: before
# ever asking the LLM to classify the date reference (Step 1 in
# attendance_node below), try to recognize the common, unambiguous
# phrasings (today/yesterday/weekday names/this-last week-month/last N
# days) with plain regex. These are the bulk of real attendance traffic —
# confirmed live, short/typo'd/Hinglish queries like "18 aug dl attendance"
# were exactly the ones where the LLM classification step sometimes picked
# the wrong symbolic type or returned "unknown" outright, surfacing as
# "date not picking properly". Skipping the LLM call for these removes
# that misclassification risk entirely (and the latency) rather than
# chasing it with more prompt examples. Anything this can't confidently
# recognize — explicit dates, ranges, unusual phrasing — still falls
# through to the existing LLM-based extraction, unchanged.
_WEEKDAY_ALTERNATION = "|".join(WEEKDAYS.keys())
# today/yesterday/tomorrow, optionally "day before "/"day after " prefixed
# (each shifts the named day by one more: "day after tomorrow" = +2, "day
# before yesterday" = -2, "day after yesterday" = 0 — colloquial for today),
# with typo tolerance (difflib, cutoff swept against real typos and common
# query vocabulary with no false positives at 0.8 — same methodology and
# cutoff as the weekday-typo matching below, which already documented the
# same "today" vs "monday" collision at a lower cutoff).
_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(query: str) -> Optional[int]:
    m = _RELATIVE_DAY_PATTERN.search(query)
    if m:
        prefix, word = m.group(1), m.group(2).lower()
    else:
        prefix = word = None
        for tm in _RELATIVE_DAY_TYPO_TOKEN_PATTERN.finditer(query):
            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


_ATTENDANCE_THIS_WEEK_RE = re.compile(r"\bthis\s+week\b", re.IGNORECASE)
_ATTENDANCE_LAST_WEEK_RE = re.compile(r"\blast\s+week\b", re.IGNORECASE)
_ATTENDANCE_THIS_MONTH_RE = re.compile(r"\bthis\s+month\b", re.IGNORECASE)
_ATTENDANCE_LAST_MONTH_RE = re.compile(r"\blast\s+month\b", re.IGNORECASE)

# "last week to next week" — a 3-calendar-week span (last week's Monday
# through next week's Sunday), NOT the same thing as either bare "last
# week" or bare "this week" alone. Confirmed live: "check attendance from
# last week to next week" matched bare _ATTENDANCE_LAST_WEEK_RE on its
# leading "last week" substring and silently discarded "to next week"
# entirely, returning just last week's range — "next week" never had any
# effect on the result at all. Must be checked BEFORE
# _ATTENDANCE_LAST_WEEK_RE/_ATTENDANCE_THIS_WEEK_RE below for that reason,
# same ordering issue as _ATTENDANCE_WEEK_QUALIFIED_WEEKDAY_RE above.
_ATTENDANCE_LAST_WEEK_TO_NEXT_WEEK_RE = re.compile(
    r"\b(?:last\s+week\s+to\s+next\s+week|next\s+week\s+to\s+last\s+week)\b", re.IGNORECASE,
)

# "last week Sunday" / "Sunday last week" / "this week Friday" — a SPECIFIC
# day within a calendar week (Mon-Sun), NOT the same thing as the bare
# this_week/last_week RANGE types above, which _ATTENDANCE_THIS_WEEK_RE /
# _ATTENDANCE_LAST_WEEK_RE alone would otherwise match first (they fire on
# the bare substring "last week"/"this week" with no regard for a weekday
# named alongside it) — confirmed live: "attendance for last week Sunday"
# (and every other weekday, not just Sunday) returned the WHOLE previous
# Mon-Sun range, silently discarding the named day. Must be checked BEFORE
# _ATTENDANCE_THIS_WEEK_RE/_ATTENDANCE_LAST_WEEK_RE below for that reason —
# same ordering _ATTENDANCE_LAST_TO_LAST_WEEKDAY_RE already needs against
# the same two patterns, just one qualifier word ("last to last") instead
# of ("this"/"last"), and same idea as punch_details.py's own
# _resolve_week_qualified_weekday (calendar-week Monday-anchored, order-
# independent) — deliberately NOT reusing _resolve_weekday's "weeks_ago"
# recency-based math here: weeks_ago=1 there means "the most recent
# occurrence before today", which only coincides with "last CALENDAR week's
# <weekday>" when today falls on or after that weekday within the current
# week — asked earlier in the week it silently returns a date from THIS
# week instead (e.g. "last week Monday" asked on a Wednesday would give
# yesterday's Monday, not last week's).
_ATTENDANCE_WEEK_QUALIFIED_WEEKDAY_RE = re.compile(
    rf"\b(this|last)\s+week\s+({_WEEKDAY_ALTERNATION})\b|"
    rf"\b({_WEEKDAY_ALTERNATION})\s+(this|last)\s+week\b",
    re.IGNORECASE,
)


def _resolve_week_qualified_weekday_deterministic(query: str, today: date) -> Optional[str]:
    m = _ATTENDANCE_WEEK_QUALIFIED_WEEKDAY_RE.search(query)
    if not m:
        return None
    if m.group(1):
        qualifier, weekday_name = m.group(1).lower(), m.group(2).lower()
    else:
        weekday_name, qualifier = m.group(3).lower(), m.group(4).lower()
    target_weekday = WEEKDAYS[weekday_name]
    this_monday = today - timedelta(days=today.weekday())
    week_monday = this_monday - timedelta(weeks=1) if qualifier == "last" else this_monday
    return (week_monday + timedelta(days=target_weekday)).isoformat()
_ATTENDANCE_RELATIVE_DAYS_RE = re.compile(r"\blast\s+(\d{1,3})\s+days?\b", re.IGNORECASE)
_ATTENDANCE_RELATIVE_MONTHS_RE = re.compile(r"\blast\s+(\d{1,2})\s+months?\b", re.IGNORECASE)
# "upcoming/next/coming N days" — a FUTURE range. Confirmed live: this had no
# symbolic type of its own anywhere in the schema (deterministic layer OR
# the LLM extraction prompt below only ever documented "last N days"), so
# "attendance for the upcoming 2 days" fell all the way through to the LLM,
# which — with no correct type available and "N days" superficially
# resembling "last N days" — picked "relative_days" anyway and got the
# PAST range that type is hardcoded to compute (today-(N-1) to today), e.g.
# "upcoming 2 days" asked on Sep 3 2026 returned Sep 2-3 (the two days
# ending today) instead of the two days actually coming up. "upcoming"/
# "next"/"coming" all mean the same thing here as bare "N days" phrasing
# goes; matched on ANY of the three rather than picking one, since a user
# could reasonably say any of them.
_ATTENDANCE_UPCOMING_DAYS_RE = re.compile(r"\b(?:upcoming|next|coming)\s+(\d{1,3})\s+days?\b", re.IGNORECASE)

# Bare named month (e.g. "june month", "attendance for august"), same
# _MONTH_NAMES dict as attendance_explain.py's/punch_details.py's (that
# duplication is intentional — they resolve different query shapes: a
# whole-month range here vs. an ordinal-weekday-within-month there).
#
# Deliberately NOT a plain "\b(month names)\b" search: several month names
# ("may" above all, but also this pattern guards "march"/"august" as
# ordinary words) double as common English words, so matching them
# anywhere would misfire on sentences like "may I check my attendance".
# Instead the month name must sit next to an anchor — the literal word
# "month", "in"/"for"/"during", or a year — that a modal/verb usage never
# does. Anything without such an anchor (a genuine "may" as a verb) falls
# through to the LLM, which reads the whole sentence.
_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,
}
_MONTH_ALTERNATION = "|".join(_MONTH_NAMES.keys())
_ATTENDANCE_MONTH_ANCHORED_RE = re.compile(
    rf"\b({_MONTH_ALTERNATION})\s+month\b"              # "june month"
    rf"|\bmonth\s+(?:of\s+)?({_MONTH_ALTERNATION})\b"    # "month of june"
    rf"|\b(?:in|for|during)\s+({_MONTH_ALTERNATION})\b"  # "in june" / "for august"
    rf"|\b({_MONTH_ALTERNATION})\s+(?:19|20)\d{{2}}\b"   # "june 2025"
    rf"|\b(?:19|20)\d{{2}}\s+({_MONTH_ALTERNATION})\b",  # "2025 june"
    re.IGNORECASE,
)
_ATTENDANCE_EXPLICIT_YEAR_RE = re.compile(r"\b((?:19|20)\d{2})\b")
_ATTENDANCE_DAY_NUMBER_RE = re.compile(r"\b\d{1,2}(?:st|nd|rd|th)?\b", re.IGNORECASE)

# Explicit single-date phrasing — numeric (DD/MM or DD/MM/YYYY, day first)
# or day + named month (with or without a year). Resolved deterministically
# for the same reason every other shortcut in this file exists: an LLM
# instructed "day-first, never month-first" can still slip and guess wrong
# (confirmed pattern throughout this file/attendance_explain.py/
# punch_details.py — weekday math, "last N months" collapsing, a year-less
# date silently defaulting to today). A numeric or day+month date is a
# closed, unambiguous shape — no NLU needed, so there's no reason to leave
# it to chance.
#
# The lookbehind keeps the numeric pattern from misreading the MM-DD tail
# of an ISO YYYY-MM-DD date (which uses the same '-' separator) as its own
# day/month pair.
# Separators tolerate surrounding whitespace ("10 - 08 - 2026") as well as
# the tight "10-08-2026" — without this, a space around the dash broke the
# match entirely (confirmed live/reported against the shared
# date_query_resolver.py copy of this same pattern — see its own comment).
#
# The year group itself tries a contiguous 4-digit year first, then a
# 4-digit year split by whitespace ("20 26" — confirmed live/reported: a
# stray space landing inside the year, e.g. "21 - 08 - 20 26", made
# \d{2,4} stop at "20" and read it as a 2-DIGIT year, silently resolving
# to 2020 instead of 2026), and only falls back to a genuine 2-digit year
# last. _resolve_explicit_date_symbolic below strips the internal
# whitespace before checking digit count.
_ATTENDANCE_YEAR_GROUP = r"(\d{4}|\d{2}\s+\d{2}|\d{2})"
_ATTENDANCE_EXPLICIT_NUMERIC_DATE_RE = re.compile(
    rf"(?<!\d{{4}}-)\b(\d{{1,2}})\s*[/-]\s*(\d{{1,2}})(?:\s*[/-]\s*{_ATTENDANCE_YEAR_GROUP})?\b"
)
_ATTENDANCE_DAY_THEN_MONTH_RE = re.compile(
    rf"\b(\d{{1,2}})(?:st|nd|rd|th)?\s+({_MONTH_ALTERNATION})\b(?:\s+(?:of\s+)?{_ATTENDANCE_YEAR_GROUP})?",
    re.IGNORECASE,
)
_ATTENDANCE_MONTH_THEN_DAY_RE = re.compile(
    rf"\b({_MONTH_ALTERNATION})\s+(\d{{1,2}})(?:st|nd|rd|th)?\b(?:\s*,?\s*{_ATTENDANCE_YEAR_GROUP})?",
    re.IGNORECASE,
)


def _resolve_explicit_date_symbolic(day: int, month: int, year_str: Optional[str], today: date) -> Optional[dict]:
    if not (1 <= day <= 31 and 1 <= month <= 12):
        return None
    if year_str:
        # Collapse the split-year whitespace the year group's "\d{2}\s+\d{2}"
        # alternative may have captured ("20 26" -> "2026") BEFORE checking
        # digit count, or a wrapped 4-digit year would still be misread as
        # a 2-digit one below.
        year_str = "".join(year_str.split())
        year = int(year_str)
        if year < 100:
            year += 2000
    else:
        # No year stated — use the current year rather than leaving it
        # null/defaulting to today's date (observed bug: a year-less
        # explicit date like "12-08" or "23 aug" was silently coming back
        # as today because nothing filled the year in).
        year = today.year
    try:
        resolved = date(year, month, day)
    except ValueError:
        return None
    return {"type": "explicit_single", **{
        **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "explicit_date": resolved.isoformat(),
    }}


def _find_all_explicit_dates(query: str, today: date) -> list[tuple[int, int, str]]:
    """Every explicit numeric or day+named-month date found in the query,
    as (start_pos, end_pos, iso_date), in order of appearance and
    de-duplicated by overlapping span. Used both to detect a two-date
    RANGE (see _resolve_explicit_range_deterministic) and to make the
    single-date resolver below bail out rather than silently matching
    only the first date of what's actually a range."""
    matches = []

    for m in _ATTENDANCE_EXPLICIT_NUMERIC_DATE_RE.finditer(query):
        resolved = _resolve_explicit_date_symbolic(int(m.group(1)), int(m.group(2)), m.group(3), today)
        if resolved:
            matches.append((m.start(), m.end(), resolved["explicit_date"]))

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

    matches.sort(key=lambda t: t[0])
    deduped: list[tuple[int, int, str]] = []
    last_end = -1
    for start, end, iso in matches:
        if start >= last_end:
            deduped.append((start, end, iso))
            last_end = end
    return deduped


_ATTENDANCE_RANGE_CONNECTOR_RE = re.compile(r"\b(to|through|until)\b", re.IGNORECASE)
_ATTENDANCE_BETWEEN_RE = re.compile(r"\bbetween\b", re.IGNORECASE)
_ATTENDANCE_TILL_TODAY_RE = re.compile(r"\b(?:till|until)\s+today\b", re.IGNORECASE)


def _looks_like_multi_date_query(query: str, dates: list[tuple[int, int, str]]) -> bool:
    """True when the query names a RANGE rather than one specific day —
    "1 july to 15 july", "between 1/07/2026 and 15/07/2026", "21 July till
    today" — so the single-date resolver below can bail out instead of
    silently matching only the first date it finds (observed bug: "1 july
    to 15 july" collapsed to just 1 July, dropping the rest of the range
    entirely)."""
    if len(dates) == 1 and _ATTENDANCE_TILL_TODAY_RE.search(query):
        return True
    if len(dates) >= 2 and (_ATTENDANCE_RANGE_CONNECTOR_RE.search(query) or _ATTENDANCE_BETWEEN_RE.search(query)):
        return True
    return False


def _resolve_explicit_range_deterministic(query: str, today: date) -> Optional[dict]:
    """Deterministic counterpart to _resolve_explicit_date_deterministic
    for the two range shapes the LLM prompt's own RULES describe — "from X
    to Y"/"between X and Y" (explicit_range) and "from X till/until today"
    (from_explicit_to_today). Must be checked BEFORE the single-date
    resolver in _resolve_attendance_type_deterministic, or the first date
    alone gets matched as a standalone explicit_single first."""
    dates = _find_all_explicit_dates(query, today)

    if len(dates) == 1 and _ATTENDANCE_TILL_TODAY_RE.search(query):
        return {"type": "from_explicit_to_today", **{
            **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "explicit_date": dates[0][2],
        }}

    if len(dates) >= 2 and (_ATTENDANCE_RANGE_CONNECTOR_RE.search(query) or _ATTENDANCE_BETWEEN_RE.search(query)):
        return {"type": "explicit_range", **{
            **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS,
            "explicit_start": dates[0][2], "explicit_end": dates[-1][2],
        }}

    return None


def _resolve_explicit_date_deterministic(query: str, today: date) -> Optional[dict]:
    dates = _find_all_explicit_dates(query, today)
    if _looks_like_multi_date_query(query, dates):
        return None

    m = _ATTENDANCE_EXPLICIT_NUMERIC_DATE_RE.search(query)
    if m:
        day, month, year_str = int(m.group(1)), int(m.group(2)), m.group(3)
        resolved = _resolve_explicit_date_symbolic(day, month, year_str, today)
        if resolved:
            return resolved

    m = _ATTENDANCE_DAY_THEN_MONTH_RE.search(query)
    if m:
        day, month_word, year_str = int(m.group(1)), m.group(2).lower(), m.group(3)
    else:
        m = _ATTENDANCE_MONTH_THEN_DAY_RE.search(query)
        if not m:
            return None
        month_word, day, year_str = m.group(1).lower(), int(m.group(2)), m.group(3)

    return _resolve_explicit_date_symbolic(day, _MONTH_NAMES[month_word], year_str, today)
_ATTENDANCE_NEXT_WEEKDAY_RE = re.compile(rf"\bnext\s+({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE)
_ATTENDANCE_LAST_TO_LAST_RE = re.compile(r"\blast\s+to\s+last\b", re.IGNORECASE)
_ATTENDANCE_LAST_TO_LAST_WEEKDAY_RE = re.compile(
    rf"\blast\s+to\s+last(?:\s+week)?\s+({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE
)
_ATTENDANCE_THIS_WEEKDAY_RE = re.compile(rf"\bthis\s+({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE)
_ATTENDANCE_LAST_WEEKDAY_RE = re.compile(rf"\blast\s+({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE)
_ATTENDANCE_BARE_WEEKDAY_RE = re.compile(rf"\b({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE)

# Any digit, weekday/month name, or a handful of other date-adjacent words
# — its ABSENCE is what confidently marks a query as genuinely date-less
# (see the end of _resolve_attendance_type_deterministic below), so this
# stays intentionally broad/permissive: a false "signal found" just means
# falling through to the LLM as before, never a wrong answer.
_ATTENDANCE_ANY_DATE_SIGNAL_RE = re.compile(
    rf"\d|\b(?:{_WEEKDAY_ALTERNATION})\b|\b(?:{_MONTH_ALTERNATION})\b|"
    rf"\b(?:week|month|year|today|yesterday|tomorrow)\b",
    re.IGNORECASE,
)

# A capitalized word appearing anywhere AFTER the first word of the query
# usually means a proper name ("was Shahid present last friday") — the
# deterministic shortcut bails out entirely in that case, falling through
# to the existing LLM extraction (which also resolves employee_name), so
# employee-name handling is never touched or risked by this change. Rare
# compared to self-queries, and a reliable name check needs real NLU
# anyway — not worth approximating with more regex.
_ATTENDANCE_MID_QUERY_CAPITALIZED_RE = re.compile(r"(?<=\s)[A-Z][a-z]+")

# Calendar vocabulary is routinely capitalized in natural typing ("21 July
# till today", "attendance for Monday") without meaning a person's name —
# without this whitelist, EVERY one of this file's own deterministic date
# shortcuts (weekday, month, relative-day) silently stopped firing the
# moment a user capitalized the word, falling all the way back to the LLM
# for something this file otherwise resolves for free (observed: "21 July
# till today" fell through to the LLM path solely because "July" was
# capitalized, even though the explicit-range resolver above already knew
# exactly what to do with it).
_ATTENDANCE_NAMED_EMPLOYEE_WHITELIST = frozenset(_MONTH_NAMES) | frozenset(WEEKDAYS) | frozenset(_RELATIVE_DAY_WORDS)


def _looks_like_named_employee_query(query: str) -> bool:
    return any(
        m.group(0).lower() not in _ATTENDANCE_NAMED_EMPLOYEE_WHITELIST
        for m in _ATTENDANCE_MID_QUERY_CAPITALIZED_RE.finditer(query)
    )


_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS = {
    "weekday": None, "weeks_ago": None, "n_days": None, "n_months": None, "month": None, "year": None,
    "explicit_date": None, "explicit_start": None, "explicit_end": None,
    "employee_name": None,
}



def _resolve_date_expression(parsed: dict, today: date, week_start: int = 0) -> Optional[dict]:
    """
    Deterministically turns the LLM's symbolic expression into the same
    shape _normalize_attendance_dates previously expected:
      {"type": "single", "date": date}  or
      {"type": "range", "start_date": date, "end_date": date}
    Returns None if unresolved ("unknown" or malformed).

    week_start: which day a calendar week begins on (Monday=0 ... Sunday=6)
    for the "this_week"/"last_week" branches below — see
    date_query_resolver.detect_week_start_override, whose result callers
    are expected to pass through here so an inline "last week starting
    Sunday" is honored even when the query fell through to this LLM-based
    path rather than date_query_resolver's own deterministic layer.
    """
    if not isinstance(parsed, dict):
        return None

    etype = parsed.get("type")

    try:
        if etype == "today":
            return {"type": "single", "date": today}

        if etype == "yesterday":
            return {"type": "single", "date": today - timedelta(days=1)}

        if etype == "tomorrow":
            return {"type": "single", "date": today + timedelta(days=1)}

        if etype == "single_offset":
            n = parsed.get("n_days")
            return {"type": "single", "date": today + timedelta(days=n)} if n is not None else None

        if etype == "weekday":
            d = _resolve_weekday(today, parsed.get("weekday"), parsed.get("weeks_ago"))
            return {"type": "single", "date": d} if d else None

        if etype == "next_weekday":
            weekday_name = (parsed.get("weekday") or "").lower()
            if weekday_name not in WEEKDAYS:
                return None
            target = WEEKDAYS[weekday_name]
            # Next occurrence strictly AFTER today — if today itself is that
            # weekday, "next" means 7 days out, not today (that's what
            # "this <weekday>" is for).
            delta = (target - today.weekday()) % 7 or 7
            return {"type": "single", "date": today + timedelta(days=delta)}

        if etype == "relative_days":
            n = parsed.get("n_days")
            if not n or n < 1:
                return None
            return {"type": "range", "start_date": today - timedelta(days=n - 1), "end_date": today}

        if etype == "upcoming_days":
            n = parsed.get("n_days")
            if not n or n < 1:
                return None
            # Strictly AFTER today, N days — the future-facing mirror of
            # relative_days above (which INCLUDES today as the most recent
            # of its N days). Excluding today matches "next_weekday"'s own
            # "strictly after today" convention elsewhere in this file:
            # "upcoming 2 days" said today means tomorrow and the day after,
            # not today itself. Per-day rendering already handles a future
            # date gracefully (_resolve_attendance_status marks anything
            # after today "Upcoming" — see _format_single_date/_format_date_
            # range), so no separate messaging is needed here.
            return {"type": "range", "start_date": today + timedelta(days=1), "end_date": today + timedelta(days=n)}

        if etype == "this_week":
            this_week_start = today - timedelta(days=(today.weekday() - week_start) % 7)
            return {"type": "range", "start_date": this_week_start, "end_date": today}

        if etype == "last_week":
            this_week_start = today - timedelta(days=(today.weekday() - week_start) % 7)
            last_week_start = this_week_start - timedelta(weeks=1)
            return {"type": "range", "start_date": last_week_start, "end_date": last_week_start + timedelta(days=6)}

        if etype == "this_month":
            return {"type": "range", "start_date": today.replace(day=1), "end_date": today}

        if etype == "last_month":
            first_of_this_month = today.replace(day=1)
            last_day_prev_month = first_of_this_month - timedelta(days=1)
            first_day_prev_month = last_day_prev_month.replace(day=1)
            return {"type": "range", "start_date": first_day_prev_month, "end_date": last_day_prev_month}

        if etype == "relative_months":
            n = parsed.get("n_months")
            if not n or n < 1:
                return None
            # N complete previous calendar months, ending the day before
            # this month started — same convention as last_month (its
            # N=1 case), extended: "last 2 months" -> the two full
            # calendar months before this one, not a rolling 60-day
            # window from today.
            first_of_this_month = today.replace(day=1)
            last_day_prev_month = first_of_this_month - timedelta(days=1)
            start = _first_of_month_offset(today, n)
            return {"type": "range", "start_date": start, "end_date": last_day_prev_month}

        if etype == "explicit_month":
            month = parsed.get("month")
            if not month or not (1 <= month <= 12):
                return None
            year = parsed.get("year") or today.year
            start = date(year, month, 1)
            end = date(year, month, calendar.monthrange(year, month)[1])
            return {"type": "range", "start_date": start, "end_date": end}

        if etype == "explicit_single":
            d = parsed.get("explicit_date")
            return {"type": "single", "date": _parse_iso_date(d)} if d else None

        if etype == "explicit_range":
            s, e = parsed.get("explicit_start"), parsed.get("explicit_end")
            if not s or not e:
                return None
            start, end = _parse_iso_date(s), _parse_iso_date(e)
            if start > end:
                start, end = end, start
            return {"type": "range", "start_date": start, "end_date": end}

        if etype == "from_explicit_to_today":
            d = parsed.get("explicit_date")
            return {"type": "range", "start_date": _parse_iso_date(d), "end_date": today} if d else None

        # A genuinely date-less query ("my attendance", "show attendance")
        # — the LLM explicitly found no date reference at all, as opposed
        # to a malformed/hallucinated type string below. Defaults to
        # today rather than asking the employee to rephrase, matching
        # punch_details.py's existing behavior for the same kind of query
        # (product decision: standardize on "today" for both flows rather
        # than leaving attendance_node as the odd one out).
        if etype == "unknown":
            return {"type": "single", "date": today}

    except (ValueError, TypeError):
        return None

    return None  # unrecognized/malformed type — genuine extraction failure


# ── Replaces the old _normalize_attendance_dates ──────────────────────────────

def _normalize_attendance_dates(parsed: dict, today: date, week_start: int = 0) -> Optional[dict]:
    """
    Now delegates all date arithmetic to _resolve_date_expression(), which
    is pure Python and deterministic (no LLM math). `parsed` is the LLM's
    symbolic expression, not a pre-computed date/range.
    """
    return _resolve_date_expression(parsed, today, week_start)