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 langgraph.types import StreamWriter
import logging
from langgraph.graph import END
import services.leave_slot_service as leave_slot_service

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

    INTENT_MODEL,

)
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) -> None:
    entries = [{"date": date_iso}] if date_iso else []
    seed = {"entries": entries}
    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."""
    seed = {"entries": [{"date": date_iso}]}
    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 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()

        parsed = _resolve_attendance_type_deterministic(query, today)
        if parsed is not None:
            logger.info(
                "[Graph] Attendance date resolved deterministically: query=%r -> type=%s",
                query[:80], parsed.get("type"),
            )
        else:
            try:
                prompt = _build_attendance_date_extraction_prompt(
                    query,
                    today,
                )

                raw = await _call_llm(
                    prompt,
                    max_tokens=200,
                    model=INTENT_MODEL,
                )

                parsed = _safe_json_parse(
                    _extract_text(raw)
                )

                usage = (
                    _normalize_usage(raw.get("usage"))
                    if isinstance(raw, dict)
                    else None
                )

                if usage:
                    usage_events.append({
                        "source": "attendance_date_extraction",
                        "usage": usage,
                    })

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

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

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

        target_employee = parsed.get("employee_name")

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

        if not _is_authorized_for_target(
            current_user_name,
            current_user_role,
            target_employee,
        ):
            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",
            )

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

        query_params = _normalize_attendance_dates(
            parsed,
            today,
        )

        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'?"
            )

        wants_reg = _wants_regularization(query)

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

            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,
                )

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

            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,
                )

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

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

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

        msg = _format_long_range_summary(
            start_date,
            end_date,
            summary,
        )

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

        return _finish(
            msg,
            intent="attendance_summary",
            extra_data={
                **summary,
                "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":
        msg = f"No attendance record was found for {date_str} ({day_name})."
    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_authorized_for_target(current_name: Optional[str], current_role,
                               target_employee: Optional[str]) -> 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 from the JWT.
    """
    if not target_employee:
        return True

    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.
    if any(r is not None and str(r).strip().lower() in PRIVILEGED_ROLES for r in roles):
        return True

    return _names_match(current_name, target_employee)


# ── 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 | 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
  "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)
}}

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.
- "last N months" -> type "relative_months", n_months=N. Do NOT map this onto "last_month" —
  that type is ONLY for the literal, uncounted phrase "last month".
- "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.

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 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}}
"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)
_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)

