"""
services/date_query_resolver.py

Deterministic (non-LLM) date-phrase resolver meant to be SHARED across the
attendance-family intents — punch_details, attendance, attendance_explain
(and, if it ever grows a real deterministic layer, regularisation) — which
today each hand-roll their OWN, separately incomplete date logic. This file
consolidates every date-phrasing bug fixed against those three intents this
session, generalized into one reusable module.

STATUS: standalone / not yet wired into any node. Nothing in
punch_details.py, attendance.py, or attendance_explain.py imports this file
yet — by request, so it can be reviewed on its own before any integration
decision is made. See the bottom of this file for a short note on how each
existing intent's date logic maps onto this module, for when that decision
gets made.

Design — two steps, deliberately kept separate (same shape attendance.py's
own existing deterministic layer already uses successfully, and the same
reason regularisation_node.py hands the LLM a literal day-of-week table
instead of asking it to compute dates itself):

  1. `resolve_query_to_expression(query, today)` -> a symbolic dict
     {"type": ..., ...fields} or None. Pure regex/text matching — no date
     arithmetic beyond counting a literal N ("last N days" -> n=N) or
     locating a weekday/month name. Returns None when nothing here
     confidently recognizes the phrase. A caller with its own LLM
     extraction step should have that LLM target THIS SAME symbolic
     schema, so a deterministic hit and an LLM guess are always
     interchangeable inputs to step 2 below — exactly the pattern
     attendance.py's _resolve_attendance_type_deterministic /
     _build_attendance_date_extraction_prompt pair already established.

  2. `resolve_expression_to_dates(expression, today)` -> the actual answer:
     {"type": "single", "date": date}
     {"type": "range", "start_date": date, "end_date": date}
     or a NoSuchOrdinalWeekday instance (see its own docstring) when the
     expression named a real month/year but asked for an ordinal weekday
     occurrence that month doesn't have (e.g. a 5th Wednesday in a month
     with only 4). This is the ONLY place real date arithmetic happens —
     tested once here, trusted identically whether the expression came
     from step 1 or from an LLM.

Every resolver in this file is a pure function of (query, today) — today is
always passed in explicitly, never read from the system clock — so
behavior is fully reproducible in tests regardless of when they run.
"""

import re
import difflib
from datetime import date, timedelta
from typing import Optional


# ── Shared vocabulary ────────────────────────────────────────────────────────

WEEKDAYS: dict[str, int] = {
    "monday": 0, "tuesday": 1, "wednesday": 2, "thursday": 3,
    "friday": 4, "saturday": 5, "sunday": 6,
}
_WEEKDAY_NAMES = list(WEEKDAYS.keys())
_WEEKDAY_ALTERNATION = "|".join(_WEEKDAY_NAMES)

MONTH_NAMES: dict[str, int] = {
    "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(sorted(MONTH_NAMES.keys(), key=len, reverse=True))

ORDINAL_WEEKDAY_WORDS: dict[str, int] = {
    "first": 1, "1st": 1, "second": 2, "2nd": 2, "third": 3, "3rd": 3,
    "fourth": 4, "4th": 4, "fifth": 5, "5th": 5,
    # Bare numerals ("2 Thursday of August" instead of "2nd Thursday of
    # August") — confirmed live/reported: dropping the "nd"/"rd"/"th"
    # suffix is a common shorthand, and without these entries the ordinal
    # matcher found no match at all, so the query fell all the way through
    # to the bare-weekday matcher, which discarded both the ordinal AND
    # the month and answered the most recent Thursday relative to TODAY
    # instead — "2 Thursday of August" asked on a Thursday silently came
    # back as today's own date.
    "1": 1, "2": 2, "3": 3, "4": 4, "5": 5,
}
_ORDINAL_ALTERNATION = "|".join(sorted(ORDINAL_WEEKDAY_WORDS.keys(), key=len, reverse=True))

# "first month"/"second month"/etc. — an ORDINAL POSITION within a year
# ("first month" = January), a completely different construct from
# ORDINAL_WEEKDAY_WORDS above (an ordinal OCCURRENCE of a weekday within a
# month). Needs its own word list since it goes up to 12, not just 5.
ORDINAL_MONTH_WORDS: dict[str, int] = {
    "first": 1, "1st": 1, "second": 2, "2nd": 2, "third": 3, "3rd": 3, "fourth": 4, "4th": 4,
    "fifth": 5, "5th": 5, "sixth": 6, "6th": 6, "seventh": 7, "7th": 7, "eighth": 8, "8th": 8,
    "ninth": 9, "9th": 9, "tenth": 10, "10th": 10, "eleventh": 11, "11th": 11, "twelfth": 12, "12th": 12,
}
_ORDINAL_MONTH_ALTERNATION = "|".join(sorted(ORDINAL_MONTH_WORDS.keys(), key=len, reverse=True))


# ── Separator normalization ─────────────────────────────────────────────────
#
# Every date pattern below is written against ASCII "-" and "/". Real
# queries do not always arrive that way: mobile keyboards and desktop
# autocorrect turn " - " into an EN DASH, pasted text carries em dashes and
# non-breaking spaces, and some IMEs emit fullwidth forms.
#
# Confirmed live/reported (2026-09-08): "why was i absent or present on
# 10 – 08 – 2026" (en dashes) answered "which date between 01 Jan 2026 and
# 08 Sep 2026 would you like?" — _NUMERIC_DATE_PATTERN never matched, so
# the day and month were dropped entirely and only the trailing "2026"
# survived, via _match_bare_year, as a whole-YEAR range. The date was fully
# specified; one non-ASCII character silently widened it to eight months.
#
# Normalizing once at the dispatcher entry is deliberate: doing it per
# pattern would leave whichever matcher gets added next with the same hole.
#
# NOTE: "." is deliberately NOT normalized to a separator here. "10.08.2026"
# is a real European date format, but treating "." as a date separator also
# matches decimals in ordinary attendance phrasing ("I worked 8.5 hours"
# would parse as the 8th of May), and a wrong date is worse than an
# unrecognized one. That format still falls through to the LLM/bare-year
# path today.
_SEPARATOR_TRANSLATION = str.maketrans({
    "‐": "-",  # hyphen
    "‑": "-",  # non-breaking hyphen
    "‒": "-",  # figure dash
    "–": "-",  # en dash — the one confirmed live
    "—": "-",  # em dash
    "―": "-",  # horizontal bar
    "−": "-",  # minus sign
    "﹘": "-",  # small em dash
    "﹣": "-",  # small hyphen-minus
    "－": "-",  # fullwidth hyphen-minus
    "⁄": "/",  # fraction slash
    "∕": "/",  # division slash
    "／": "/",  # fullwidth solidus
    " ": " ",  # non-breaking space
    " ": " ",  # figure space
    " ": " ",  # thin space
    " ": " ",  # narrow non-breaking space
    "　": " ",  # ideographic space
})


def normalize_separators(query: str) -> str:
    """Maps unicode dash/slash/space look-alikes onto the ASCII characters
    every pattern in this module is written against. Pure text substitution
    — same length, same offsets, no date logic."""
    return query.translate(_SEPARATOR_TRANSLATION)


class NoSuchOrdinalWeekday:
    """The query named a REAL month/year but asked for an nth-occurrence
    weekday that month doesn't have (e.g. "5th Wednesday" in a month that
    only has 4). Distinguished from a plain None ("nothing matched at all")
    so a caller can answer directly ("June 2026 doesn't have a 5th
    Wednesday") instead of silently falling through to some unrelated
    default date — confirmed live bug in punch_details.py before this was
    introduced there: the query fell all the way through to erp-api with
    date=None, which defaults to TODAY, silently answering an unrelated
    day with zero indication the actual question was never resolved."""

    def __init__(self, ordinal_word: str, weekday_name: str, year: int, month: int):
        self.ordinal_word = ordinal_word
        self.weekday_name = weekday_name
        self.year = year
        self.month = month

    def __repr__(self) -> str:
        return f"NoSuchOrdinalWeekday({self.ordinal_word!r}, {self.weekday_name!r}, {self.year}, {self.month})"


class InvalidExplicitDate:
    """The query contains what's clearly an ATTEMPT at an explicit date —
    it matches the numeric DD/MM(/YYYY), ISO YYYY-MM-DD, or day+named-month
    shape — but the numbers don't form a real calendar date: a month over
    12 with a day also over 12 (e.g. "10/45/2026"), a day that doesn't
    exist in that month (e.g. "31/02/2026", "30 feb"), etc. Distinguished
    from a plain None ("no date reference in the query at all") so a
    caller can tell the employee their date looks wrong instead of
    silently treating it as if no date were mentioned — same rationale as
    NoSuchOrdinalWeekday above, a different invalid shape."""

    def __init__(self, matched_text: str):
        self.matched_text = matched_text

    def __repr__(self) -> str:
        return f"InvalidExplicitDate({self.matched_text!r})"


_EMPTY_EXPRESSION_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,
    # "<N> <unit> ago" — n_units is the literal N, unit one of
    # "day"/"week"/"month"/"year". Deliberately NOT folded into n_days/
    # n_months above: those two belong to the forward-anchored "last N
    # days"/"last N months" types, whose resolution is a completely
    # different formula, and a shared field name would make an LLM
    # extraction targeting this schema ambiguous between the two.
    "n_units": None, "unit": None,
    # For "bare_day_of_month" only — the literal day-of-month number named
    # ("5th" -> 5), with no weekday and no month attached. Deliberately its
    # own field rather than reusing n_days (a COUNT elsewhere in this
    # schema, e.g. "last 5 days") or month (which is always a 1-12 MONTH
    # number, never a day) — either reuse would make an LLM extraction
    # targeting this schema genuinely ambiguous about which meaning applies.
    "day": None,
    # For "relative_ago"/"weekday_ago" only, and only when the phrase names
    # TWO units at once ("1 month 3 days ago"). n_units/unit above already
    # carry the FIRST (coarser) component; these carry the second (finer)
    # one, applied as a second offset from the anchor the first produces —
    # see resolve_expression_to_dates' own comment for why chaining beats
    # trying to fold both into one combined unit.
    "n_units2": None, "unit2": None,
}


def _expr(etype: str, **fields) -> dict:
    return {"type": etype, **_EMPTY_EXPRESSION_FIELDS, **fields}


# ── Calendar primitives (each independently pure, no query text involved) ───

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


def nth_weekday_of_month(year: int, month: int, weekday: int, n: int) -> Optional[date]:
    """The Nth (1-5) occurrence of `weekday` in year/month. None if that
    month doesn't have an Nth occurrence — e.g. a 5th Wednesday when the
    month only has 4."""
    first = date(year, month, 1)
    day = 1 + ((weekday - first.weekday()) % 7) + (n - 1) * 7
    if day > last_day_of_month(year, month):
        return None
    return date(year, month, day)


def last_weekday_of_month(year: int, month: int, weekday: int) -> date:
    """The LAST occurrence of `weekday` in year/month — always exists,
    unlike nth_weekday_of_month (every month has a final Monday/Tuesday/
    etc.), so this never returns None."""
    last = date(year, month, last_day_of_month(year, month))
    return last - timedelta(days=(last.weekday() - weekday) % 7)


def count_weekday_occurrences(year: int, month: int, weekday: int) -> int:
    """How many times `weekday` occurs in year/month — always 4 or 5. Used
    to make a NoSuchOrdinalWeekday message concrete ("June 2026 only has 4
    Wednesdays") instead of a bare no."""
    count = 0
    while nth_weekday_of_month(year, month, weekday, count + 1):
        count += 1
    return count


def most_recent_weekday_before(today: date, weekday: int) -> date:
    """"last <weekday>" (bare, no "week" qualifier) — the most recent
    occurrence STRICTLY BEFORE today, RECENCY-based. Deliberately NOT the
    same as calendar_week_weekday(today, weekday, "last") below — "last
    Wednesday" said on a Thursday is yesterday (still this calendar week),
    but "last week Wednesday" is a full 7 days earlier, in the PRIOR
    calendar week. Confirmed live: the two genuinely disagree and a caller
    must pick the right one for the phrasing actually used."""
    delta = (today.weekday() - weekday) % 7
    delta = delta or 7
    return today - timedelta(days=delta)


def week_start_date(today: date, week_start: int = 0) -> date:
    """The date the calendar week CONTAINING `today` begins, for a week
    that starts on `week_start` (Python's own date.weekday() numbering:
    Monday=0 ... Sunday=6). Defaults to Monday (0) — every caller below
    used to hardcode exactly this Monday-anchored computation inline;
    this is the one place that math now lives, so a caller that wants a
    different week-start convention (a company or user configured "weeks
    start on Sunday", "on Tuesday", etc.) has exactly one function to
    call with a different `week_start` instead of six independent
    Monday-shaped formulas to keep in sync.

    The modulo generalizes the old `today - timedelta(days=today.weekday())`
    (which is this formula's week_start=0 case exactly): e.g. week_start=6
    (Sunday) asked on a Monday gives yesterday (today.weekday()=0,
    (0-6)%7=1, today-1); asked ON a Sunday gives today itself
    (today.weekday()=6, (6-6)%7=0)."""
    return today - timedelta(days=(today.weekday() - week_start) % 7)


def calendar_week_weekday(today: date, weekday: int, which: str, week_start: int = 0) -> date:
    """`which` in {"last", "this", "next"} — `weekday` within the calendar
    week (starting on `week_start`, default Monday) that is last/this/next
    RELATIVE TO today's own week, regardless of where in that week today
    itself falls. This is the calendar-anchored sibling of
    most_recent_weekday_before above — use this for "last week Wednesday"/
    "this week Friday"/"next week Monday", NOT for a bare "last Wednesday"/
    "next Monday" (which are recency-based, see most_recent_weekday_before
    / next_weekday_strict — and, unlike this function, never need a
    week_start at all, since they're not anchored to a week boundary in
    the first place).

    Confirmed live bug (attendance.py): "last week Sunday" — and every
    other weekday, not just Sunday — was matching a bare "last week"
    substring check FIRST and returning the WHOLE previous week's range,
    completely discarding which day was actually named."""
    this_week_start = week_start_date(today, week_start)
    if which == "last":
        target_week_start = this_week_start - timedelta(weeks=1)
    elif which == "next":
        target_week_start = this_week_start + timedelta(weeks=1)
    else:
        target_week_start = this_week_start
    # weekday is still Python's own Monday=0..Sunday=6 numbering (that's
    # what the caller names, e.g. "Wednesday" -> 2) — offset it from
    # week_start, not from Monday, so it lands on the right day within a
    # non-Monday-starting week (e.g. week_start=6/Sunday, weekday=2/
    # Wednesday must be 3 days after the Sunday, not 2).
    return target_week_start + timedelta(days=(weekday - week_start) % 7)


def next_weekday_strict(today: date, weekday: int) -> date:
    """"next <weekday>" — nearest occurrence STRICTLY AFTER today. If today
    itself IS that weekday, returns 7 days out, never today."""
    delta = (weekday - today.weekday()) % 7
    delta = delta or 7
    return today + timedelta(days=delta)


def month_before(today: date, months_back: int) -> tuple[int, int]:
    """(year, month) `months_back` calendar months before today's month —
    a single wraparound always suffices since today.month is 1-12 and
    months_back is small (1 or 2 in practice here)."""
    total = (today.year * 12 + (today.month - 1)) - months_back
    year, month0 = divmod(total, 12)
    return year, month0 + 1


def date_before(today: date, n: int, unit: str) -> date:
    """The ANCHOR date `n` days/weeks/months/years before `today` — the one
    place "N <unit> ago" arithmetic lives, for both the plain
    "relative_ago" and the weekday-scoped "weekday_ago" expression types.

    Day/week are plain subtraction. Month/year are CALENDAR steps with the
    day-of-month clamped to the target month's own length, so the result
    is always a real date: "a month ago" asked on the 31st of a month
    whose predecessor has 30 days lands on the 30th, not on a ValueError,
    and "a year ago" asked on Feb 29th of a leap year lands on Feb 28th."""
    if unit == "day":
        return today - timedelta(days=n)
    if unit == "week":
        return today - timedelta(weeks=n)
    if unit == "month":
        year, month = month_before(today, n)
    elif unit == "year":
        year, month = today.year - n, today.month
    else:
        raise ValueError(f"unknown unit {unit!r}")
    return date(year, month, min(today.day, last_day_of_month(year, month)))


# ── Step 1a: simple relative-day phrases ─────────────────────────────────────
# "today"/"yesterday"/"tomorrow", plus "day before "/"day after " prefixed
# (so "day after tomorrow" = +2, "day before yesterday" = -2, "day after
# yesterday" = 0, colloquial for today) — the prefix shifts the bare word's
# own offset by one more in the stated direction.

_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,
)
# "current day" / "previous day" — synonyms for bare "today"/"yesterday",
# not for "day before/after X" (that idiom doesn't apply to either).
# Checked as their own pattern rather than folded into _RELATIVE_DAY_PATTERN
# above, which anchors the "day before/after " prefix immediately onto
# yesterday/tomorrow/today and would otherwise need "current"/"previous"
# threaded through that prefix logic for no reason — neither ever takes a
# before/after prefix in practice.
_CURRENT_DAY_PATTERN = re.compile(r"\bcurrent\s+day\b", re.IGNORECASE)
_PREVIOUS_DAY_PATTERN = re.compile(r"\bprevious\s+day\b", re.IGNORECASE)



def _match_relative_day(query: str) -> Optional[dict]:
    m = _RELATIVE_DAY_PATTERN.search(query)
    if not m:
        if _CURRENT_DAY_PATTERN.search(query):
            return _expr("today")
        if _PREVIOUS_DAY_PATTERN.search(query):
            return _expr("yesterday")
        return None
    prefix, word = m.group(1), m.group(2).lower()
    offset = _RELATIVE_DAY_BASE_OFFSETS[word]
    if prefix:
        offset += _RELATIVE_DAY_PREFIX_DELTAS[prefix.strip().split()[1].lower()]
    if offset == 0:
        return _expr("today")
    if offset == -1:
        return _expr("yesterday")
    if offset == 1:
        return _expr("tomorrow")
    return _expr("single_offset", n_days=offset)


# ── Step 1b: explicit dates ("21/07/2026", "23 aug", "2026-07-21") ─────────
# Day-first is this product's stated convention (the HRMS itself renders
# dd/MM/yyyy), never MM/DD/YYYY, even when both numbers are <=12 and the
# format looks ambiguous.

# Separators tolerate surrounding whitespace ("10 - 08 - 2026", "10/ 08" as
# well as the tight "10-08-2026") — without this, a space around the dash
# broke the match entirely, and the query fell through to whatever weaker
# signal was left in the text (confirmed live/reported: "10 -08 -2026"
# matched nothing here, then got misread by the bare-year matcher as just
# "2026" — the day/month were silently dropped instead of parsed).
_ISO_DATE_PATTERN = re.compile(r"\b(\d{4})\s*-\s*(\d{1,2})\s*-\s*(\d{1,2})\b")
# Year group 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. from "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. Ordering
# matters: \d{4} is tried before the split-year alternative so an ordinary
# "2026" is never mistaken for anything else, and _resolve_numeric_date
# below strips the internal whitespace before checking length.
_NUMERIC_DATE_PATTERN = re.compile(
    r"\b(\d{1,2})\s*[/-]\s*(\d{1,2})(?:\s*[/-]\s*(\d{4}|\d{2}\s+\d{2}|\d{2}))?\b"
)
# "1 Oct 2026", and the app's own display format "01-Oct-2026" (also
# "01/Oct/2026", "1-oct") - employees copy dates back from the cards.
_DAY_THEN_MONTH_PATTERN = re.compile(
    rf"\b(\d{{1,2}})(?:st|nd|rd|th)?(?:\s+|\s*[-/.]\s*)({_MONTH_ALTERNATION})"
    rf"(?:(?:\s+|\s*[-/.]\s*)(\d{{4}}))?\b", re.IGNORECASE,
)
_MONTH_THEN_DAY_PATTERN = re.compile(
    rf"\b({_MONTH_ALTERNATION})\s+(\d{{1,2}})(?:st|nd|rd|th)?(?:,?\s+(\d{{4}}))?\b", re.IGNORECASE,
)


def _resolve_numeric_date(day: int, month: int, year_str: Optional[str], today: date) -> Optional[date]:
    if month > 12:
        if day > 12:
            return None
        day, month = month, day  # forced month-first — the only valid calendar reading
    if not (1 <= month <= 12):
        return None
    # Collapse the split-year whitespace _NUMERIC_DATE_PATTERN'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 here.
    if year_str:
        year_str = "".join(year_str.split())
    year = int(year_str) if year_str else today.year
    if year_str and len(year_str) == 2:
        year += 2000
    try:
        return date(year, month, day)
    except ValueError:
        return None


def _invalid_date_expr(matched_text: str) -> dict:
    return _expr("invalid_explicit_date") | {"_matched_text": matched_text}


def _match_explicit_date(query: str, today: date) -> Optional[dict]:
    m = _ISO_DATE_PATTERN.search(query)
    if m:
        try:
            d = date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
            return _expr("explicit_single", explicit_date=d.isoformat())
        except ValueError:
            return _invalid_date_expr(m.group(0))

    m = _NUMERIC_DATE_PATTERN.search(query)
    if m:
        resolved = _resolve_numeric_date(int(m.group(1)), int(m.group(2)), m.group(3), today)
        if resolved:
            return _expr("explicit_single", explicit_date=resolved.isoformat())
        return _invalid_date_expr(m.group(0))

    m = _DAY_THEN_MONTH_PATTERN.search(query)
    if m:
        day, month_word, year_str = int(m.group(1)), m.group(2).lower(), m.group(3)
        month = MONTH_NAMES.get(month_word)
        if month:
            resolved = _resolve_numeric_date(day, month, year_str, today)
            if resolved:
                return _expr("explicit_single", explicit_date=resolved.isoformat())
            return _invalid_date_expr(m.group(0))

    m = _MONTH_THEN_DAY_PATTERN.search(query)
    if m:
        month_word, day, year_str = m.group(1).lower(), int(m.group(2)), m.group(3)
        month = MONTH_NAMES.get(month_word)
        if month:
            resolved = _resolve_numeric_date(day, month, year_str, today)
            if resolved:
                return _expr("explicit_single", explicit_date=resolved.isoformat())
            return _invalid_date_expr(m.group(0))

    return None


# ── Step 1c: explicit ranges ("from X to Y", "between X and Y") ────────────

_RANGE_CONNECTOR_PATTERN = re.compile(r"\b(?:to|until|till)\b", re.IGNORECASE)
_BETWEEN_PATTERN = re.compile(r"\bbetween\b.*\band\b", re.IGNORECASE)
_TILL_TODAY_PATTERN = re.compile(r"\b(?:till|until|to)\s+today\b", re.IGNORECASE)
# A bare "from <date>" with no end date named at all — "attendance from
# August 20" is a common, natural way to ask for a history starting then
# and running up to now, the same open-ended meaning _TILL_TODAY_PATTERN
# already gives an EXPLICIT "till today"/"until today". Without this, it
# used to fall through to _match_explicit_date below and answer for
# August 20 alone, silently dropping everything since (confirmed/
# reported live).
_FROM_PATTERN = re.compile(r"\bfrom\b", re.IGNORECASE)


def _find_all_explicit_dates(query: str, today: date) -> list[date]:
    found = []
    for pattern, extractor in (
        (_ISO_DATE_PATTERN, lambda m: date(int(m.group(1)), int(m.group(2)), int(m.group(3)))),
        (_DAY_THEN_MONTH_PATTERN, lambda m: _resolve_numeric_date(
            int(m.group(1)), MONTH_NAMES.get(m.group(2).lower(), 0), m.group(3), today)),
        (_MONTH_THEN_DAY_PATTERN, lambda m: _resolve_numeric_date(
            int(m.group(2)), MONTH_NAMES.get(m.group(1).lower(), 0), m.group(3), today)),
        (_NUMERIC_DATE_PATTERN, lambda m: _resolve_numeric_date(
            int(m.group(1)), int(m.group(2)), m.group(3), today)),
    ):
        for m in pattern.finditer(query):
            try:
                d = extractor(m)
            except ValueError:
                d = None
            if d:
                found.append(d)
    # Stable de-dupe, preserving first-seen order (finditer across several
    # patterns can find the same literal date more than once).
    seen = set()
    ordered = []
    for d in found:
        if d not in seen:
            seen.add(d)
            ordered.append(d)
    return ordered