# 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.
_ATTENDANCE_EXPLICIT_NUMERIC_DATE_RE = re.compile(
    r"(?<!\d{4}-)\b(\d{1,2})[/-](\d{1,2})(?:[/-](\d{2,4}))?\b"
)
_ATTENDANCE_DAY_THEN_MONTH_RE = re.compile(
    rf"\b(\d{{1,2}})(?:st|nd|rd|th)?\s+({_MONTH_ALTERNATION})\b(?:\s+(?:of\s+)?(\d{{2,4}}))?",
    re.IGNORECASE,
)
_ATTENDANCE_MONTH_THEN_DAY_RE = re.compile(
    rf"\b({_MONTH_ALTERNATION})\s+(\d{{1,2}})(?:st|nd|rd|th)?\b(?:\s*,?\s*(\d{{2,4}}))?",
    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:
        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_attendance_type_deterministic(query: str, today: date) -> Optional[dict]:
    """Classifies the query into the same symbolic {"type": ...} shape the
    LLM extraction (_build_attendance_date_extraction_prompt) produces —
    consumed identically by _resolve_date_expression() either way, so
    matching an equivalent type/weekday/weeks_ago here is provably the
    same downstream result the LLM would have produced, just without the
    risk of it guessing wrong. Returns None (defer to the LLM) for
    anything not confidently recognized."""
    if _looks_like_named_employee_query(query):
        return None

    # An explicit RANGE ("1 july to 15 july", "12/07/2026 to 20/07/2026",
    # "between 1 july and 15 july", "21 July till today") is checked
    # BEFORE any single-date shortcut below — otherwise the first date
    # alone gets matched as a standalone explicit_single and the rest of
    # the range is silently dropped (observed bug: "1 july to 15 july"
    # collapsed to just 1 July).
    range_resolved = _resolve_explicit_range_deterministic(query, today)
    if range_resolved:
        return range_resolved

    # An explicit numeric date (DD/MM or DD/MM/YYYY) is checked early since
    # it's a closed, unambiguous shape that can't collide with any of the
    # weaker heuristics below (none of them involve a '/' or '-').
    m = _ATTENDANCE_EXPLICIT_NUMERIC_DATE_RE.search(query)
    if m:
        resolved = _resolve_explicit_date_symbolic(int(m.group(1)), int(m.group(2)), m.group(3), today)
        if resolved:
            return resolved

    # Checked FIRST, before this_week/last_week below: "last to last week
    # <weekday>" contains a literal "last week" substring, which would
    # otherwise match _ATTENDANCE_LAST_WEEK_RE and silently produce the
    # wrong type (a plain last-week range instead of one specific day two
    # weeks back). If the weekday name is misspelled ("mondey") and this
    # compound doesn't fully resolve, bail out to the LLM entirely rather
    # than falling through into that wrong simpler match — confirmed live:
    # "mondey last to last week" was resolving to "last_week" here before
    # this reordering.
    if _ATTENDANCE_LAST_TO_LAST_RE.search(query):
        m = _ATTENDANCE_LAST_TO_LAST_WEEKDAY_RE.search(query)
        if m:
            return {"type": "weekday", **{**_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "weekday": m.group(1).lower(), "weeks_ago": 2}}
        return None

    relative_day_offset = _resolve_relative_day_offset(query)
    if relative_day_offset is not None:
        if relative_day_offset == 0:
            return {"type": "today", **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS}
        if relative_day_offset == -1:
            return {"type": "yesterday", **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS}
        if relative_day_offset == 1:
            return {"type": "tomorrow", **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS}
        return {"type": "single_offset", **{**_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "n_days": relative_day_offset}}

    if _ATTENDANCE_THIS_WEEK_RE.search(query):
        return {"type": "this_week", **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS}
    if _ATTENDANCE_LAST_WEEK_RE.search(query):
        return {"type": "last_week", **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS}
    if _ATTENDANCE_THIS_MONTH_RE.search(query):
        return {"type": "this_month", **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS}
    if _ATTENDANCE_LAST_MONTH_RE.search(query):
        return {"type": "last_month", **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS}

    # Bare named month ("june month", "attendance for august") with no day
    # number nearby — a day number means an explicit single date instead
    # ("21 july 2026", "23 aug"), resolved deterministically just below
    # rather than being misread as "all of July".
    m = _ATTENDANCE_MONTH_ANCHORED_RE.search(query)
    if m and not _ATTENDANCE_DAY_NUMBER_RE.search(query):
        month_word = next(g for g in m.groups() if g)
        year_m = _ATTENDANCE_EXPLICIT_YEAR_RE.search(query)
        return {"type": "explicit_month", **{
            **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS,
            "month": _MONTH_NAMES[month_word.lower()],
            "year": int(year_m.group(1)) if year_m else None,
        }}

    # Day + named month ("23 aug", "12 August", "aug 23") — same closed,
    # unambiguous shape as the numeric case above, just spelled out. A
    # year-less one uses the current year (see _resolve_explicit_date_
    # symbolic) instead of the query silently defaulting to today.
    resolved = _resolve_explicit_date_deterministic(query, today)
    if resolved:
        return resolved

    m = _ATTENDANCE_RELATIVE_DAYS_RE.search(query)
    if m:
        return {"type": "relative_days", **{**_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "n_days": int(m.group(1))}}

    # "last N months" — checked before the plain _ATTENDANCE_LAST_MONTH_RE
    # match above would have already skipped this (that pattern requires
    # "month" immediately after "last", so "last 2 months" never matches
    # it), but without this case the query fell through to the LLM with no
    # symbolic type to represent "last N months" at all — the schema only
    # had "last_month" (uncounted) and "relative_days" (days, not months) —
    # so it silently collapsed to a single previous-month lookup instead of
    # an N-month range (observed bug: "last 2 months" showed just last
    # month's data, and never reached the long-range summary because a
    # single month's span is under ATTENDANCE_MAX_INLINE_RANGE_DAYS).
    m = _ATTENDANCE_RELATIVE_MONTHS_RE.search(query)
    if m:
        return {"type": "relative_months", **{**_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "n_months": int(m.group(1))}}

    m = _ATTENDANCE_NEXT_WEEKDAY_RE.search(query)
    if m:
        return {"type": "next_weekday", **{**_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "weekday": m.group(1).lower()}}

    m = _ATTENDANCE_THIS_WEEKDAY_RE.search(query)
    if m:
        return {"type": "weekday", **{**_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "weekday": m.group(1).lower(), "weeks_ago": 0}}

    m = _ATTENDANCE_LAST_WEEKDAY_RE.search(query)
    if m:
        return {"type": "weekday", **{**_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "weekday": m.group(1).lower(), "weeks_ago": 1}}

    # Bare weekday name with no last/this/next qualifier — attendance is
    # always retrospective, so (matching _resolve_weekday's own weeks_ago=1
    # semantics above) this resolves to the most recent occurrence.
    m = _ATTENDANCE_BARE_WEEKDAY_RE.search(query)
    if m:
        return {"type": "weekday", **{**_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS, "weekday": m.group(1).lower(), "weeks_ago": 1}}

    # Nothing above matched AND the query contains no date-like vocabulary
    # at all (no digit, weekday, month, or "week"/"month"/"year"/today-ish
    # word) — a genuinely date-less query like "my attendance"/"show my
    # attendance". Confidently "unknown" rather than deferring to the LLM
    # for something this file can already tell has no date reference in
    # it; _resolve_date_expression's "unknown" branch defaults this to
    # today (see its own comment for the product decision behind that).
    if not _ATTENDANCE_ANY_DATE_SIGNAL_RE.search(query):
        return {"type": "unknown", **_ATTENDANCE_SYMBOLIC_EMPTY_FIELDS}

    return None


def _resolve_date_expression(parsed: dict, today: date) -> 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).
    """
    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 == "this_week":
            monday = today - timedelta(days=today.weekday())
            return {"type": "range", "start_date": monday, "end_date": today}

        if etype == "last_week":
            this_monday = today - timedelta(days=today.weekday())
            last_monday = this_monday - timedelta(weeks=1)
            last_sunday = last_monday + timedelta(days=6)
            return {"type": "range", "start_date": last_monday, "end_date": last_sunday}

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