def _match_explicit_range(query: str, today: date) -> Optional[dict]:
    if _TILL_TODAY_PATTERN.search(query):
        dates = _find_all_explicit_dates(query, today)
        if dates:
            return _expr("from_explicit_to_today", explicit_date=dates[0].isoformat())

    if _RANGE_CONNECTOR_PATTERN.search(query) or _BETWEEN_PATTERN.search(query):
        dates = _find_all_explicit_dates(query, today)
        if len(dates) >= 2:
            return _expr(
                "explicit_range",
                explicit_start=dates[0].isoformat(), explicit_end=dates[-1].isoformat(),
            )

    # "from <date>" with no second date/connector at all — open-ended
    # through today. Checked last, and only fires with exactly ONE
    # explicit date, so it never steals a query the two branches above
    # already handle (an explicit "till today", or a genuine "from X to
    # Y" two-date range).
    if _FROM_PATTERN.search(query):
        dates = _find_all_explicit_dates(query, today)
        if len(dates) == 1:
            return _expr("from_explicit_to_today", explicit_date=dates[0].isoformat())

    return None


# ── Step 1c-ter: a range with a bare MONTH on either end ───────────────────
#
# "july to september", "1 july to september", "from july till 15 september",
# "between july and september". _match_explicit_range above needs two FULL
# dates, so these fell to the single-date matcher ("1 july to september" ->
# 1 Jul alone) or the single-month one ("july to september" -> July alone).
# Live: "show my attendance for 1 july to september" answered for 01 Jul.
#
# A bare month means its whole month: the 1st at the start, the last day at
# the end. An end that runs past today stops at today, the way "this month"
# and "this year" do. With no year named the current year is used, and a
# span that wraps ("november to february") starts the year before.
_MONTH_WORD = rf"(?:{_MONTH_ALTERNATION})"
_SPAN_END = rf"(?:(\d{{1,2}})(?:st|nd|rd|th)?\s+)?({_MONTH_WORD})\b(?:\s+(\d{{1,2}})(?:st|nd|rd|th)?\b)?"
_MONTH_SPAN_PATTERN = re.compile(
    rf"\b(?:from\s+|between\s+)?{_SPAN_END}\s*(?:to|till|until|through|thru|-|and)\s*{_SPAN_END}",
    re.IGNORECASE,
)


def _span_day(day_before, day_after) -> Optional[int]:
    for value in (day_before, day_after):
        if value:
            return int(value)
    return None


def _match_month_span(query: str, today: date) -> Optional[dict]:
    m = _MONTH_SPAN_PATTERN.search(query)
    if not m:
        return None
    start_day = _span_day(m.group(1), m.group(3))
    end_day = _span_day(m.group(4), m.group(6))
    if start_day is not None and end_day is not None:
        # Two full dates: _match_explicit_range's.
        return None
    start_month = MONTH_NAMES[m.group(2).lower()]
    end_month = MONTH_NAMES[m.group(5).lower()]
    year_m = _EXPLICIT_YEAR_PATTERN.search(query)
    end_year = int(year_m.group(1)) if year_m else today.year
    start_year = end_year - 1 if start_month > end_month else end_year
    try:
        start = date(start_year, start_month, start_day or 1)
        end = date(end_year, end_month, end_day or last_day_of_month(end_year, end_month))
    except ValueError:
        return None
    if start > end:
        return None
    if start <= today < end:
        end = today
    return _expr("explicit_range", explicit_start=start.isoformat(), explicit_end=end.isoformat())


# "3 months including september", "last 3 months including this month",
# "2 months till august" — N months ENDING at the month named. Live: "show
# me attendance for 3 month including september" matched nothing here, and
# the fallback read it as "the last 3 months", i.e. Jun-Aug, dropping the
# very month the employee asked to include.
_N_MONTHS_ENDING_PATTERN = re.compile(
    rf"\b(\d{{1,2}}|one|two|three|four|five|six|twelve)\s+months?\b[^.?!]{{0,20}}?"
    rf"\b(?:including|incl|till|until|up\s+to|upto|ending(?:\s+(?:in|with))?|through|thru)\s+"
    rf"(?:the\s+)?(this\s+month|current\s+month|{_MONTH_WORD})\b",
    re.IGNORECASE,
)
_COUNT_WORDS = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "twelve": 12}


def _match_n_months_ending(query: str, today: date) -> Optional[dict]:
    m = _N_MONTHS_ENDING_PATTERN.search(query)
    if not m:
        return None
    count_text = m.group(1).lower()
    n = _COUNT_WORDS.get(count_text) or int(count_text)
    if not 1 <= n <= 24:
        return None
    anchor = m.group(2).lower()
    if anchor.endswith("month"):
        end_year, end_month = today.year, today.month
    else:
        end_month = MONTH_NAMES[anchor]
        year_m = _EXPLICIT_YEAR_PATTERN.search(query)
        end_year = int(year_m.group(1)) if year_m else today.year
    month_index = end_year * 12 + (end_month - 1) - (n - 1)
    start = date(month_index // 12, month_index % 12 + 1, 1)
    end = date(end_year, end_month, last_day_of_month(end_year, end_month))
    if start <= today < end:
        end = today
    return _expr("explicit_range", explicit_start=start.isoformat(), explicit_end=end.isoformat())


# Misspelled month names ("septmeber", "agust", "novmber"). Only words of 5+
# letters are considered, against full month names, so short words ("mar",
# "may") and ordinary words stay as they are.
_FULL_MONTH_NAMES = [name for name in MONTH_NAMES if len(name) >= 5]
_MONTH_TYPO_CUTOFF = 0.8
_NOT_A_MONTH_TYPO = frozenset({"number", "member", "remember", "decent", "octave", "junior",
                               "marching", "julie", "augment", "august"})


def fold_month_typos(query: str) -> str:
    def _fix(m):
        word = m.group(0)
        low = word.lower()
        if len(low) < 5 or low in MONTH_NAMES or low in _NOT_A_MONTH_TYPO:
            return word
        best = difflib.get_close_matches(low, _FULL_MONTH_NAMES, n=1, cutoff=_MONTH_TYPO_CUTOFF)
        return best[0] if best else word
    return re.sub(r"[A-Za-z]+", _fix, query or "")


# ── Step 1c-bis: "last N <weekday>s" ("last 2 Tuesdays") — several
# DISCONTIGUOUS occurrences of the same weekday, not a continuous range.
# Checked before the plain "last <weekday>" matcher below so the count
# isn't silently dropped (that matcher's own regex requires "last" to sit
# immediately next to the weekday name — an optional "for "/"on " in
# between, never a number — so there's no direct substring collision, but
# this is still resolved as its own distinct shape rather than one bare
# weekday). Left unhandled before this, "last 2 Tuesdays" matched nothing
# at all (not even _DATE_HINT_PATTERN in punch_details.py, which has no
# equivalent for weekday counts) and fell all the way through to erp-api's
# own default of TODAY — silently answering an unrelated day, and not
# even the right WEEKDAY, with zero indication multiple dates were named.
_LAST_N_WEEKDAYS_PATTERN = re.compile(
    rf"\blast\s+(\d{{1,2}})\s+({_WEEKDAY_ALTERNATION})s?\b", re.IGNORECASE,
)


def _match_last_n_weekdays(query: str) -> Optional[dict]:
    m = _LAST_N_WEEKDAYS_PATTERN.search(query)
    if not m:
        return None
    n = int(m.group(1))
    if n < 1:
        return None
    return _expr("last_n_weekdays", weekday=m.group(2).lower(), n_days=n)


# ── Step 1d: bare weekday, with last/this/next qualifier ────────────────────

_LAST_TO_LAST_WEEKDAY_PATTERN = re.compile(
    rf"\blast\s+to\s+last(?:\s+week)?\s+({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE,
)
_LAST_WEEKDAY_PATTERN = re.compile(
    r"\blast\s+(?:for\s+|on\s+)?(" + _WEEKDAY_ALTERNATION + r")\b", re.IGNORECASE,
)
_THIS_WEEKDAY_PATTERN = re.compile(rf"\b(?:this|current)\s+({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE)
# "next to next <weekday>" — the future mirror of "last to last <weekday>"
# above. Same substring-collision reasoning: it contains a literal "next
# <weekday>" as its trailing two words ("next to next monday" ends in
# "next monday"), so must be checked BEFORE the plain _NEXT_WEEKDAY_PATTERN
# below or that pattern would win on the substring and silently drop the
# "to next" part, answering one week too early.
_NEXT_TO_NEXT_WEEKDAY_PATTERN = re.compile(
    rf"\bnext\s+to\s+next\s+({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE,
)
# "upcoming"/"coming" are accepted synonyms for "next" elsewhere in this
# file (_NEXT_WEEK_PATTERN already covers "upcoming/coming week") but were
# never added here for a bare weekday — "upcoming Monday" fell all the way
# through to _BARE_WEEKDAY_PATTERN below, which is RETROSPECTIVE (most
# recent occurrence, confirmed live/reported: "upcoming Monday" asked on a
# Tuesday came back as YESTERDAY's Monday, not next Monday).
_NEXT_WEEKDAY_PATTERN = re.compile(rf"\b(?:next|upcoming|coming)\s+({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE)
_BARE_WEEKDAY_PATTERN = re.compile(rf"\b({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE)


def _match_bare_weekday(query: str) -> Optional[dict]:
    text = query.lower()

    # "last to last <weekday>" contains a literal "last <weekday>" as its
    # tail — must be checked first or the plain _LAST_WEEKDAY_PATTERN below
    # would win on that substring and silently drop the "to last" part.
    m = _LAST_TO_LAST_WEEKDAY_PATTERN.search(text)
    if m:
        return _expr("weekday", weekday=m.group(1), weeks_ago=2)

    m = _LAST_WEEKDAY_PATTERN.search(text)
    if m:
        return _expr("weekday", weekday=m.group(1), weeks_ago=1)

    m = _THIS_WEEKDAY_PATTERN.search(text)
    if m:
        return _expr("weekday", weekday=m.group(1), weeks_ago=0)

    m = _NEXT_TO_NEXT_WEEKDAY_PATTERN.search(text)
    if m:
        return _expr("next_weekday", weekday=m.group(1), weeks_ago=2)

    m = _NEXT_WEEKDAY_PATTERN.search(text)
    if m:
        return _expr("next_weekday", weekday=m.group(1), weeks_ago=1)

    # Bare weekday with NO qualifier at all ("Friday", not "last Friday",
    # "this Friday", or "next Friday") — its own distinct type, not a reuse
    # of "weekday"/weeks_ago or "this <weekday>"'s weeks_ago=0. Neither
    # existing formula is right here:
    #   - weeks_ago=1 ("last <weekday>") is EXCLUSIVE of today — "last
    #     Friday" asked on a Friday means the PREVIOUS one, confirmed by
    #     its own deliberately-worded regression test.
    #   - weeks_ago=0 ("this <weekday>") searches WITHIN the current
    #     Mon-Sun calendar week without clamping to the past, so it can
    #     land in the FUTURE relative to today (e.g. "this Saturday" asked
    #     on a Friday means tomorrow).
    # A bare mention in a retrospective context ("why was I marked late
    # Friday", asked ON a Friday) needs a third behavior: the most recent
    # occurrence INCLUDING today, but NEVER the future — confirmed by its
    # own separate, deliberately-worded regression test ("attendance is
    # always retrospective ... so both mean the most recent occurrence,
    # including today itself if today IS that weekday").
    m = _BARE_WEEKDAY_PATTERN.search(text)
    if m:
        return _expr("weekday_retrospective", weekday=m.group(1))

    return None


# ── Step 1e: "<last/this/next week> + <weekday>" — calendar-week-anchored,
# NOT the same as the bare weekday forms above ─────────────────────────────

_WEEK_QUALIFIED_WEEKDAY_PATTERN = re.compile(
    rf"\b(last|this|current|next)\s+week\s+({_WEEKDAY_ALTERNATION})\b|"
    rf"\b({_WEEKDAY_ALTERNATION})\s+(last|this|current|next)\s+week\b",
    re.IGNORECASE,
)


def _match_week_qualified_weekday(query: str) -> Optional[dict]:
    m = _WEEK_QUALIFIED_WEEKDAY_PATTERN.search(query)
    if not m:
        return None
    if m.group(1):
        which, weekday_name = m.group(1).lower(), m.group(2).lower()
    else:
        weekday_name, which = m.group(3).lower(), m.group(4).lower()
    which = "this" if which == "current" else which
    return _expr("week_qualified_weekday", weekday=weekday_name, weeks_ago={"last": 1, "this": 0, "next": -1}[which])


# ── Step 1f: "last week to next week" — a 3-calendar-week span ──────────────

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


def _match_last_week_to_next_week(query: str) -> Optional[dict]:
    if _LAST_WEEK_TO_NEXT_WEEK_PATTERN.search(query):
        return _expr("last_week_to_next_week")
    return None


# ── Step 1f-bis: "last/previous month to next month" — a 3-calendar-month
# span, the month mirror of "last week to next week" above. Must be
# checked before _match_bare_week_or_month below, same substring-collision
# reasoning as everywhere else in this file: "previous month to next
# month" contains a literal "previous month" as its head, which
# _LAST_MONTH_PATTERN would otherwise match on its own and return just
# last/previous month alone — silently dropping "to next month" entirely
# (confirmed live/reported: "show previous month to next month attendance"
# was coming back as just last month's data).
_LAST_MONTH_TO_NEXT_MONTH_PATTERN = re.compile(
    r"\b(?:(?:last|previous)\s+month\s+to\s+next\s+month|next\s+month\s+to\s+(?:last|previous)\s+month)\b",
    re.IGNORECASE,
)


def _match_last_month_to_next_month(query: str) -> Optional[dict]:
    if _LAST_MONTH_TO_NEXT_MONTH_PATTERN.search(query):
        return _expr("last_month_to_next_month")
    return None


# ── Step 1g: bare this/last week, this/last month ───────────────────────────

_THIS_WEEK_PATTERN = re.compile(r"\b(?:this|current)\s+week\b", re.IGNORECASE)
_LAST_WEEK_PATTERN = re.compile(r"\blast\s+week\b", re.IGNORECASE)
_THIS_MONTH_PATTERN = re.compile(r"\b(?:this|current)\s+month\b", re.IGNORECASE)
_LAST_MONTH_PATTERN = re.compile(r"\b(?:last|previous)\s+month\b", re.IGNORECASE)
_LAST_TO_LAST_MONTH_PATTERN = re.compile(
    r"\blast[\s-]+to[\s-]+last\s+month\b|\bmonth\s+before\s+last\b", re.IGNORECASE,
)
# "last to last week"/"last-to-last week"/"week before last" — the calendar
# week BEFORE last week. Same substring-collision reasoning as
# _LAST_TO_LAST_MONTH_PATTERN above: this contains a literal "last week" as
# its tail ("last to last week" ends in "last week"), so it must be checked
# BEFORE _LAST_WEEK_PATTERN below or that pattern wins on the substring and
# silently drops the "to last" part, answering LAST week instead of the one
# before it (confirmed live/reported: "last to last week attendance" record
# was coming back as plain last week).
_LAST_TO_LAST_WEEK_PATTERN = re.compile(
    r"\blast[\s-]+to[\s-]+last\s+week\b|\bweek\s+before\s+last\b", re.IGNORECASE,
)
# Bare "next/upcoming/coming week" — NO weekday attached (a weekday
# attached, e.g. "next week Wednesday", is owned by
# _match_week_qualified_weekday, which the dispatcher checks earlier — the
# negative lookahead here is a defensive belt-and-braces guard in case this
# matcher is ever called in isolation). A bare week mention implies the
# WHOLE following Mon-Sun span, the same way bare "last week" already
# means the whole prior week — not a single ambiguous day.
_NEXT_WEEK_PATTERN = re.compile(
    rf"\b(?:next|upcoming|coming)\s+week\b(?!\s+(?:{_WEEKDAY_ALTERNATION}))", re.IGNORECASE,
)


def _match_bare_week_or_month(query: str) -> Optional[dict]:
    # "last to last month" contains "last month" as its trailing two words
    # — must be checked first, same substring-collision reasoning as
    # everywhere else in this file.
    if _LAST_TO_LAST_MONTH_PATTERN.search(query):
        return _expr("last_to_last_month")
    # Same reasoning, one line up: "last to last week" ends in "last week",
    # so it must be checked before _LAST_WEEK_PATTERN too.
    if _LAST_TO_LAST_WEEK_PATTERN.search(query):
        return _expr("last_to_last_week")
    if _THIS_WEEK_PATTERN.search(query):
        return _expr("this_week")
    if _LAST_WEEK_PATTERN.search(query):
        return _expr("last_week")
    if _NEXT_WEEK_PATTERN.search(query):
        return _expr("next_week")
    if _THIS_MONTH_PATTERN.search(query):
        return _expr("this_month")
    if _LAST_MONTH_PATTERN.search(query):
        return _expr("last_month")
    # Bare "next month" — NO ordinal weekday attached ("first Friday of
    # next month" is owned by _match_ordinal_weekday_of_month, checked
    # earlier in the dispatcher and returns before this function is ever
    # reached in that case). Confirmed live: this had no standalone handler
    # at all — only the ordinal-weekday-scoped "next month" qualifier
    # existed — so a bare "next month attendance" fell all the way through
    # to the LLM fallback, which answered the CURRENT month instead.
    # _NEXT_MONTH_PATTERN is defined further down this file (used by the
    # ordinal-weekday resolver); referencing it here is fine since Python
    # resolves module-level names at call time, not definition time.
    if _NEXT_MONTH_PATTERN.search(query):
        return _expr("next_month_bare")
    return None


# ── Step 1h: "last/upcoming/next/coming N days", "last N months" ───────────

_RELATIVE_DAYS_PATTERN = re.compile(r"\blast\s+(\d{1,3})\s+days?\b", re.IGNORECASE)
_UPCOMING_DAYS_PATTERN = re.compile(r"\b(?:upcoming|next|coming)\s+(\d{1,3})\s+days?\b", re.IGNORECASE)
_RELATIVE_MONTHS_PATTERN = re.compile(r"\blast\s+(\d{1,2})\s+months?\b", re.IGNORECASE)


def _match_relative_count(query: str) -> Optional[dict]:
    m = _RELATIVE_DAYS_PATTERN.search(query)
    if m:
        return _expr("relative_days", n_days=int(m.group(1)))

    m = _UPCOMING_DAYS_PATTERN.search(query)
    if m:
        return _expr("upcoming_days", n_days=int(m.group(1)))

    m = _RELATIVE_MONTHS_PATTERN.search(query)
    if m:
        return _expr("relative_months", n_months=int(m.group(1)))

    return None


# ── Step 1h-ter: "<N> <day|week|month|year>s ago/back" ─────────────────
#
# The whole BACKWARD-anchored count family — "one month ago", "2 weeks
# back", "3 days ago", "a year ago". Step 1h above only ever knew the
# FORWARD-anchored spellings ("last N days", "last N months", "upcoming N
# days"), so every "N <unit> ago" phrase matched nothing at all here and
# fell through the whole dispatcher.
#
# That fall-through was not merely a no-answer: confirmed live/reported
# ("what was punch time on Friday one month ago?" asked on Tue 2026-09-08
# came back with Fri 2026-09-04, the MOST RECENT Friday), an unrecognized
# "ago" qualifier sitting next to a weekday name fell all the way to
# _match_bare_weekday, which matched the bare "friday" token on its own and
# silently answered the most recent occurrence — discarding "one month ago"
# entirely with no indication a qualifier had been dropped. Exactly the
# failure _TRUE_ORDINAL_WEEKDAY_GATE_PATTERN already guards for "second
# friday"; this section closes the same hole for the "ago" family, both by
# resolving these phrases properly (below) and by gating the ones it still
# can't parse (see the dispatcher).
#
# A bare "a"/"an" counts as 1 ("a month ago"), and the number may be
# omitted entirely ("month back") — also 1. The unit is required, which is
# what keeps this from matching a bare "last month" (no ago/back suffix)
# and stealing it from _match_bare_week_or_month.
_AGO_NUMBER_WORDS: dict[str, int] = {
    "a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6,
    "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12,
}
_AGO_NUMBER_ALTERNATION = "|".join(sorted(_AGO_NUMBER_WORDS.keys(), key=len, reverse=True))
_AGO_UNITS = ("day", "week", "month", "year")
_AGO_UNIT_ALTERNATION = "|".join(_AGO_UNITS)
# "before"/"earlier"/"prior" are accepted alongside "ago"/"back" — all five
# are the same retrospective suffix in practice ("3 days before", "2 weeks
# prior"). Safe to include "before" here even though it also appears in
# "day before yesterday": _match_relative_day owns that phrasing and is
# checked far earlier in the dispatcher, so it never reaches this pattern.
_AGO_SUFFIX_ALTERNATION = "ago|back|before|earlier|prior"
_RELATIVE_AGO_PATTERN = re.compile(
    rf"\b(?:(\d{{1,3}}|{_AGO_NUMBER_ALTERNATION})\s+)?"
    rf"({_AGO_UNIT_ALTERNATION})s?\s+(?:{_AGO_SUFFIX_ALTERNATION})\b",
    re.IGNORECASE,
)
# Used ONLY as the dispatcher's gate for an "ago" phrase this module could
# not parse into a real count ("friday a few weeks ago", "friday couple of
# months back") — never for resolution. Deliberately narrower than a bare
# \bback\b, which is far too common a word in ordinary attendance phrasing
# ("when did I get back", "back to back leaves") to treat as a date
# qualifier on its own; only a "back" directly following a time unit counts.
_VAGUE_AGO_PATTERN = re.compile(
    rf"\bago\b|\b(?:{_AGO_UNIT_ALTERNATION})s?\s+(?:back|earlier|prior)\b", re.IGNORECASE,
)
_ANY_WEEKDAY_PATTERN = re.compile(rf"\b({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE)
# A VAGUE quantity sitting where the count would be ("a few weeks ago", "a
# couple of months back"). The count in _RELATIVE_AGO_PATTERN is optional
# so that a bare "month back" still means 1, but that same optionality
# would otherwise let these phrases match with the vague word simply
# ignored — "a few weeks ago" silently resolving to exactly ONE week ago,
# which is a confidently wrong answer of precisely the kind this whole
# section exists to prevent. Anchored to the END of the text preceding the
# unit, so it only fires when the vague word is the count position itself.
_VAGUE_QUANTIFIER_PATTERN = re.compile(
    r"\b(?:few|couple|several|some|many|handful|number)\b(?:\s+of)?\s*$", re.IGNORECASE,
)

# Compound form — "1 month 3 days ago", "2 weeks 1 day back". Confirmed
# live/reported: "missing punch 1 month 3 days ago" resolved to the same
# date as bare "3 days ago" — 2026-09-07 instead of the intended
# 2026-08-07. _RELATIVE_AGO_PATTERN's own .search() finds the FIRST
# position in the text where <count><unit><suffix> sit directly adjacent;
# "1 month" isn't followed immediately by the suffix (it's followed by
# "3 days ago"), so that candidate never matches, and the scan continues
# to "3 days ago", which does — the "1 month" component is silently
# dropped with no trace, not even a partial-match warning.
#
# Matched as its OWN pattern (checked first in _match_relative_ago, below)
# rather than trying to make _RELATIVE_AGO_PATTERN itself loop over
# multiple units: two units chained back-to-back, sharing a single
# ago-suffix at the very end, never one each — "1 month ago 3 days ago"
# is a different (and not currently supported) phrasing, not this one.
_COMPOUND_AGO_PATTERN = re.compile(
    rf"\b(?:(\d{{1,3}}|{_AGO_NUMBER_ALTERNATION})\s+)?({_AGO_UNIT_ALTERNATION})s?\s+"
    rf"(?:(\d{{1,3}}|{_AGO_NUMBER_ALTERNATION})\s+)?({_AGO_UNIT_ALTERNATION})s?\s+"
    rf"(?:{_AGO_SUFFIX_ALTERNATION})\b",
    re.IGNORECASE,
)


def _parse_ago_number(token: Optional[str]) -> Optional[int]:
    """Shared by both the single- and compound-unit "ago" matchers — a
    missing token means a bare "a"/"an" was elided (e.g. "month back"),
    which still counts as 1."""
    if token is None:
        return 1
    if token.isdigit():
        return int(token)
    return _AGO_NUMBER_WORDS.get(token)


def _match_relative_ago(query: str) -> Optional[dict]:
    """"one month ago", "2 weeks back", "3 days ago", "1 month 3 days ago"
    — and the same phrases with a weekday named alongside them ("Friday
    one month ago"), which is its own expression type rather than a reuse
    of the plain one: the count(s) fix an ANCHOR date, and the weekday
    then selects a specific day relative to that anchor instead of
    relative to today."""
    text = query.lower()

    # Compound ("1 month 3 days ago") checked FIRST: _RELATIVE_AGO_PATTERN
    # below would otherwise match just its trailing "3 days ago" and
    # silently drop the "1 month" — see _COMPOUND_AGO_PATTERN's own
    # comment for the confirmed live case.
    cm = _COMPOUND_AGO_PATTERN.search(text)
    if cm:
        n1, unit1, n2, unit2 = _parse_ago_number(cm.group(1)), cm.group(2).lower(), \
            _parse_ago_number(cm.group(3)), cm.group(4).lower()
        if n1 is not None and n2 is not None and n1 >= 1 and n2 >= 1 and unit1 != unit2:
            weekday_m = _ANY_WEEKDAY_PATTERN.search(text)
            fields = {"n_units": n1, "unit": unit1, "n_units2": n2, "unit2": unit2}
            if weekday_m:
                return _expr("weekday_ago", weekday=weekday_m.group(1).lower(), **fields)
            return _expr("relative_ago", **fields)

    m = _RELATIVE_AGO_PATTERN.search(text)
    if not m:
        return None

    number_token, unit = m.group(1), m.group(2).lower()
    if number_token is None:
        if _VAGUE_QUANTIFIER_PATTERN.search(text[:m.start()]):
            return None
        n = 1
    elif number_token.isdigit():
        n = int(number_token)
    else:
        n = _AGO_NUMBER_WORDS[number_token]
    if n < 1:
        return None

    weekday_m = _ANY_WEEKDAY_PATTERN.search(text)
    if weekday_m:
        return _expr("weekday_ago", weekday=weekday_m.group(1).lower(), n_units=n, unit=unit)
    return _expr("relative_ago", n_units=n, unit=unit)


# ── Step 1h.5: bare named month, optional year ("attendance for august
# 2025", "june month") — a day-less month reference is a whole-month RANGE,
# distinct from a day+month ("23 aug") which is a single explicit date
# (handled earlier, in _match_explicit_date). Checked only when the ordinal-
# weekday matcher below doesn't already claim the month qualifier (a query
# like "first Friday of August 2025" must resolve to that single Friday,
# not fall in here and answer the whole month instead) — see the dispatcher
# for the ordering that guarantees this.

_MONTH_DAY_NUMBER_PATTERN = re.compile(r"\b\d{1,2}\b")


def _match_explicit_month(query: str) -> Optional[dict]:
    text = query.lower()
    m = _EXPLICIT_MONTH_NAME_PATTERN.search(text)
    if not m:
        return None
    if _MONTH_DAY_NUMBER_PATTERN.search(text):
        # A day number nearby means "23 aug"-style explicit single date,
        # not a whole-month reference — let _match_explicit_date own it.
        return None
    year_m = _EXPLICIT_YEAR_PATTERN.search(text)
    return _expr("explicit_month", month=MONTH_NAMES[m.group(1)], year=int(year_m.group(1)) if year_m else None)


# ── Step 1h-bis: a bare YEAR with no month/day at all ("for 2026", "this
# year", "last year") ───────────────────────────────────────────────────
# Checked AFTER _match_explicit_month above, so "june 2025" is already
# claimed by that matcher (owns the month name) before this ever sees the
# trailing "2025" in isolation. Without this, a bare year fell all the way
# through to the LLM's single-date extraction, which has no way to answer
# "the whole year" and instead invented ONE day for it (confirmed live/
# reported: "what was my punch time for 2026?" silently answered for
# Jan 1st alone) — the same RANGE ambiguity "last month"/"last week"
# already handle correctly is just as real for a bare year.
def _match_bare_year(query: str) -> Optional[dict]:
    text = query.lower()
    if _THIS_YEAR_PATTERN.search(text):
        return _expr("this_year")
    if _LAST_YEAR_PATTERN.search(text):
        return _expr("last_year")
    m = _EXPLICIT_YEAR_PATTERN.search(text)
    if m:
        return _expr("explicit_year", year=int(m.group(1)))
    return None


# ── Step 1h-ter: FINANCIAL year ("financial year"/"fiscal year") — India
# convention, 1 April to 31 March, distinct from the plain calendar-year
# matcher above ("this year"/"2026"). Confirmed live/reported: "first day
# of this financial year attendance" matched nothing at all anywhere in
# this file and fell through to the LLM's single-date guess, which has no
# concept of a financial year and no reliable way to invent 1 April
# itself. "weeks_ago" is reused here purely as a this(0)/last(1) selector
# — the same trick the "weekday" expression type already uses it for —
# rather than adding a whole new field only these three etypes would ever
# read.
_FY_WORD = r"(?:financial|fiscal)\s+year"
_FY_FIRST_DAY_PATTERN = re.compile(
    rf"\bfirst\s+day\s+of\s+(?:the\s+)?(this|current|last|previous)\s+{_FY_WORD}\b", re.IGNORECASE,
)
_FY_LAST_DAY_PATTERN = re.compile(
    rf"\blast\s+day\s+of\s+(?:the\s+)?(this|current|last|previous)\s+{_FY_WORD}\b", re.IGNORECASE,
)
# Bare "this/last financial year" checked LAST, since "first/last day of
# this financial year" contains "this financial year" as its tail —
# same substring-collision reasoning as everywhere else in this file.
_THIS_FY_PATTERN = re.compile(rf"\b(?:this|current)\s+{_FY_WORD}\b", re.IGNORECASE)
_LAST_FY_PATTERN = re.compile(rf"\b(?:last|previous)\s+{_FY_WORD}\b", re.IGNORECASE)


def _match_financial_year(query: str) -> Optional[dict]:
    text = query.lower()

    m = _FY_FIRST_DAY_PATTERN.search(text)
    if m:
        return _expr("financial_year_first_day", weeks_ago=1 if m.group(1) in ("last", "previous") else 0)

    m = _FY_LAST_DAY_PATTERN.search(text)
    if m:
        return _expr("financial_year_last_day", weeks_ago=1 if m.group(1) in ("last", "previous") else 0)

    if _THIS_FY_PATTERN.search(text):
        return _expr("financial_year", weeks_ago=0)
    if _LAST_FY_PATTERN.search(text):
        return _expr("financial_year", weeks_ago=1)

    return None


# ── Step 1i: ordinal weekday of a month ("5th Wednesday of last month",
# "first Friday of January 2025", "second Monday of this month") ──────────
# Requires an ORDINAL word directly before a weekday name AND at least one
# year/month qualifier elsewhere in the query; a bare "second Friday" with
# no scoping is too ambiguous to guess a month for and returns None.

_ORDINAL_WEEKDAY_PATTERN = re.compile(
    rf"\b({_ORDINAL_ALTERNATION}|last)\s+(?:for\s+|on\s+|of\s+)?({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE,
)
# Same shape as _ORDINAL_WEEKDAY_PATTERN but WITHOUT "last" — used only as
# the dispatcher's ambiguity gate (see resolve_query_to_expression), never
# for actual resolution. "last <weekday>" must NOT trip this gate: unlike a
# true ordinal (2nd..5th), it has its own perfectly valid unscoped meaning
# (the most recent occurrence), handled by _match_bare_weekday.
_TRUE_ORDINAL_WEEKDAY_GATE_PATTERN = re.compile(
    rf"\b({_ORDINAL_ALTERNATION})\s+(?:for\s+|on\s+|of\s+)?({_WEEKDAY_ALTERNATION})\b", re.IGNORECASE,
)
_EXPLICIT_YEAR_PATTERN = re.compile(r"\b((?:19|20)\d{2})\b")
_LAST_YEAR_PATTERN = re.compile(r"\b(?:last|previous)\s+year\b", re.IGNORECASE)
_THIS_YEAR_PATTERN = re.compile(r"\b(?:this|current)\s+year\b", re.IGNORECASE)
_EXPLICIT_MONTH_NAME_PATTERN = re.compile(rf"\b({_MONTH_ALTERNATION})\b", re.IGNORECASE)
_ORDINAL_MONTH_PATTERN = re.compile(rf"\b({_ORDINAL_MONTH_ALTERNATION})\s+month\b", re.IGNORECASE)
# "first Friday of next month" — the forward mirror of has_last_month
# below. Deliberately its own qualifier rather than reusing has_last_month
# with a sign flip: "next month" never combines with an explicit year the
# way "last year's last month" does (there's no equivalent "next year's
# next month" idiom in scope here), so it doesn't need that branch's
# has_year_qualifier special-casing at all.
_NEXT_MONTH_PATTERN = re.compile(r"\bnext\s+month\b", re.IGNORECASE)


def _match_ordinal_weekday_of_month(query: str, today: date) -> Optional[dict]:
    text = query.lower()

    ordinal_match = _ORDINAL_WEEKDAY_PATTERN.search(text)
    if not ordinal_match:
        return None
    ordinal_word = ordinal_match.group(1)
    weekday_name = ordinal_match.group(2)

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

    explicit_month = _EXPLICIT_MONTH_NAME_PATTERN.search(text)
    # "first month"/"second month" — ordinal POSITION within a year
    # ("first month" = January), a different construct from the ordinal
    # WEEKDAY occurrence this whole function is otherwise about. Searched
    # independently of ordinal_match above — the two ordinals can both be
    # present in the same query ("last year FIRST MONTH last Friday": the
    # ordinal_match above already claimed "last Friday", this one claims
    # "first month" separately as the month qualifier).
    ordinal_month = _ORDINAL_MONTH_PATTERN.search(text)
    has_last_to_last_month = bool(_LAST_TO_LAST_MONTH_PATTERN.search(text))
    has_last_month = not has_last_to_last_month and bool(_LAST_MONTH_PATTERN.search(text))
    has_this_month = bool(_THIS_MONTH_PATTERN.search(text))
    has_next_month = bool(_NEXT_MONTH_PATTERN.search(text))
    has_month_qualifier = bool(
        explicit_month or ordinal_month or has_last_month or has_last_to_last_month
        or has_this_month or has_next_month
    )

    if not has_year_qualifier and not has_month_qualifier:
        return None

    month_year_delta = 0
    if explicit_month:
        month = MONTH_NAMES[explicit_month.group(1).lower()]
    elif ordinal_month:
        month = ORDINAL_MONTH_WORDS[ordinal_month.group(1).lower()]
    elif has_next_month:
        if today.month == 12:
            month, month_year_delta = 1, 1
        else:
            month = today.month + 1
    elif has_last_to_last_month:
        year_for_2_back, month = month_before(today, 2)
        month_year_delta = year_for_2_back - today.year
    elif has_last_month:
        if has_year_qualifier:
            month = 12
        elif today.month == 1:
            month, month_year_delta = 12, -1
        else:
            month = today.month - 1
    else:  # has_this_month, or year-only query
        month = today.month

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

    return _expr(
        "ordinal_weekday_of_month",
        weekday=weekday_name, month=month, year=year,
        n_days=ORDINAL_WEEKDAY_WORDS.get(ordinal_word, -1) if ordinal_word != "last" else -1,
    ) | {"_ordinal_word": ordinal_word}  # noqa: see note below


# NOTE: Python dicts don't support `|` merge with extra non-expression keys
# cleanly for typing purposes, but functionally this attaches the raw
# ordinal word (needed verbatim for a NoSuchOrdinalWeekday message like
# "doesn't have a Fifth Wednesday") without adding a whole new field to
# every OTHER expression type that will never use it.


# ── Step 1i-bis: bare ordinal day-of-month, no month/weekday attached
# ("5th", "on the 15th") ─────────────────────────────────────────────────
# Confirmed live/reported: "explain my attendance for 5th" had no matcher
# here at all — _match_explicit_date requires a month name right after the
# day, and _match_ordinal_weekday_of_month requires a WEEKDAY right after
# the ordinal, so a bare "5th" on its own matched neither and fell all the
# way through to the caller's own LLM date-extraction prompt. That prompt's
# schema (attendance.py's _build_attendance_date_extraction_prompt) has no
# type for "day-of-month, no month stated" either — no rule, no example —
# so the LLM was left to improvise, and did so inconsistently: the same
# query came back as the 5th of THIS month on one run and, on another,
# with the lone number misread as BOTH day and month ("05-05" -> May 5th),
# an unrelated date with no connection to what was actually asked.
#
# Resolved the same "attendance is always retrospective" way this file
# already resolves a bare weekday (see weekday_retrospective's own
# comment): the most recent occurrence of that day-of-month, INCLUDING
# this month if the day has already occurred, otherwise stepping back to
# last month — never a future date, and never the day-as-month misreading
# above, since there is no month arithmetic left for an LLM to get wrong.
#
# Deliberately narrow — skipped outright (falls through to the LLM path,
# unchanged) when the query also names a weekday or any month
# qualifier (an explicit month name, "first month", "last/this/next
# month"): those combinations ("5th of last month") are already
# unambiguous once the qualifier is read correctly, a different problem
# from the genuinely bare case this section fixes, and folding them in
# here would risk silently overriding a month the user DID specify.
_BARE_ORDINAL_DAY_PATTERN = re.compile(r"\b(\d{1,2})(?:st|nd|rd|th)\b", re.IGNORECASE)

# Spelled-out ordinal day words ("fourth", "twenty-first") — same bare
# day-of-month meaning as "4th"/"21st" above, checked as a fallback when
# the numeric pattern finds nothing. Confirmed live/reported: "explain my
# attendance for fourth" (and its common misspelling "foruth") matched
# nothing here at all and fell through to the caller's own LLM extraction
# with no rule for this shape — the exact same gap _BARE_ORDINAL_DAY_PATTERN
# was added to close for the numeral form, just never extended to the
# spelled-out one.
_ORDINAL_WORD_TO_DAY = {
    "first": 1, "second": 2, "third": 3, "fourth": 4, "fifth": 5,
    "sixth": 6, "seventh": 7, "eighth": 8, "ninth": 9, "tenth": 10,
    "eleventh": 11, "twelfth": 12, "thirteenth": 13, "fourteenth": 14,
    "fifteenth": 15, "sixteenth": 16, "seventeenth": 17, "eighteenth": 18,
    "nineteenth": 19, "twentieth": 20, "thirtieth": 30,
}
_ORDINAL_WORD_PATTERN = re.compile(
    r"\b(" + "|".join(_ORDINAL_WORD_TO_DAY) + r")\b", re.IGNORECASE,
)

# "twenty-first" .. "twenty-ninth" / "thirty-first" — compound words, kept
# separate from the single-word map above: a two-word phrase isn't a good
# candidate for the word-level typo tolerance below (fuzzy-matching it
# against a list of single words is unreliable), and spelled-out days past
# twenty are rare enough in practice that exact matching only is enough.
#
# The ones-part also accepts its NUMERAL ordinal form ("twenty 1st",
# "twenty-1st") alongside the spelled-out word ("twenty-first") — a mixed
# style real users type. A bare cardinal ("twenty one", no ordinal marker
# anywhere) is deliberately NOT accepted here, for the same reason a bare
# "21" isn't accepted by _BARE_ORDINAL_DAY_PATTERN above: with no ordinal
# suffix at all it's indistinguishable from an unrelated count ("twenty one
# employees are absent"), so the existing "only an explicit ordinal counts"
# rule stays consistent for the compound form too.
_COMPOUND_ORDINAL_SUFFIXES = [
    "first", "second", "third", "fourth", "fifth",
    "sixth", "seventh", "eighth", "ninth",
]
_TWENTY_SOMETHING_TO_DAY = {
    suffix: 20 + n for n, suffix in enumerate(_COMPOUND_ORDINAL_SUFFIXES, start=1)
}
_NUMERAL_ORDINAL_ONES_TO_DAY = {
    "1st": 1, "2nd": 2, "3rd": 3, "4th": 4, "5th": 5,
    "6th": 6, "7th": 7, "8th": 8, "9th": 9,
}
_COMPOUND_ORDINAL_PATTERN = re.compile(
    rf"\b(twenty|thirty)[\s-]({'|'.join(_COMPOUND_ORDINAL_SUFFIXES)}|"
    rf"{'|'.join(_NUMERAL_ORDINAL_ONES_TO_DAY)})\b",
    re.IGNORECASE,
)


def _resolve_compound_ordinal_word(tens_word: str, suffix: str) -> Optional[int]:
    tens_word, suffix = tens_word.lower(), suffix.lower()
    ones = _TWENTY_SOMETHING_TO_DAY.get(suffix) or (
        20 + _NUMERAL_ORDINAL_ONES_TO_DAY[suffix]
        if suffix in _NUMERAL_ORDINAL_ONES_TO_DAY else None
    )
    if tens_word == "twenty":
        return ones
    if tens_word == "thirty" and suffix in ("first", "1st"):
        return 31
    return None  # "thirty-second" etc. don't exist — left unresolved


# Same 0.8 cutoff convention already used for typo-tolerant trigger words
# elsewhere in this file (detect_week_start_override) and in
# attendance_explain.py/punch_details.py's today/yesterday/tomorrow and
# leave_action_service.py's weekday names — verified against the whole
# ordinal-word list plus a broad sample of ordinary query vocabulary
# (attendance/explain/status/punch/reason/...) with zero false-positive
# collisions at this cutoff. 4+ letters, not 5+: the ordinal vocabulary's
# shortest correct spelling is "first"/"tenth" (5), but a single DELETED
# letter — a common typo shape — drops that to 4 (e.g. "fith" for "fifth"),
# and shorter words are still too close to several ordinal words by pure
# character overlap to be a useful match at any cutoff.
_ORDINAL_WORD_TYPO_CUTOFF = 0.8
_CANDIDATE_WORD_PATTERN = re.compile(r"\b[a-z]{4,}\b", re.IGNORECASE)


def _match_ordinal_day_word(text: str) -> Optional[int]:
    """Returns the day-of-month a spelled-out ordinal word names ("fourth"
    -> 4), tolerating a common single-word misspelling ("foruth" -> 4) via
    difflib, or None if nothing in `text` resolves. Compound words
    ("twenty-first") are handled by the caller BEFORE this runs — see
    _match_bare_ordinal_day_of_month, whose plain numeral pattern would
    otherwise steal the "1st" out of "twenty 1st" as if "twenty" weren't
    there at all."""
    exact = _ORDINAL_WORD_PATTERN.search(text)
    if exact:
        return _ORDINAL_WORD_TO_DAY[exact.group(1).lower()]

    for word in _CANDIDATE_WORD_PATTERN.findall(text):
        close = difflib.get_close_matches(
            word, _ORDINAL_WORD_TO_DAY.keys(), n=1, cutoff=_ORDINAL_WORD_TYPO_CUTOFF,
        )
        if close:
            return _ORDINAL_WORD_TO_DAY[close[0]]

    return None


def _match_bare_ordinal_day_of_month(query: str) -> Optional[dict]:
    text = query.lower()

    # Checked BEFORE the plain numeral pattern below — "twenty 1st"/
    # "twenty-first" contain "1st"/"first" as a substring, which
    # _BARE_ORDINAL_DAY_PATTERN would otherwise match on its own, silently
    # discarding the "twenty"/"thirty" tens part (confirmed while testing
    # this fix: "twenty 1st" was resolving to the 1st of the month instead
    # of the 21st).
    compound = _COMPOUND_ORDINAL_PATTERN.search(text)
    if compound:
        day = _resolve_compound_ordinal_word(compound.group(1), compound.group(2))
    else:
        m = _BARE_ORDINAL_DAY_PATTERN.search(text)
        day = int(m.group(1)) if m else _match_ordinal_day_word(text)

    if not day or not (1 <= day <= 31):
        return None

    if _ANY_WEEKDAY_PATTERN.search(text):
        return None
    if (
        _EXPLICIT_MONTH_NAME_PATTERN.search(text)
        or _ORDINAL_MONTH_PATTERN.search(text)
        or _LAST_MONTH_PATTERN.search(text)
        or _THIS_MONTH_PATTERN.search(text)
        or _NEXT_MONTH_PATTERN.search(text)
    ):
        return None

    return _expr("bare_day_of_month", day=day)


# ── Step 1: top-level dispatcher ─────────────────────────────────────────────
# Order matters — more specific/compound phrasings are checked before the
# simpler patterns they contain as substrings. Do not reorder without
# re-verifying every "confirmed live" comment above that depends on it.

def resolve_query_to_expression(query: str, today: date) -> Optional[dict]:
    """Classifies `query` into a symbolic expression dict — see the module
    docstring for the full contract. Returns None when nothing here
    confidently recognizes the phrase; callers fall back to their own LLM
    extraction, targeting this same schema."""
    # Before ANY matcher runs — see normalize_separators for the live case
    # a single en dash caused.
    query = normalize_separators(query)
    # "septmeber" -> "september", so every month matcher below sees it.
    query = fold_month_typos(query)

    explicit_range = _match_explicit_range(query, today)
    if explicit_range:
        return explicit_range

    # Before the single-date and single-month matchers, which would otherwise
    # claim just one end of "1 july to september" / "july to september".
    month_span = _match_month_span(query, today) or _match_n_months_ending(query, today)
    if month_span:
        return month_span

    explicit_date = _match_explicit_date(query, today)
    if explicit_date:
        return explicit_date

    relative_day = _match_relative_day(query)
    if relative_day:
        return relative_day

    ordinal_weekday = _match_ordinal_weekday_of_month(query, today)
    if ordinal_weekday:
        return ordinal_weekday

    # A TRUE ordinal word (2nd..5th — deliberately NOT bare "last", which
    # has its own valid, correct unscoped meaning via _match_bare_weekday
    # below: "last Friday" alone means the most recent one) adjacent to a
    # weekday, with no year/month scope found above, is genuinely
    # ambiguous and must not fall through to the bare-weekday matcher —
    # confirmed by testing this file directly: without this gate, "what
    # about second friday" fell through past _match_ordinal_weekday_of_
    # month's correct None into _match_bare_weekday, which matched the
    # bare "friday" token and silently answered the MOST RECENT Friday —
    # quietly dropping "second" and answering a different question than
    # what was asked, never surfacing that the reference was ambiguous.
    if _TRUE_ORDINAL_WEEKDAY_GATE_PATTERN.search(query.lower()):
        return None

    # "<N> <unit> ago/back" — checked AFTER the ordinal gate above (so
    # "first friday one month ago" stays ambiguous rather than being
    # claimed here with the "first" silently dropped) but BEFORE every
    # matcher below, above all _match_bare_weekday: the bare-weekday
    # matcher would otherwise win on the "friday" token alone and discard
    # the "one month ago" qualifier entirely. See the section's own
    # comment for the confirmed live case.
    relative_ago = _match_relative_ago(query)
    if relative_ago:
        return relative_ago

    last_n_weekdays = _match_last_n_weekdays(query)
    if last_n_weekdays:
        return last_n_weekdays

    # "last to last week <weekday>"/"next to next week <weekday>" each
    # contain a literal "last week <weekday>"/"next week <weekday>" as
    # their tail, which _match_week_qualified_weekday's own pattern below
    # would otherwise match first on that substring — silently dropping
    # the "to last"/"to next" part and answering one week too early/late
    # (confirmed live/reported alongside the bare "last to last week" bug
    # above: "last to last week monday" was coming back as plain last
    # week's Monday). Must be checked first, same reasoning as every other
    # "X to X <unit>" collision in this file.
    last_to_last_weekday = _LAST_TO_LAST_WEEKDAY_PATTERN.search(query.lower())
    if last_to_last_weekday:
        return _expr("weekday", weekday=last_to_last_weekday.group(1), weeks_ago=2)

    next_to_next_weekday = _NEXT_TO_NEXT_WEEKDAY_PATTERN.search(query.lower())
    if next_to_next_weekday:
        return _expr("next_weekday", weekday=next_to_next_weekday.group(1), weeks_ago=2)

    week_qualified = _match_week_qualified_weekday(query)
    if week_qualified:
        return week_qualified

    last_week_to_next_week = _match_last_week_to_next_week(query)
    if last_week_to_next_week:
        return last_week_to_next_week

    last_month_to_next_month = _match_last_month_to_next_month(query)
    if last_month_to_next_month:
        return last_month_to_next_month

    relative_count = _match_relative_count(query)
    if relative_count:
        return relative_count

    bare_week_or_month = _match_bare_week_or_month(query)
    if bare_week_or_month:
        return bare_week_or_month

    # Checked AFTER the ordinal-weekday gate above (so "first Friday of
    # August 2025" resolves to that single Friday, not the whole month)
    # but BEFORE the bare-weekday matcher below (a month name never
    # collides with a weekday name, so order relative to that one doesn't
    # matter, but keeping month-scale matches ahead of day-scale ones
    # reads correctly top-to-bottom).
    explicit_month = _match_explicit_month(query)
    if explicit_month:
        return explicit_month

    bare_year = _match_bare_year(query)
    if bare_year:
        return bare_year

    financial_year = _match_financial_year(query)
    if financial_year:
        return financial_year

    # A retrospective "ago"/"<unit> back" qualifier is present next to a
    # weekday name, but _match_relative_ago above could not parse a real
    # count out of it ("friday a few weeks ago", "friday couple of months
    # back") — so the qualifier is still unconsumed. Falling through to
    # _match_bare_weekday here would answer the MOST RECENT occurrence of
    # that weekday, silently discarding the qualifier: exactly the
    # confirmed live bug this whole section exists to fix, just with a
    # vaguer count than "one". Return None instead so the caller's own LLM
    # fallback gets the query — the same choice
    # _TRUE_ORDINAL_WEEKDAY_GATE_PATTERN above already makes for an
    # unscoped "second friday", and for the same reason: no answer beats
    # a confidently wrong one.
    if _VAGUE_AGO_PATTERN.search(query) and _ANY_WEEKDAY_PATTERN.search(query):
        return None

    bare_weekday = _match_bare_weekday(query)
    if bare_weekday:
        return bare_weekday

    # Checked LAST — after every weekday/week/month/year shape above has
    # had a chance to claim the query, so this only ever fires for a
    # genuinely bare ordinal day-of-month ("5th") with nothing else
    # attached to it. See this matcher's own comment for the live bug it
    # fixes.
    bare_ordinal_day = _match_bare_ordinal_day_of_month(query)
    if bare_ordinal_day:
        return bare_ordinal_day

    return None


# ── Step 2: expression -> real dates ─────────────────────────────────────────

def _parse_iso(value: str) -> date:
    return date(*(int(p) for p in value.split("-")))


def resolve_expression_to_dates(expression: Optional[dict], today: date, week_start: int = 0):
    """Turns a symbolic expression (from step 1, OR an LLM extraction
    targeting the same schema) into real dates. Returns:
      {"type": "single", "date": date}
      {"type": "range", "start_date": date, "end_date": date}
      a NoSuchOrdinalWeekday instance
      None — unresolvable / malformed expression.

    week_start: which day a calendar week begins on (Python's own
    date.weekday() numbering — Monday=0 ... Sunday=6, the default).
    Only affects the WEEK-BOUNDARY-anchored branches below (this_week/
    last_week/next_week/last_week_to_next_week ranges, week_qualified_
    weekday, and bare "this <weekday>") — the RECENCY-based branches
    (weekday/weeks_ago>=1, next_weekday, weekday_retrospective) are
    unaffected on purpose: "last Friday"/"next Monday"/a bare "Friday"
    with no qualifier mean the nearest occurrence by plain day-counting,
    never anchored to a week boundary in the first place, so there is
    nothing for week_start to change there."""
    if not isinstance(expression, dict):
        return None

    etype = expression.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 = expression.get("n_days")
            return {"type": "single", "date": today + timedelta(days=n)} if n is not None else None

        if etype == "explicit_single":
            d = expression.get("explicit_date")
            return {"type": "single", "date": _parse_iso(d)} if d else None
        if etype == "invalid_explicit_date":
            return InvalidExplicitDate(expression.get("_matched_text", ""))
        if etype == "explicit_range":
            s, e = expression.get("explicit_start"), expression.get("explicit_end")
            if not s or not e:
                return None
            start, end = _parse_iso(s), _parse_iso(e)
            if start > end:
                start, end = end, start
            return {"type": "range", "start_date": start, "end_date": end}
        if etype == "from_explicit_to_today":
            d = expression.get("explicit_date")
            return {"type": "range", "start_date": _parse_iso(d), "end_date": today} if d else None

        if etype == "weekday":
            weekday = WEEKDAYS.get(expression.get("weekday"))
            weeks_ago = expression.get("weeks_ago") or 0
            if weekday is None:
                return None
            if weeks_ago == 0:
                # "this <weekday>" — within the CURRENT calendar week (per
                # week_start), so this is the one branch of "weekday" that
                # does depend on week_start, unlike the weeks_ago>=1
                # (recency-based, below) branch.
                this_week_start = week_start_date(today, week_start)
                return {"type": "single", "date": this_week_start + timedelta(days=(weekday - week_start) % 7)}
            most_recent = most_recent_weekday_before(today, weekday)
            return {"type": "single", "date": most_recent - timedelta(weeks=weeks_ago - 1)}
        if etype == "last_n_weekdays":
            weekday = WEEKDAYS.get(expression.get("weekday"))
            n = expression.get("n_days")
            if weekday is None or not n or n < 1:
                return None
            most_recent = most_recent_weekday_before(today, weekday)
            dates = [most_recent - timedelta(weeks=i) for i in range(n)]
            dates.reverse()  # oldest first — reads naturally as "which of these"
            if len(dates) == 1:
                return {"type": "single", "date": dates[0]}
            return {"type": "multiple", "dates": dates}
        if etype == "next_weekday":
            weekday = WEEKDAYS.get(expression.get("weekday"))
            if weekday is None:
                return None
            # weeks_ago here counts how many "next"s are stacked (1 for a
            # bare "next Monday", 2 for "next to next Monday") — reusing
            # the same field name the "weekday"/past-side type uses for
            # its own stacked-qualifier count, just applied forward.
            weeks_ahead = expression.get("weeks_ago") or 1
            return {
                "type": "single",
                "date": next_weekday_strict(today, weekday) + timedelta(weeks=weeks_ahead - 1),
            }
        if etype == "weekday_retrospective":
            weekday = WEEKDAYS.get(expression.get("weekday"))
            if weekday is None:
                return None
            # Modulo, WITHOUT the "or 7" override "weekday"/weeks_ago=1 uses
            # — always 0-6, so today itself is included when it matches,
            # but never goes negative/future the way weeks_ago=0's "this
            # <weekday>" formula can. See _match_bare_weekday's own comment
            # for why this needs to be its own distinct formula.
            delta = (today.weekday() - weekday) % 7
            return {"type": "single", "date": today - timedelta(days=delta)}
        if etype == "bare_day_of_month":
            day = expression.get("day")
            if not day or not (1 <= day <= 31):
                return None
            # Retrospective, same convention as weekday_retrospective just
            # above: if that day-of-month has already occurred THIS month,
            # use this month; otherwise it can only mean last month (never
            # a future date — attendance is always about a day that's
            # already happened). Clamped to the target month's own length
            # for a day that doesn't exist there (e.g. "31st" asked in a
            # 30-day month falls back to last month's 31st, not a
            # ValueError).
            if day <= today.day:
                year, month = today.year, today.month
            else:
                year, month = month_before(today, 1)
            clamped_day = min(day, last_day_of_month(year, month))
            return {"type": "single", "date": date(year, month, clamped_day)}
        if etype == "week_qualified_weekday":
            weekday = WEEKDAYS.get(expression.get("weekday"))
            weeks_ago = expression.get("weeks_ago") or 0
            if weekday is None:
                return None
            which = {1: "last", 0: "this", -1: "next"}.get(weeks_ago, "this")
            return {"type": "single", "date": calendar_week_weekday(today, weekday, which, week_start)}

        if etype in ("relative_ago", "weekday_ago"):
            n, unit = expression.get("n_units"), expression.get("unit")
            if not n or n < 1 or unit not in ("day", "week", "month", "year"):
                return None
            anchor = date_before(today, n, unit)

            # Compound form ("1 month 3 days ago") — chain a SECOND offset
            # from the first anchor. See _COMPOUND_AGO_PATTERN's own
            # comment for the confirmed live bug (the month component was
            # silently dropped entirely before this existed).
            n2, unit2 = expression.get("n_units2"), expression.get("unit2")
            is_compound = bool(n2 and n2 >= 1 and unit2 in ("day", "week", "month", "year"))
            if is_compound:
                anchor = date_before(anchor, n2, unit2)

            if etype == "weekday_ago":
                weekday = WEEKDAYS.get(expression.get("weekday"))
                if weekday is None:
                    return None
                # Most recent occurrence of that weekday ON OR BEFORE the
                # anchor — the same formula "weekday_retrospective" uses
                # for a bare weekday, just applied at the anchor instead
                # of at today. Inclusive of the anchor itself (so "Friday
                # a week ago" asked on a Friday IS that Friday) and never
                # later than it, which is what keeps "Friday one month
                # ago" inside the intended month rather than drifting
                # forward toward today.
                return {"type": "single", "date": anchor - timedelta(days=(anchor.weekday() - weekday) % 7)}

            # A compound anchor ("1 month 3 days ago") always names one
            # exact day, never a whole-unit range — unlike the single-unit
            # case just below, there's no ambiguity left for a second unit
            # to resolve.
            if is_compound:
                return {"type": "single", "date": anchor}

            # No weekday named — the phrase refers to the whole calendar
            # week/month/year the anchor falls in, NOT to the anchor day
            # alone. That keeps "1 <unit> ago" exactly equivalent to the
            # already-established "last <unit>" types above (1 week ago ==
            # last_week, 1 month ago == last_month, 1 year ago ==
            # last_year), and it means a single-day-only caller such as
            # punch_details gets a RANGE it can ask about rather than a
            # silently-picked day out of ~30. "N days ago" is the one unit
            # that is genuinely a single day, and stays one.
            if unit == "day":
                return {"type": "single", "date": anchor}
            if unit == "week":
                start = week_start_date(anchor, week_start)
                return {"type": "range", "start_date": start, "end_date": start + timedelta(days=6)}
            if unit == "month":
                return {
                    "type": "range",
                    "start_date": date(anchor.year, anchor.month, 1),
                    "end_date": date(anchor.year, anchor.month, last_day_of_month(anchor.year, anchor.month)),
                }
            return {
                "type": "range",
                "start_date": date(anchor.year, 1, 1),
                "end_date": date(anchor.year, 12, 31),
            }

        if etype == "relative_days":
            n = expression.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 = expression.get("n_days")
            if not n or n < 1:
                return None
            return {"type": "range", "start_date": today + timedelta(days=1), "end_date": today + timedelta(days=n)}

        if etype == "this_week":
            this_week_start = week_start_date(today, week_start)
            return {"type": "range", "start_date": this_week_start, "end_date": today}
        if etype == "last_week":
            this_week_start = week_start_date(today, week_start)
            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 == "last_to_last_week":
            this_week_start = week_start_date(today, week_start)
            start = this_week_start - timedelta(weeks=2)
            return {"type": "range", "start_date": start, "end_date": start + timedelta(days=6)}
        if etype == "next_week":
            this_week_start = week_start_date(today, week_start)
            next_week_start = this_week_start + timedelta(weeks=1)
            return {"type": "range", "start_date": next_week_start, "end_date": next_week_start + timedelta(days=6)}
        if etype == "last_week_to_next_week":
            this_week_start = week_start_date(today, week_start)
            start = this_week_start - timedelta(weeks=1)
            end = this_week_start + timedelta(weeks=1) + timedelta(days=6)
            return {"type": "range", "start_date": start, "end_date": end}

        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 = first_of_this_month - timedelta(days=1)
            return {"type": "range", "start_date": last_day_prev.replace(day=1), "end_date": last_day_prev}
        if etype == "next_month_bare":
            year = today.year + 1 if today.month == 12 else today.year
            month = 1 if today.month == 12 else today.month + 1
            start = date(year, month, 1)
            end = date(year, month, last_day_of_month(year, month))
            return {"type": "range", "start_date": start, "end_date": end}
        if etype == "last_month_to_next_month":
            first_of_this_month = today.replace(day=1)
            last_day_prev = first_of_this_month - timedelta(days=1)
            start = last_day_prev.replace(day=1)
            next_year = today.year + 1 if today.month == 12 else today.year
            next_month = 1 if today.month == 12 else today.month + 1
            end = date(next_year, next_month, last_day_of_month(next_year, next_month))
            return {"type": "range", "start_date": start, "end_date": end}
        if etype == "last_to_last_month":
            year, month = month_before(today, 2)
            start = date(year, month, 1)
            end = date(year, month, last_day_of_month(year, month))
            return {"type": "range", "start_date": start, "end_date": end}
        if etype == "relative_months":
            n = expression.get("n_months")
            if not n or n < 1:
                return None
            first_of_this_month = today.replace(day=1)
            last_day_prev = first_of_this_month - timedelta(days=1)
            year, month = month_before(today, n)
            return {"type": "range", "start_date": date(year, month, 1), "end_date": last_day_prev}

        if etype == "ordinal_weekday_of_month":
            weekday = WEEKDAYS.get(expression.get("weekday"))
            month, year = expression.get("month"), expression.get("year")
            ordinal_word = expression.get("_ordinal_word", "")
            if weekday is None or not month or not year:
                return None
            if ordinal_word == "last":
                return {"type": "single", "date": last_weekday_of_month(year, month, weekday)}
            n = ORDINAL_WEEKDAY_WORDS.get(ordinal_word)
            if not n:
                return None
            target = nth_weekday_of_month(year, month, weekday, n)
            if target:
                return {"type": "single", "date": target}
            return NoSuchOrdinalWeekday(ordinal_word, expression.get("weekday"), year, month)

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

        if etype == "this_year":
            return {"type": "range", "start_date": date(today.year, 1, 1), "end_date": today}
        if etype == "last_year":
            last_year = today.year - 1
            return {"type": "range", "start_date": date(last_year, 1, 1), "end_date": date(last_year, 12, 31)}
        if etype == "explicit_year":
            year = expression.get("year")
            if not year:
                return None
            # Clamp to today for the CURRENT year (same convention as
            # this_month/this_week) rather than running to Dec 31st of a
            # year that hasn't finished yet.
            end = today if year == today.year else date(year, 12, 31)
            return {"type": "range", "start_date": date(year, 1, 1), "end_date": end}

        if etype in ("financial_year", "financial_year_first_day", "financial_year_last_day"):
            # India convention: 1 April - 31 March. weeks_ago is reused
            # purely as a this(0)/last(1) selector here.
            weeks_ago = expression.get("weeks_ago") or 0
            current_fy_start_year = today.year if today.month >= 4 else today.year - 1
            fy_start_year = current_fy_start_year - weeks_ago
            fy_start = date(fy_start_year, 4, 1)
            fy_end = date(fy_start_year + 1, 3, 31)

            if etype == "financial_year_first_day":
                return {"type": "single", "date": fy_start}
            if etype == "financial_year_last_day":
                return {"type": "single", "date": fy_end}
            # etype == "financial_year": clamp the CURRENT financial year's
            # end to today (same convention as this_year/this_month) —
            # only relevant when weeks_ago == 0, since a past financial
            # year's end date is already behind today regardless.
            end = min(fy_end, today) if weeks_ago == 0 else fy_end
            return {"type": "range", "start_date": fy_start, "end_date": end}

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

    except (ValueError, TypeError, KeyError):
        return None

    return None


# ── Inline "week starts on <weekday>" override ──────────────────────────────
#
# An employee can name their own calendar week's first day right in the
# query itself ("attendance for last week starting Sunday", "last week,
# week start Monday") rather than relying on whatever default this module
# (or a caller) assumes. Confirmed live/reported: "last week" always
# resolved Mon-Sun regardless of what the employee said their week starts
# on, because nothing anywhere ever detected this phrasing or threaded a
# non-default week_start through — every caller left resolve()'s week_start
# at its default (0/Monday).
# The trigger word is captured loosely (any word token) rather than baked
# into the regex as "start(s|ing)?" directly, so a misspelling of it
# ("strat", "satrt") can still be caught below via the same difflib
# typo-tolerance methodology already used elsewhere in this codebase for
# common trigger-word misspellings (attendance_explain.py/punch_details.py's
# today/yesterday/tomorrow, leave_action_service.py's weekday names) —
# confirmed live/reported: "last week strat from wednesday" (transposed
# "start") silently found no override and fell back to Monday.
_WEEK_START_OVERRIDE_PATTERN = re.compile(
    rf"\b(?:week\s+)?([a-z]+)\s+(?:from\s+|on\s+|with\s+)?({_WEEKDAY_ALTERNATION})\b",
    re.IGNORECASE,
)
_WEEK_START_TRIGGER_WORDS = ["start", "starts", "starting"]
_WEEK_START_TRIGGER_TYPO_CUTOFF = 0.8


def detect_week_start_override(query: str) -> Optional[int]:
    """Returns the WEEKDAYS index the query names as its week's first day
    ("starting Sunday", "week start Monday", "start from Sunday", or a
    misspelling of "start" close enough per difflib), or None if it names
    none. resolve() below calls this automatically so every existing
    caller gets the override for free without having to detect or thread
    it through themselves."""
    for m in _WEEK_START_OVERRIDE_PATTERN.finditer(query):
        trigger = m.group(1).lower()
        if trigger in _WEEK_START_TRIGGER_WORDS or difflib.get_close_matches(
            trigger, _WEEK_START_TRIGGER_WORDS, n=1, cutoff=_WEEK_START_TRIGGER_TYPO_CUTOFF,
        ):
            return WEEKDAYS[m.group(2).lower()]
    return None


# ── One-call convenience wrapper ─────────────────────────────────────────────

def resolve(query: str, today: date, week_start: Optional[int] = None):
    """resolve_query_to_expression + resolve_expression_to_dates in one
    call, for a caller that has no LLM fallback of its own and just wants
    "the best deterministic answer, or None".

    week_start: which day a calendar week begins on (Monday=0 ... Sunday=6,
    etc.) for "last week"/"this week"/"next week"/"last week <weekday>".
    Left as None (the normal case), it's auto-detected from the query text
    itself via detect_week_start_override — e.g. "last week starting
    Sunday" — falling back to Monday (0) when the query names no such
    override. Pass an explicit int only to force a specific day regardless
    of query text (e.g. a company- or user-configured default), which
    always wins over auto-detection."""
    if week_start is None:
        week_start = detect_week_start_override(query)
        if week_start is None:
            week_start = 0
    return resolve_expression_to_dates(resolve_query_to_expression(query, today), today, week_start)


# ─────────────────────────────────────────────────────────────────────────────
# Integration notes (not wired up yet — for whenever that decision is made)
#
# punch_details.py:        single-day only. Would drop its own duplicate
#                           _resolve_year_month_weekday / _resolve_relative_
#                           day_offset / _resolve_week_qualified_weekday and
#                           call resolve() directly, checking isinstance(...,
#                           NoSuchOrdinalWeekday) before falling to its LLM
#                           date-extraction prompt (unchanged).
#
# attendance.py:            needs BOTH steps kept separate, since it must
#                           hand step 1's schema to its LLM prompt as the
#                           fallback path (_build_attendance_date_extraction_
#                           prompt already targets an equivalent, though not
#                           identical, schema — would need reconciling field
#                           names, e.g. attendance.py's "single_offset" vs this
#                           file's field spelling, before a straight swap).
#
# attendance_explain.py:    has its own separate ordinal-weekday resolver
#                           (_resolve_year_month_weekday, duplicated logic,
#                           same shape as this file's _match_ordinal_weekday_
#                           of_month) — most direct candidate to just delete
#                           and call into this module instead.
#
# regularisation_node.py:   different design entirely (hands the LLM a
#                           literal day-of-week lookup table rather than
#                           doing deterministic pre-resolution) — lower
#                           priority / different integration shape, not a
#                           simple swap.
# ─────────────────────────────────────────────────────────────────────────────


# ─────────────────────────────────────────────────────────────────────────────
# A DAY TYPED WITH A LETTER FOR A DIGIT - "3o sept", "sept 3o", "o3 oct",
# "for 2o", "1l oct" ("o"/"O" for 0, "l"/"I" for 1).
#
# Never guessed: classify_node asks "did you mean 03 Sep 2026 or 30 Sep
# 2026?" and, on the answer, re-reads the ORIGINAL message with the chosen
# date in it - so whichever flow was running (or being started) carries on
# as if the date had been typed right. Live (Oct 14): "sept 3o" became 30 Sep,
# "for 2o" became 30 Sep, and "o3 oct" 3 Oct, each without a word.
# ─────────────────────────────────────────────────────────────────────────────

_TYPO_MONTHS = r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?"
_TYPO_TOKEN = r"(?:\d[oOlI]|[oOlI]\d)"
_TYPO_DAY_RE = re.compile(
    rf"\b(?P<a>{_TYPO_MONTHS}\s*{_TYPO_TOKEN})\b"
    rf"|\b(?P<b>{_TYPO_TOKEN}(?:st|nd|rd|th)?\s+(?:of\s+)?{_TYPO_MONTHS})"
    rf"|(?:^\s*|\b(?:for|on|of|dated?)\s+)(?P<c>{_TYPO_TOKEN}(?:st|nd|rd|th)?)(?=\s*[.!?]*\s*$)",
    re.IGNORECASE)
_TYPO_MONTH_NUMBER = {m: i for i, m in enumerate(
    ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"), 1)}
_TYPO_MONTH_ABBR = {v: k.title() for k, v in _TYPO_MONTH_NUMBER.items()}


class TypoDay:
    """What was typed, the dates it could mean (ISO), where it sits in the
    message, and whether a month was named next to it."""

    def __init__(self, typed, options, start, end, month_named):
        self.typed, self.options = typed, options
        self.start, self.end, self.month_named = start, end, month_named


def find_typo_day(text: str, today: date):
    """The first day typed with a letter in it, as a TypoDay, or None. A
    reading that is not a real date ("3o feb" -> 30 Feb) is dropped; a year
    typed right after it is used, else this year. With no month named, the
    current month."""
    m = _TYPO_DAY_RE.search(text or "")
    if not m:
        return None
    group = "a" if m.group("a") else ("b" if m.group("b") else "c")
    span_text = m.group(group)
    token = re.search(_TYPO_TOKEN, span_text).group(0)
    month_word = re.search(_TYPO_MONTHS, span_text, re.IGNORECASE) if group != "c" else None
    month = _TYPO_MONTH_NUMBER.get(month_word.group(0).lower()[:3]) if month_word else today.month
    if token[0].isdigit():
        digit, letter = int(token[0]), token[1].lower()
        days = [digit, digit * 10 + (0 if letter == "o" else 1)]
    else:
        digit, letter = int(token[1]), token[0].lower()
        days = [digit] if letter == "o" else [10 + digit]
    start, end = m.start(group), m.end(group)
    year_m = re.match(r"\s*,?\s*(\d{4})\b", (text or "")[end:])
    year = int(year_m.group(1)) if year_m else today.year
    if year_m:
        end += year_m.end()
    options = []
    for day in dict.fromkeys(days):
        try:
            options.append(date(year, month, day).isoformat())
        except ValueError:
            continue
    if not options:
        return None
    return TypoDay(span_text.strip(" .!?"), options, start, end, bool(month_word))


_ORDINAL_PICK = {"first": 0, "1st": 0, "second": 1, "2nd": 1, "former": 0, "latter": 1}


def pick_typo_option(reply: str, options: list, today: date):
    """The ISO date a reply to "did you mean X or Y?" chooses, or None when
    the reply is not an answer to it. A full date is taken as given (the
    employee may name a third date); a bare day number, "the second one", or
    "yes" (with one option) picks from the options."""
    text = (reply or "").strip().lower().strip(" .!?")
    if not text or find_typo_day(text, today):
        return None
    # "the second one" first: resolve() reads "second" as the 2nd of the month.
    pick = re.fullmatch(r"(?:the\s+)?(first|1st|second|2nd|former|latter)(?:\s+(?:one|date|option))?",
                        text)
    if pick:
        index = _ORDINAL_PICK[pick.group(1)]
        return options[index] if index < len(options) else None
    resolved = resolve(text, today)
    if isinstance(resolved, dict) and resolved.get("type") == "single" and resolved.get("date"):
        return resolved["date"].isoformat()
    day = re.fullmatch(r"(?:the\s+)?(\d{1,2})(?:st|nd|rd|th)?", text)
    if day:
        hits = [o for o in options if int(o[8:10]) == int(day.group(1))]
        return hits[0] if len(hits) == 1 else None
    if len(options) == 1 and re.fullmatch(
            r"(?:yes|yeah|yep|yup|ok|okay|correct|right|sure|haan|ha)(?:\s+(?:it\s+is|that'?s\s+right|please))?",
            text):
        return options[0]
    return None


def apply_typo_choice(original: str, typo: "TypoDay", chosen_iso: str) -> str:
    """`original` with the mistyped date replaced by the chosen one, written
    out in full ("30 Sep 2026") so every flow's own date reading agrees."""
    chosen = date.fromisoformat(chosen_iso)
    written = f"{chosen.day} {_TYPO_MONTH_ABBR[chosen.month]} {chosen.year}"
    return f"{original[:typo.start]}{written}{original[typo.end:]}"
