"""
Deterministic (non-LLM) resolution of relative date phrases and explicit
duration counts for the apply-leave conversation flow.

Pure functions only — every public function takes `today: date` explicitly
(never reads the system clock itself) so behavior is fully reproducible in
tests and reusable anywhere a reference date is available. Callers are
responsible for computing `today` in the app's configured timezone (see
hr_graph._today_in_app_timezone) rather than passing a naive, server-local
date.today() — a leave request evaluated near midnight could otherwise
silently disagree with what day it actually is for the company.

Nothing here ever guesses: resolve_relative_date_phrase() and
extract_duration_days() both return None when the query doesn't match a
recognized pattern, and callers must treat None as "fall through to the
existing LLM extraction unchanged" — this module is additive, never a
replacement for the LLM's own handling of absolute dates ("12th November"),
leave type, reason, session type, etc.
"""

import re
from datetime import date, timedelta
from typing import Callable, Optional, TypedDict

_WEEKDAYS: dict[str, int] = {
    "monday": 0, "tuesday": 1, "wednesday": 2, "thursday": 3,
    "friday": 4, "saturday": 5, "sunday": 6,
}

_MONTHS: dict[str, int] = {
    "january": 1, "february": 2, "march": 3, "april": 4, "may": 5, "june": 6,
    "july": 7, "august": 8, "september": 9, "october": 10, "november": 11, "december": 12,
}

_MONTH_ORDINALS: dict[str, int] = {"first": 1, "second": 2, "third": 3, "fourth": 4}

_WD = r"(monday|tuesday|wednesday|thursday|friday|saturday|sunday)"

_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,
}

# "a month" is inherently ambiguous (28-31 days depending on the anchor
# month) and no calendar-month-aware library is installed. A fixed 30-day
# approximation is used deliberately — simple, deterministic, auditable.
# If a live complaint surfaces about a specific 28/31-day mismatch, this is
# the one line to revisit (e.g. compose with first_of_next_month() for a
# real calendar-month jump instead).
_APPROX_DAYS_PER_MONTH = 30


class ResolvedDate(TypedDict):
    from_date: str        # YYYY-MM-DD
    matched_phrase: str    # the substring that matched, for logging
    matched_kind: str      # internal pattern key, for logging/debugging


# ── Pure date-math primitives (each independently unit-tested) ────────────

def this_coming_weekday(anchor: date, target_weekday: int) -> date:
    """'this Monday' / 'this coming Monday' / 'coming Monday' / 'upcoming
    Monday' — nearest occurrence ON OR AFTER anchor, INCLUSIVE of anchor
    itself. If anchor already IS target_weekday, returns anchor."""
    return anchor + timedelta(days=(target_weekday - anchor.weekday()) % 7)


def next_weekday_strict(anchor: date, target_weekday: int) -> date:
    """'next Monday' — nearest occurrence STRICTLY AFTER anchor. If anchor
    already IS target_weekday, returns anchor + 7 (never anchor itself) —
    this is the deliberate disambiguation from this_coming_weekday() for
    that exact edge case."""
    days_ahead = (target_weekday - anchor.weekday()) % 7
    if days_ahead == 0:
        days_ahead = 7
    return anchor + timedelta(days=days_ahead)


def weekday_of_next_calendar_week(anchor: date, target_weekday: int) -> date:
    """'next week Wednesday' / 'upcoming week Wednesday' / 'coming week
    Wednesday' — the given weekday within the Mon-Sun calendar week
    immediately following anchor's own current week. Live bug: this used
    to be aliased to next_weekday_strict() (treated as identical to bare
    'next Wednesday'), which is only correct when anchor is itself near
    the start of its week — from a Monday, "next week Thursday" and "next
    Thursday" both happen to land 3 days out, so the equivalence looked
    right in that one case and was even asserted by a test — but from any
    other weekday it diverges: asked on a Monday for "next week Thursday,"
    a user means the Thursday roughly 9-13 days out (the FOLLOWING
    calendar week), not the Thursday 3 days away that's still within the
    current week. This function always anchors to next week's Monday
    first, so it never lands inside anchor's own current week regardless
    of which day anchor is.

    Live bug #2: the triggering _PATTERNS regex originally only recognized
    literal "next week <weekday>" — "upcoming week friday" fell through to
    tier 2, which (with no field to represent "weekday within a NAMED
    week" at all) collapsed it to plain "upcoming Friday" and silently
    returned THIS week's Friday instead. "upcoming"/"coming" are already
    treated as synonyms for "next" everywhere else in this module (see
    this_coming_weekday, _BARE_NEXT_WEEK_PATTERN) — the trigger regex now
    matches all three here too."""
    monday_this_week = anchor - timedelta(days=anchor.weekday())
    monday_next_week = monday_this_week + timedelta(weeks=1)
    return monday_next_week + timedelta(days=target_weekday)


def next_to_next_weekday(anchor: date, target_weekday: int) -> date:
    """'next to next Monday' / 'next to next Friday' — one full week after
    next_weekday_strict()."""
    return next_weekday_strict(anchor, target_weekday) + timedelta(days=7)


def week_after_next(anchor: date) -> date:
    """Bare 'week after next' (no weekday given) — Monday of
    (current ISO week + 2)."""
    monday_this_week = anchor - timedelta(days=anchor.weekday())
    return monday_this_week + timedelta(weeks=2)


def first_of_next_month(anchor: date) -> date:
    """Bare 'next month' (no day given) — the 1st of the month following
    anchor's month, with December -> January year rollover."""
    if anchor.month == 12:
        return date(anchor.year + 1, 1, 1)
    return date(anchor.year, anchor.month + 1, 1)


def first_weekday_of_next_month(anchor: date, target_weekday: int) -> date:
    """'first Monday of next month' — this_coming_weekday() re-anchored to
    next month's 1st instead of today. If the 1st itself is target_weekday,
    returns the 1st."""
    return this_coming_weekday(first_of_next_month(anchor), target_weekday)


def nth_weekday_of_next_month(anchor: date, target_weekday: int, n: int) -> Optional[date]:
    """'second Friday of next month' / 'next month's third Wednesday' — the
    Nth (1-4) occurrence of target_weekday in the month following anchor's
    month. Generalizes first_weekday_of_next_month (n=1 only, and computed
    differently) to match nth_weekday_of_month's ordinal support. None if
    that month doesn't have an Nth occurrence (e.g. a 5th Friday)."""
    next_month = first_of_next_month(anchor)
    return nth_weekday_of_month(next_month.year, next_month.month, target_weekday, n)


def last_weekday_of_next_month(anchor: date, target_weekday: int) -> date:
    """'last Friday of next month' — the LAST occurrence of target_weekday
    in the month following anchor's month."""
    next_month = first_of_next_month(anchor)
    return last_weekday_of_month(next_month.year, next_month.month, target_weekday)


# ── Named-month anchoring ("first Wednesday of October", "October next
# Saturday") — a DIFFERENT construct from "first Monday of NEXT month" above:
# the month is named explicitly, not relative to today, and the year has to
# be inferred (this year, unless that month has already fully passed). ─────

def _year_for_month(today: date, month: int) -> int:
    """Named months with no year given always mean the NEXT occurrence of
    that month — this year if it hasn't fully passed yet, otherwise next
    year. ('this fully passed' uses month, not day, as the cutoff: naming a
    month that's still the current month resolves within it, even if a
    specific day-of-month ends up before today — the per-date past-date
    guard in resolve_relative_date_phrase/resolve_date_range_phrase is what
    actually rejects a genuinely past result, not this year inference.)"""
    return today.year if month >= today.month else today.year + 1


def nth_weekday_of_month(year: int, month: int, target_weekday: int, n: int) -> Optional[date]:
    """The Nth (1-4) occurrence of target_weekday within year/month. None if
    that month doesn't have an Nth occurrence (e.g. a 5th Friday)."""
    first = date(year, month, 1)
    first_occurrence = first + timedelta(days=(target_weekday - first.weekday()) % 7)
    result = first_occurrence + timedelta(weeks=n - 1)
    return result if result.month == month else None


def last_weekday_of_month(year: int, month: int, target_weekday: int) -> date:
    """The LAST occurrence of target_weekday within year/month."""
    next_month_first = date(year + 1, 1, 1) if month == 12 else date(year, month + 1, 1)
    last_day = next_month_first - timedelta(days=1)
    return last_day - timedelta(days=(last_day.weekday() - target_weekday) % 7)


def weekday_in_named_month(
    today: date, month: int, target_weekday: int, ordinal: str,
    after: Optional[date] = None,
) -> Optional[date]:
    """Resolves '<ordinal> <weekday> of <Month>' / '<Month> <ordinal>
    <weekday>' for an explicitly-named month (not "next month" — see
    first_weekday_of_next_month for that).

    ordinal: "first"/"second"/"third"/"fourth"/"last"/"next".
    - first..fourth / last: the Nth (or last) occurrence of that weekday
      within the named month, in the nearest year that hasn't already
      passed (see _year_for_month). None if that ordinal doesn't exist in
      the month (e.g. a 5th Friday).
    - "next": if `after` is given (this is the SECOND date in a two-sided
      range — see resolve_date_range_phrase), the nearest occurrence of
      that weekday STRICTLY AFTER `after` — e.g. "October next Saturday"
      following an already-resolved "first Wednesday of October" means the
      Saturday right after that Wednesday, not the first Saturday of the
      whole month (which could be earlier and produce a backwards range).
      If `after` is None (a standalone, non-range mention), the nearest
      occurrence on/after max(today, 1st of the named month), still within
      that month — rolling to next year's occurrence of the month if the
      named month has no such day left (e.g. asked in its last week)."""
    if ordinal == "last":
        year = _year_for_month(today, month)
        return last_weekday_of_month(year, month, target_weekday)
    if ordinal in _MONTH_ORDINALS:
        year = _year_for_month(today, month)
        return nth_weekday_of_month(year, month, target_weekday, _MONTH_ORDINALS[ordinal])
    if ordinal == "next":
        if after is not None:
            return next_weekday_strict(after, target_weekday)
        year = _year_for_month(today, month)
        month_start = date(year, month, 1)
        anchor = month_start if month_start > today else today
        candidate = this_coming_weekday(anchor, target_weekday)
        if candidate.month == month and candidate.year == year:
            return candidate
        # No occurrence left in the named month this cycle — try next year's.
        next_year = year + 1
        return this_coming_weekday(date(next_year, month, 1), target_weekday)
    return None


_MONTH_NAME_GROUP = "(" + "|".join(_MONTHS) + ")"
_ORDINAL_GROUP = "(first|second|third|fourth|last|next)"

_MONTH_ANCHORED_PATTERN = re.compile(
    rf"\b(?:{_ORDINAL_GROUP}\s+{_WD}\s+(?:of|in)\s+{_MONTH_NAME_GROUP}"
    rf"|{_MONTH_NAME_GROUP}(?:'s)?\s+{_ORDINAL_GROUP}\s+{_WD})\b",
    re.I,
)


def _parse_month_anchored_match(m: re.Match) -> tuple[str, int, int]:
    """Returns (ordinal, target_weekday, month) from either capture-group
    order the pattern above can match."""
    g = m.groups()
    if g[0] is not None:  # "<ordinal> <weekday> of/in <Month>"
        ordinal, weekday_name, month_name = g[0], g[1], g[2]
    else:  # "<Month> <ordinal> <weekday>"
        month_name, ordinal, weekday_name = g[3], g[4], g[5]
    return ordinal.lower(), _WEEKDAYS[weekday_name.lower()], _MONTHS[month_name.lower()]


def resolve_date_range_phrase(
    query: str, today: date,
) -> Optional[tuple[ResolvedDate, Optional[ResolvedDate]]]:
    """Finds named-month-anchored expressions ("first Wednesday of
    October", "October next Saturday") in `query`, in the order they
    appear. Returns None if none are found — callers fall through exactly
    as resolve_relative_date_phrase's callers do.

    - Exactly one match: returns (that ResolvedDate, None) — a single
      anchor, same shape as resolve_relative_date_phrase's single-date
      result, for callers that only need a from_date.
    - Two or more matches: uses the FIRST TWO as (from, to) — this is a
      genuine two-sided RANGE, and takes precedence over any other
      resolution for BOTH endpoints, since two explicit named-month
      anchors is the most precise signal the user can give. If the second
      match's ordinal is "next", it resolves relative to the FIRST match's
      date (see weekday_in_named_month) rather than to today, so e.g.
      "October first Wednesday to October next Saturday" produces a
      forward-moving 4-day range instead of an inverted one.

    A resolved date before `today` is dropped (returns None for that slot,
    or None overall for a single match) — never silently hands back a past
    date, same guard as resolve_relative_date_phrase."""
    matches = list(_MONTH_ANCHORED_PATTERN.finditer(query))
    if not matches:
        return None

    def _resolve(m: re.Match, after: Optional[date]) -> Optional[date]:
        ordinal, weekday, month = _parse_month_anchored_match(m)
        return weekday_in_named_month(today, month, weekday, ordinal, after=after)

    first_date = _resolve(matches[0], after=None)
    if first_date is None or first_date < today:
        return None
    first_resolved: ResolvedDate = {
        "from_date": first_date.isoformat(), "matched_phrase": matches[0].group(0),
        "matched_kind": "month_anchored_weekday",
    }

    if len(matches) < 2:
        return first_resolved, None

    second_date = _resolve(matches[1], after=first_date)
    if second_date is None or second_date < first_date:
        return first_resolved, None
    second_resolved: ResolvedDate = {
        "from_date": second_date.isoformat(), "matched_phrase": matches[1].group(0),
        "matched_kind": "month_anchored_weekday",
    }
    return first_resolved, second_resolved


# ── Week-of-month ("first week of November", "November's last week") — a
# DIFFERENT construct again: a "week" mention already implies BOTH
# endpoints on its own (no separate from/to phrase needed, unlike the
# weekday-anchored range above). Live bug: "apply leave from november first
# week to end of the first week" — the trailing "to end of the first week"
# is the user re-stating the same week's own end date, not a second anchor.

def _last_day_of_month(year: int, month: int) -> int:
    """The day-of-month number of the last day of year/month (28-31)."""
    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 week_of_month(today: date, month: int, ordinal: str) -> Optional[tuple[date, date]]:
    """Resolves '<ordinal> week of <Month>' to a literal (from_date, to_date)
    7-day span counted from the 1st of the month — days 1-7 are the first
    week, 8-14 the second, etc. — NOT an ISO/Mon-Sun calendar week. This is
    the simplest, most predictable reading and matches how users actually
    say "first week of November" meaning "the first 7 days of November".

    ordinal: "first"/"second"/"third"/"fourth"/"last". "last" is the final
    7 days of the month (may overlap the 4th week in months with >28 days).
    Returns None if that ordinal week doesn't exist in the month."""
    year = _year_for_month(today, month)
    last_day = _last_day_of_month(year, month)
    if ordinal == "last":
        end_day = last_day
        start_day = max(1, last_day - 6)
    elif ordinal in _MONTH_ORDINALS:
        n = _MONTH_ORDINALS[ordinal]
        start_day = (n - 1) * 7 + 1
        if start_day > last_day:
            return None
        end_day = min(start_day + 6, last_day)
    else:
        return None
    return date(year, month, start_day), date(year, month, end_day)


_WEEK_ORDINAL_GROUP = "(first|second|third|fourth|last)"

_WEEK_OF_MONTH_PATTERN = re.compile(
    rf"\b(?:{_WEEK_ORDINAL_GROUP}\s+week\s+(?:of|in)\s+{_MONTH_NAME_GROUP}"
    rf"|{_MONTH_NAME_GROUP}(?:'s)?\s+{_WEEK_ORDINAL_GROUP}\s+week)\b",
    re.I,
)


def _parse_week_of_month_match(m: re.Match) -> tuple[str, int]:
    """Returns (ordinal, month) from either capture-group order the pattern
    above can match."""
    g = m.groups()
    if g[0] is not None:  # "<ordinal> week of/in <Month>"
        return g[0].lower(), _MONTHS[g[1].lower()]
    return g[3].lower(), _MONTHS[g[2].lower()]  # "<Month> <ordinal> week"


def resolve_week_of_month_phrase(
    query: str, today: date,
) -> Optional[tuple[ResolvedDate, ResolvedDate]]:
    """Finds a '<ordinal> week of <Month>' expression ("first week of
    November", "November's last week") and resolves it directly to a full
    (from_date, to_date) span — unlike resolve_date_range_phrase, a single
    week mention already implies both endpoints, so only ONE match is ever
    needed. A trailing "...to end of the week" elsewhere in the user's
    sentence is redundant with this span and is safely ignored — it never
    needs to be separately parsed. Returns None if no such phrase is found,
    or if the resolved start date is before `today`."""
    m = _WEEK_OF_MONTH_PATTERN.search(query)
    if not m:
        return None
    ordinal, month = _parse_week_of_month_match(m)
    span = week_of_month(today, month, ordinal)
    if span is None:
        return None
    start, end = span
    if start < today:
        return None
    matched = m.group(0)
    return (
        {"from_date": start.isoformat(), "matched_phrase": matched, "matched_kind": "week_of_month"},
        {"from_date": end.isoformat(), "matched_phrase": matched, "matched_kind": "week_of_month"},
    )


# ── "<ordinal> week of next month" — the same day-range construct as
# week_of_month above, but "next month" instead of an explicit month name.
# Live bug, found by mining real production queries (not a single report —
# the SAME underlying concept was retried at least 7 times across
# different phrasings: "next month first week wednesday", "monday in next
# month first week", "wednesday in the second week of next month" x5):
# bare "next month" (see _apply_deterministic_date_overrides's discard-
# next_month guard) is genuinely ambiguous about WHICH day, but "next
# month's Nth week, narrowed to a weekday" is NOT ambiguous at all — it's
# exactly as well-defined as "first week of November", just anchored to
# "next month" instead of a named one. Every real phrasing found only
# needs the ORDINAL+WEEK pair matched here; the weekday itself is found
# separately by weekday_within_span (already generic, no word-order
# dependency), same as week_of_month's own narrowing above.
_NEXT_MONTH_WEEK_PATTERN = re.compile(
    rf"\b(?:{_WEEK_ORDINAL_GROUP}\s+week\s+(?:of\s+|in\s+)?(?<!to\s)next\s+month"
    rf"|(?<!to\s)next\s+month(?:'s|\s+of)?\s+{_WEEK_ORDINAL_GROUP}\s+week)\b",
    re.I,
)


def resolve_week_of_next_month_phrase(query: str, today: date) -> Optional[tuple[date, date]]:
    """Finds an '<ordinal> week of next month' expression, in either word
    order, and resolves it to a literal (start, end) day-range span within
    next month — reuses week_of_month directly by computing next month's
    own number; _year_for_month's existing "wrap to next year if the
    target month number is smaller than today's" comparison already
    produces correct 'next month' semantics (including a December ->
    January rollover) with no separate primitive needed. Returns None if
    no such phrase is found, or if the resolved ordinal week doesn't exist
    in that month."""
    m = _NEXT_MONTH_WEEK_PATTERN.search(query)
    if not m:
        return None
    g = m.groups()
    ordinal = (g[0] or g[1]).lower()
    next_month_num = 1 if today.month == 12 else today.month + 1
    return week_of_month(today, next_month_num, ordinal)


# ── "<ordinal> week of THIS month" — the third and last anchor for the same
# week_of_month construct. A named month ("last week of September") and
# "next month" both had a pattern; "this month" was the one that never did,
# so "Book leave for the last week of this month" (QA report, 2026-09-09)
# resolved to nothing at all and the user was handed an empty date picker
# with only the generic "could you tell me the exact date" to go on — while
# the very same request phrased against a named month worked. Nothing about
# "this month" is any less determinate than the other two; the gap was
# simply that no regex covered it.
_THIS_MONTH_WEEK_PATTERN = re.compile(
    rf"\b(?:{_WEEK_ORDINAL_GROUP}\s+week\s+(?:of\s+|in\s+)?(?:this|current|the\s+current)\s+month"
    rf"|(?:this|current|the\s+current)\s+month(?:'s|\s+of)?\s+{_WEEK_ORDINAL_GROUP}\s+week)\b",
    re.I,
)


def resolve_week_of_this_month_phrase(query: str, today: date) -> Optional[tuple[date, date]]:
    """Finds an '<ordinal> week of this month' expression, in either word
    order, and resolves it to a literal (start, end) span within today's own
    month — same week_of_month construct as its named-month and next-month
    siblings.

    Unlike the next-month sibling (where every week is necessarily still
    ahead), a week of the CURRENT month may already have gone by, so this
    declines a span starting before `today` — the same past-date guard
    resolve_week_of_month_phrase applies to a named month, and the same
    contract every resolver in this module keeps: never hand back a past
    date for a future leave application. "First week of this month" asked
    mid-month therefore falls through to the caller's own handling rather
    than resolving to days that have already passed."""
    m = _THIS_MONTH_WEEK_PATTERN.search(query)
    if not m:
        return None
    g = m.groups()
    ordinal = (g[0] or g[1]).lower()
    span = week_of_month(today, today.month, ordinal)
    if span is None or span[0] < today:
        return None
    return span


# ── "last day of <month>" — the single-day member of the same family, and
# named in the same QA report as the week span above. Determinate for all
# three anchors (this month / next month / a named month), so it belongs
# here rather than in the "ask the user" net. Deliberately NOT extended to
# "last few days": that one genuinely doesn't name a number of days, so
# being asked about it is the correct outcome, not a gap.
_LAST_DAY_OF_MONTH_PATTERN = re.compile(
    r"\blast\s+day\s+(?:of\s+|in\s+)?(?:"
    r"(?P<this>(?:this|current|the\s+current)\s+month)"
    r"|(?P<next>next\s+month)"
    rf"|(?P<named>{_MONTH_NAME_GROUP})"
    r")\b",
    re.I,
)


def resolve_last_day_of_month_phrase(query: str, today: date) -> Optional[ResolvedDate]:
    """'last day of this month' / 'last day of next month' / 'last day of
    October' -> that month's final calendar day. Returns None if no such
    phrase is found, or if the resolved date is already past — the same
    guard every resolver in this module applies."""
    m = _LAST_DAY_OF_MONTH_PATTERN.search(query)
    if not m:
        return None
    if m.group("this"):
        year, month = today.year, today.month
    elif m.group("next"):
        month = 1 if today.month == 12 else today.month + 1
        year = today.year + 1 if today.month == 12 else today.year
    else:
        month = _MONTHS[m.group("named").lower()]
        year = _year_for_month(today, month)
    resolved = date(year, month, _last_day_of_month(year, month))
    if resolved < today:
        return None
    return {
        "from_date": resolved.isoformat(), "matched_phrase": m.group(0),
        "matched_kind": "last_day_of_month",
    }


# ── "<ordinal> <weekday> of next month" — like the named-month-anchored
# pattern above, but "next month" instead of an explicit month name, and
# (unlike first_weekday_of_next_month, which only ever supports "first")
# generalized to any of first/second/third/fourth/last, in either word
# order. Live bug: only the bare "first <weekday> of next month" word order
# had a pattern at all — "next month of first friday" / "next month's
# second wednesday" fell all the way through to the unrelated bare "next
# month" pattern (see _PATTERNS), which silently resolves to just the 1st
# of next month, discarding the weekday entirely.
_NEXT_MONTH_WEEKDAY_PATTERN = re.compile(
    rf"\b(?:{_WEEK_ORDINAL_GROUP}\s+{_WD}\s+of\s+(?<!to\s)next\s+month"
    rf"|(?<!to\s)next\s+month(?:'s|\s+of)?\s+{_WEEK_ORDINAL_GROUP}\s+{_WD})\b",
    re.I,
)


def _resolve_next_month_weekday_match(m: re.Match, today: date) -> Optional[date]:
    g = m.groups()
    if g[0] is not None:  # "<ordinal> <weekday> of next month"
        ordinal, weekday_name = g[0].lower(), g[1].lower()
    else:  # "next month('s) <ordinal> <weekday>"
        ordinal, weekday_name = g[2].lower(), g[3].lower()
    target = _WEEKDAYS[weekday_name]

    if ordinal == "last":
        return last_weekday_of_next_month(today, target)
    return nth_weekday_of_next_month(today, target, _MONTH_ORDINALS[ordinal])


def resolve_next_month_weekday_phrase(query: str, today: date) -> Optional[ResolvedDate]:
    """Finds an '<ordinal> <weekday> of next month' expression, in either
    word order, and resolves it to a single date. Returns None if no such
    phrase is found, or if the resolved date is somehow before `today`
    (shouldn't happen for a genuine "next month" reference, but mirrors
    every other resolver's past-date guard for consistency)."""
    m = _NEXT_MONTH_WEEKDAY_PATTERN.search(query)
    if not m:
        return None
    result = _resolve_next_month_weekday_match(m, today)
    if result is None or result < today:
        return None
    return {"from_date": result.isoformat(), "matched_phrase": m.group(0), "matched_kind": "next_month_weekday"}


# ── "<ordinal> <weekday> this month" — the same construct as
# resolve_next_month_weekday_phrase above, but anchored to the CURRENT
# month instead of next month. Live bug: "last Monday this month" had no
# pattern at all, fell through to the LLM, and got a different (wrong)
# guess on every single call for the identical query — 2026-08-22 one
# minute, 2026-08-15 the next. "this"/"of this"/no connector are all
# accepted before the ordinal+weekday, matching how resolve_week_of_month_
# phrase already tolerates "of"/"in" for the named-month case.
#
# Split into a pure text-matcher (_THIS_MONTH_WEEKDAY_PATTERN) and a
# separate date-resolution step, same architecture as
# resolve_relative_date_phrase/_match_relative_phrase's "yesterday" split —
# a query recognized here that resolves to a date before `today` returns
# None (mirrors resolve_relative_date_phrase's default allow_past=False),
# deferring past-date policy entirely to the existing, company-config-aware
# back-date-disallowed check downstream, rather than silently handing back
# a past date OR duplicating that check's own decision here.
_THIS_MONTH_WEEKDAY_PATTERN = re.compile(
    rf"\b(?:{_WEEK_ORDINAL_GROUP}\s+{_WD}\s+(?:of\s+|in\s+)?(?:this|current)\s+month"
    rf"|(?:this|current)\s+month(?:'s)?\s+{_WEEK_ORDINAL_GROUP}\s+{_WD})\b",
    re.I,
)


def _resolve_this_month_weekday_match(m: re.Match, today: date) -> Optional[date]:
    g = m.groups()
    if g[0] is not None:  # "<ordinal> <weekday> [of/in] this month"
        ordinal, weekday_name = g[0].lower(), g[1].lower()
    else:  # "this month('s) <ordinal> <weekday>"
        ordinal, weekday_name = g[2].lower(), g[3].lower()
    target = _WEEKDAYS[weekday_name]

    if ordinal == "last":
        return last_weekday_of_month(today.year, today.month, target)
    return nth_weekday_of_month(today.year, today.month, target, _MONTH_ORDINALS[ordinal])


def resolve_this_month_weekday_phrase(
    query: str, today: date, allow_past: bool = False,
) -> Optional[ResolvedDate]:
    """Finds an '<ordinal> <weekday> this month' expression, in either word
    order, and resolves it to a single date within `today`'s own month.

    allow_past: same contract as resolve_relative_date_phrase — apply-leave
    callers must use the default (False); a resolved date before `today` is
    treated the same as "unrecognized" (returns None) rather than ever
    silently handing back a past date for a FUTURE leave application. A
    read-only, past-tolerant caller (e.g. a status/history query) would
    pass True."""
    m = _THIS_MONTH_WEEKDAY_PATTERN.search(query)
    if not m:
        return None
    result = _resolve_this_month_weekday_match(m, today)
    if result is None or (result < today and not allow_past):
        return None
    return {"from_date": result.isoformat(), "matched_phrase": m.group(0), "matched_kind": "this_month_weekday"}


# ── "<weekday> of the current/this week" — a DIFFERENT construct from a
# bare "this Wednesday" (this_coming_weekday): "this Wednesday" always
# means the nearest occurrence ON OR AFTER today (future-leaning, by
# design — see this_coming_weekday's own docstring), but "Wednesday of
# THIS WEEK" anchors to the Mon-Sun calendar week containing today and
# means that week's Wednesday specifically, even if today has already
# passed it. Live bug: "Monday of current week" asked on a Tuesday (this
# week's Monday is chronologically YESTERDAY relative to today) had no
# pattern for this distinct meaning, fell through to the LLM's structured
# extraction, and — because the schema had no way to represent "the
# specific day within the current week, regardless of past/future" either
# — the model didn't just approximate, it hallucinated an unrelated date
# that wasn't even a Monday at all.
_THIS_WEEK_WEEKDAY_PATTERN = re.compile(
    rf"\b(?:{_WD}\s+of\s+(?:the\s+)?(?:current|this)\s+week"
    rf"|(?:current|this)\s+week(?:'s)?\s+{_WD})\b",
    re.I,
)


def _resolve_this_week_weekday_match(m: re.Match, today: date) -> Optional[date]:
    g = m.groups()
    weekday_name = (g[0] or g[1]).lower()
    target = _WEEKDAYS[weekday_name]
    monday_this_week = today - timedelta(days=today.weekday())
    return monday_this_week + timedelta(days=target)


def resolve_this_week_weekday_phrase(
    query: str, today: date, allow_past: bool = False,
) -> Optional[ResolvedDate]:
    """Finds a '<weekday> of the current/this week' expression, in either
    word order, and resolves it to that weekday within the Mon-Sun
    calendar week containing `today` — deliberately NOT the same as
    this_coming_weekday(), which searches forward from today instead of
    anchoring to the week boundary.

    allow_past: same contract as every other resolver here — apply-leave
    callers must use the default (False); if the resolved date has already
    passed within the current week (e.g. asked about Monday on a
    Wednesday), this returns None so the caller defers to the existing
    back-date-disallowed check, same as "yesterday" or a now-past "last
    Monday this month" — rather than silently handing back, or worse
    (as observed live) letting an unconstrained LLM guess invent, a wrong
    date. A read-only, past-tolerant caller would pass True."""
    m = _THIS_WEEK_WEEKDAY_PATTERN.search(query)
    if not m:
        return None
    result = _resolve_this_week_weekday_match(m, today)
    if result < today and not allow_past:
        return None
    return {"from_date": result.isoformat(), "matched_phrase": m.group(0), "matched_kind": "this_week_weekday"}


# ── Two-sided ranges for the three single-pattern resolvers above ──────────
# Live bug (found via audit, not a report yet): each of the three resolvers
# above does a plain .search() — the FIRST match only, same shape as the
# original bug resolve_date_range_phrase/resolve_relative_date_range_phrase
# were built to fix for their own phrase families. "Monday of this week to
# Friday of this week", "first Friday of next month to last Friday of next
# month", and "last Monday this month to last Friday this month" each
# currently resolve ONLY to the first endpoint, silently discarding the
# second. Unlike resolve_date_range_phrase (which needs an `after=`
# parameter since its second match can use the ordinal "next", relative to
# the first match rather than today), none of these three constructs
# support that — the second match always resolves independently against
# `today`, so one shared, simpler finditer-based helper covers all three.
def _resolve_same_pattern_range(
    pattern: re.Pattern,
    resolve_match: Callable[[re.Match, date], Optional[date]],
    matched_kind: str,
    query: str,
    today: date,
) -> Optional[tuple[ResolvedDate, Optional[ResolvedDate]]]:
    matches = list(pattern.finditer(query))
    if not matches:
        return None
    first_date = resolve_match(matches[0], today)
    if first_date is None or first_date < today:
        return None
    first_resolved: ResolvedDate = {
        "from_date": first_date.isoformat(), "matched_phrase": matches[0].group(0), "matched_kind": matched_kind,
    }
    if len(matches) < 2:
        return first_resolved, None
    second_date = resolve_match(matches[1], today)
    if second_date is None or second_date <= first_date:
        return first_resolved, None
    second_resolved: ResolvedDate = {
        "from_date": second_date.isoformat(), "matched_phrase": matches[1].group(0), "matched_kind": matched_kind,
    }
    return first_resolved, second_resolved


def resolve_next_month_weekday_range_phrase(
    query: str, today: date,
) -> Optional[tuple[ResolvedDate, Optional[ResolvedDate]]]:
    """'first Friday of next month to last Friday of next month' — two
    _NEXT_MONTH_WEEKDAY_PATTERN matches bound a range; a single match
    behaves exactly like resolve_next_month_weekday_phrase (second=None)."""
    return _resolve_same_pattern_range(
        _NEXT_MONTH_WEEKDAY_PATTERN, _resolve_next_month_weekday_match, "next_month_weekday", query, today,
    )


def resolve_this_month_weekday_range_phrase(
    query: str, today: date,
) -> Optional[tuple[ResolvedDate, Optional[ResolvedDate]]]:
    """'last Monday this month to last Friday this month' — two
    _THIS_MONTH_WEEKDAY_PATTERN matches bound a range."""
    return _resolve_same_pattern_range(
        _THIS_MONTH_WEEKDAY_PATTERN, _resolve_this_month_weekday_match, "this_month_weekday", query, today,
    )


def resolve_this_week_weekday_range_phrase(
    query: str, today: date,
) -> Optional[tuple[ResolvedDate, Optional[ResolvedDate]]]:
    """'Monday of this week to Friday of this week' — two
    _THIS_WEEK_WEEKDAY_PATTERN matches bound a range."""
    return _resolve_same_pattern_range(
        _THIS_WEEK_WEEKDAY_PATTERN, _resolve_this_week_weekday_match, "this_week_weekday", query, today,
    )


# ── Bare "next/upcoming/coming week" (no weekday attached) — a DIFFERENT
# construct from "next week Wednesday" (weekday_of_next_calendar_week,
# handled via _PATTERNS below): a bare mention of the week itself, with no
# day named, implies the WHOLE Mon-Sun span the way "first week of
# November" does (resolve_week_of_month_phrase) — not a single ambiguous
# day the way bare "next month" used to be silently (and wrongly) resolved
# to just the 1st. Live bug: "apply leave for upcoming week" had no pattern
# for this at all, fell through to tier 2's structured extraction (whose
# schema has no way to represent a week span either — only single-day
# day_offset/weekday fields), which guessed day_offset=7 + duration_days=7,
# producing a rolling 7-day window starting a week from today instead of
# the actual Mon-Sun calendar week.
_BARE_NEXT_WEEK_PATTERN = re.compile(
    rf"\b(?:next|upcoming|coming)\s+week\b(?!\s+{_WD})",
    re.I,
)


def next_calendar_week_bounds(anchor: date) -> tuple[date, date]:
    """(Monday, Sunday) of the Mon-Sun calendar week immediately following
    anchor's own current week — same anchor-to-next-Monday computation as
    weekday_of_next_calendar_week, generalized to the whole week's span."""
    monday_this_week = anchor - timedelta(days=anchor.weekday())
    monday_next_week = monday_this_week + timedelta(weeks=1)
    return monday_next_week, monday_next_week + timedelta(days=6)


def resolve_next_calendar_week_phrase(
    query: str, today: date,
) -> Optional[tuple[ResolvedDate, ResolvedDate]]:
    """Finds a bare 'next/upcoming/coming week' mention (no weekday) and
    resolves it directly to the full (Monday, Sunday) span of the following
    calendar week — same "a week mention already implies both endpoints"
    contract as resolve_week_of_month_phrase. Returns None if no such
    phrase is found."""
    m = _BARE_NEXT_WEEK_PATTERN.search(query)
    if not m:
        return None
    start, end = next_calendar_week_bounds(today)
    matched = m.group(0)
    return (
        {"from_date": start.isoformat(), "matched_phrase": matched, "matched_kind": "next_calendar_week"},
        {"from_date": end.isoformat(), "matched_phrase": matched, "matched_kind": "next_calendar_week"},
    )


def weekday_within_span(query: str, start: date, end: date) -> Optional[ResolvedDate]:
    """If `query` ALSO names a specific weekday (e.g. "november first week
    coming wednesday"), narrows an already-resolved week-of-month span down
    to that single day, instead of the caller using the whole 7-day span.

    Live bug: "apply casual leave for november first week coming wednesday
    for 1 day" was treated as a 7-day request for the entire first week
    (matching "You only have 6 day(s)... but this request needs 7.0"),
    silently ignoring BOTH the weekday narrowing ("coming wednesday") and
    the explicit duration ("for 1 day") that followed it — because
    resolve_week_of_month_phrase's caller returned immediately with the
    full span before either could be considered.

    A bare weekday name is matched here regardless of a "this"/"coming"/
    "next"/etc. modifier — within an already-resolved single week there is
    exactly one occurrence of any given weekday, so the modifier can't
    change which date is meant. Returns None if no weekday name is present
    in `query` at all, or (defensively) if the span contains no matching
    date — callers should fall back to the full span in either case."""
    m = re.search(_WD, query, re.I)
    if not m:
        return None
    target = _WEEKDAYS[m.group(1).lower()]
    d = start
    while d <= end:
        if d.weekday() == target:
            return {"from_date": d.isoformat(), "matched_phrase": m.group(0), "matched_kind": "weekday_within_week"}
        d += timedelta(days=1)
    return None


# ── Phrase matcher ──────────────────────────────────────────────────────────
# Order matters: more specific phrases MUST be checked before the shorter
# phrases they contain as substrings ("next to next monday" contains "next
# monday"; "first monday of next month" contains "next month"), or the
# shorter/wrong pattern would win. Do not reorder without re-verifying this.

_PATTERNS: list[tuple[re.Pattern, str]] = [
    (re.compile(r"\bday\s+after\s+tomorrow\b", re.I), "day_after_tomorrow"),
    (re.compile(r"\btomorrow\b", re.I), "tomorrow"),
    (re.compile(r"\byesterday\b", re.I), "yesterday"),
    (re.compile(r"\btoday\b", re.I), "today"),
    (re.compile(rf"\bnext\s+to\s+next\s+{_WD}\b", re.I), "next_to_next_weekday"),
    (re.compile(rf"\bfirst\s+{_WD}\s+of\s+next\s+month\b", re.I), "first_weekday_of_next_month"),
    (re.compile(rf"\b(?:next|upcoming|coming)\s+week\s+{_WD}\b", re.I), "weekday_of_next_calendar_week"),
    (re.compile(rf"\bnext\s+{_WD}\b", re.I), "next_weekday_strict"),
    (re.compile(rf"\b(?:this\s+coming|coming|upcoming|this)\s+{_WD}\b", re.I), "this_coming_weekday"),
    (re.compile(r"\bweek\s+after\s+next\b", re.I), "week_after_next"),
    (re.compile(r"\bnext\s+month\b", re.I), "next_month"),
]


def _resolve_kind(kind: str, today: date, target_weekday: Optional[int]) -> Optional[date]:
    if kind == "day_after_tomorrow":
        return today + timedelta(days=2)
    if kind == "tomorrow":
        return today + timedelta(days=1)
    if kind == "yesterday":
        return today - timedelta(days=1)
    if kind == "today":
        return today
    if kind == "next_to_next_weekday":
        return next_to_next_weekday(today, target_weekday)
    if kind == "next_weekday_strict":
        return next_weekday_strict(today, target_weekday)
    if kind == "weekday_of_next_calendar_week":
        return weekday_of_next_calendar_week(today, target_weekday)
    if kind == "this_coming_weekday":
        return this_coming_weekday(today, target_weekday)
    if kind == "first_weekday_of_next_month":
        return first_weekday_of_next_month(today, target_weekday)
    if kind == "week_after_next":
        return week_after_next(today)
    if kind == "next_month":
        return first_of_next_month(today)
    return None


def _match_relative_phrase(text: str) -> Optional[tuple[str, Optional[int], str]]:
    """Matches `text` against _PATTERNS in priority order — the FIRST
    pattern that matches ANYWHERE in the (lowercased) text wins, regardless
    of where in the text it appears (see resolve_relative_date_phrase's own
    docstring for why that's the correct behavior for a single bare
    anchor). Returns (kind, target_weekday_or_None, matched substring), or
    None if nothing recognized. Pure text matching only — does not resolve
    to a date, so it has no `today`/anchor dependency and is safe to reuse
    against an isolated substring (see resolve_relative_date_range_phrase)."""
    lowered = text.lower()
    for pattern, kind in _PATTERNS:
        m = pattern.search(lowered)
        if not m:
            continue
        weekday_name = m.groups()[-1] if m.groups() else None
        target = _WEEKDAYS.get(weekday_name) if weekday_name else None
        return kind, target, m.group(0)
    return None


def resolve_relative_date_phrase(
    query: str, today: date, allow_past: bool = False,
) -> Optional[ResolvedDate]:
    """Matches the FIRST recognized relative-date phrase in `query` (patterns
    checked in priority order — see _PATTERNS) and resolves it against
    `today`. Returns None if nothing recognized — callers must fall through
    to the existing LLM-driven extraction unchanged; this function NEVER
    guesses.

    allow_past: "yesterday" resolves to a date before today by definition.
    Apply-leave callers must use the default (False) — a resolved date
    before `today` is treated as unrecognized (returns None) rather than
    ever silently handing back a past date for a FUTURE leave application.
    A future read-only status-query reuse of this function would pass True.

    A bare single-anchor phrase never implies a date RANGE on its own —
    callers combine the returned from_date with extract_duration_days()
    or their own already-known to_date."""
    match = _match_relative_phrase(query)
    if match is None:
        return None
    kind, target, matched_text = match
    resolved = _resolve_kind(kind, today, target)
    if resolved is None:
        return None
    if resolved < today and not allow_past:
        return None
    return {"from_date": resolved.isoformat(), "matched_phrase": matched_text, "matched_kind": kind}


# ── Bare weekday-to-weekday range ("upcoming Wednesday to next Sunday") —
# a DIFFERENT construct again from the named-month range and the
# week-of-month range above: no month is named on either side, just two
# independently-recognized _PATTERNS phrases joined by a connector word.
#
# resolve_relative_date_phrase() above deliberately only ever returns its
# FIRST match by fixed PATTERN PRIORITY order, not by where phrases appear
# in the text — that's correct and sufficient for a single bare anchor, but
# it silently breaks for two-sided ranges: live bug, "upcoming Wednesday to
# next Sunday" resolved to "next Sunday" alone (a higher-priority pattern),
# completely ignoring "upcoming Wednesday" — which appears FIRST in the
# sentence — because next_weekday_strict is checked before
# this_coming_weekday in _PATTERNS regardless of position in the query.

_RELATIVE_PHRASE_ALTERNATION = "|".join(f"(?:{p.pattern})" for p, _ in _PATTERNS)

# The closing endpoint may be a BARE weekday with no modifier of its own —
# "next Monday to Wednesday" (QA report, 2026-09-09). Every _PATTERNS entry
# requires a modifier ("next"/"this"/"upcoming"/...), so before this the
# second half matched nothing, the whole connector pattern failed, and the
# caller fell back to the single-anchor resolver: it captured "next Monday"
# and dropped "Wednesday" entirely, submitting a 1-day request for what the
# user asked to be a 3-day one.
#
# Only ever accepted in SECOND position, and only directly after the
# connector word: a bare weekday is far too common in ordinary text to
# recognize loosely ("cancel my monday leave"), but "<recognized relative
# phrase> to <weekday>" is unambiguous — the phrase before the connector is
# what makes it a range, and the weekday after it can only be its end.
# Listed last in the alternation so a fully-qualified second endpoint
# ("next monday to NEXT wednesday") still matches as its own phrase.
_BARE_WEEKDAY_ENDPOINT = r"\b" + _WD + r"\b"

_RELATIVE_DATE_RANGE_CONNECTOR = re.compile(
    rf"(?P<first>{_RELATIVE_PHRASE_ALTERNATION})\s*(?:to|till|until|through)\s*"
    rf"(?P<second>{_RELATIVE_PHRASE_ALTERNATION}|{_BARE_WEEKDAY_ENDPOINT})",
    re.I,
)

_BARE_WEEKDAY_ONLY = re.compile(rf"^\s*{_WD}\s*$", re.I)


def resolve_relative_date_range_phrase(
    query: str, today: date,
) -> Optional[tuple[ResolvedDate, Optional[ResolvedDate]]]:
    """Finds a bare (no named month) two-sided range like 'upcoming
    Wednesday to next Sunday' / 'this Monday to next Friday' — two
    independently-recognized _PATTERNS phrases joined by 'to'/'till'/
    'until'/'through', found by their actual left-to-right position in the
    text (unlike resolve_relative_date_phrase's fixed priority order).

    The FIRST endpoint resolves against `today`, same as a standalone
    mention. The SECOND endpoint resolves RELATIVE TO THE FIRST endpoint's
    resolved date, not independently against `today` — mirroring the
    named-month range's `after`-relative "next" design
    (weekday_in_named_month). This is deliberate, not incidental: "upcoming
    Wednesday to next Sunday" means the Sunday following that Wednesday.
    Resolving both sides against `today` independently was the original
    bug — "next Sunday" (strictly after today) can land BEFORE "upcoming
    Wednesday" (also on/after today) whenever today itself falls between
    the two weekdays, silently producing an inverted range.

    If the second phrase doesn't resolve, or its date-relative-to-first
    result is not strictly after the first, the range is dropped — returns
    (first, None) rather than an inverted or same-day range. Returns None
    if no connector-joined pair of recognized phrases is found at all."""
    m = _RELATIVE_DATE_RANGE_CONNECTOR.search(query)
    if not m:
        return None

    first_match = _match_relative_phrase(m.group("first"))
    if first_match is None:
        return None
    first_kind, first_target, first_text = first_match
    first_date = _resolve_kind(first_kind, today, first_target)
    if first_date is None or first_date < today:
        return None
    first_resolved: ResolvedDate = {
        "from_date": first_date.isoformat(), "matched_phrase": first_text, "matched_kind": first_kind,
    }

    second_text = m.group("second")
    second_match = _match_relative_phrase(second_text)
    if second_match is None:
        # A bare weekday closing the range ("next Monday to Wednesday") —
        # see _BARE_WEEKDAY_ENDPOINT. Resolved as the first occurrence of
        # that weekday STRICTLY AFTER the range's own start, which is the
        # same first-relative rule every other second endpoint here follows;
        # anchoring it to `today` instead could land it before the start and
        # invert the range.
        bare = _BARE_WEEKDAY_ONLY.match(second_text)
        if bare is None:
            return first_resolved, None
        second_date = this_coming_weekday(
            first_date + timedelta(days=1), _WEEKDAYS[bare.group(1).lower()])
        return first_resolved, {
            "from_date": second_date.isoformat(),
            "matched_phrase": bare.group(1),
            "matched_kind": "bare_weekday_range_end",
        }
    second_kind, second_target, second_text = second_match
    second_date = _resolve_kind(second_kind, first_date, second_target)
    if second_date is None or second_date <= first_date:
        return first_resolved, None
    second_resolved: ResolvedDate = {
        "from_date": second_date.isoformat(), "matched_phrase": second_text, "matched_kind": second_kind,
    }
    return first_resolved, second_resolved


# ── Duration extractor ──────────────────────────────────────────────────────

_DURATION_QTY_GROUP = r"(\d+|a|an|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)"
_DURATION_UNIT_GROUP = r"(day|days|week|weeks|month|months)"

_DURATION_PATTERN = re.compile(
    rf"\b(?:for\s+)?{_DURATION_QTY_GROUP}\s+{_DURATION_UNIT_GROUP}\b",
    re.I,
)


def _qty_to_int(qty_raw: str) -> Optional[int]:
    return int(qty_raw) if qty_raw.isdigit() else _NUMBER_WORDS.get(qty_raw)


def _days_for_qty_unit(qty: int, unit: str) -> int:
    if unit.startswith("day"):
        return qty
    if unit.startswith("week"):
        return qty * 7
    return qty * _APPROX_DAYS_PER_MONTH  # "month"/"months"


def extract_duration_days(query: str, exclude: Optional[str] = None) -> Optional[int]:
    """'20 days' -> 20, 'for 5 days' -> 5, 'a week' -> 7, 'two weeks' -> 14,
    'a month' -> 30 (see _APPROX_DAYS_PER_MONTH). Returns None if no
    duration phrase is found. Deliberately not LLM-driven — the extraction
    schema has no duration field at all today, so a spoken count like "20
    days" previously had nowhere to land and was silently discarded.

    exclude: a substring (case-insensitive) to blank out before searching —
    pass the matched_phrase of a resolver that already consumed part of the
    query. Live bug: "apply leave a week after next" resolved "week after
    next" to a single day via resolve_relative_date_phrase, but this
    function ALSO separately matched "a week" in the very same sentence and
    returned 7, which the caller then applied as an explicit multi-day
    duration — silently corrupting a single-day request into a 7-day range.
    A resolver's own already-consumed phrase must never double as a
    separate duration count. Default None reproduces prior behavior
    exactly."""
    text = query
    if exclude:
        idx = text.lower().find(exclude.lower())
        if idx != -1:
            text = text[:idx] + " " * len(exclude) + text[idx + len(exclude):]
    m = _DURATION_PATTERN.search(text.lower())
    if not m:
        return None
    qty_raw, unit = m.groups()
    qty = _qty_to_int(qty_raw)
    if not qty:
        return None
    return _days_for_qty_unit(qty, unit)


# ── Bare duration-offset phrases ("in two weeks", "15 days from now") ──────
# Systemic gap found via audit, not a single live bug report: tier 2's LLM
# gate and tier 3's "don't trust it, ask instead" cross-check both key off
# _RELATIVE_DATE_QUALIFIER_PATTERN/_find_named_weekday — a phrase with
# neither (no weekday name, none of next/this/coming/last/etc.) is
# completely invisible to both, and silently rides on the plain first-pass
# LLM extraction's own guess with zero cross-check. This is genuinely
# deterministic day arithmetic though — no reason to spend an LLM call or
# a possible "let me ask" turn on something Python can compute exactly, the
# same reasoning that already applies to "tomorrow"/"next Monday" above.
_RELATIVE_DURATION_OFFSET_PATTERN = re.compile(
    rf"\b(?:in|after)\s+{_DURATION_QTY_GROUP}\s+{_DURATION_UNIT_GROUP}\b"
    rf"|\b{_DURATION_QTY_GROUP}\s+{_DURATION_UNIT_GROUP}\s+from\s+(?:now|today)\b",
    re.I,
)


def mentions_relative_duration_qualifier(query: str) -> bool:
    """True if `query` contains a bare duration-offset phrase ("in two
    weeks", "15 days from now") — a pure text signal (not a resolution),
    reusable as an additional gate/scrutiny trigger by callers that need to
    know whether this kind of phrasing is present, independent of whether
    resolve_relative_duration_offset_phrase below can actually resolve it."""
    return bool(_RELATIVE_DURATION_OFFSET_PATTERN.search(query))


def resolve_relative_duration_offset_phrase(
    query: str, today: date, allow_past: bool = False,
) -> Optional[ResolvedDate]:
    """Finds a bare 'in/after N days/weeks/months' or 'N days/weeks/months
    from now/today' phrase and resolves it to today + that many days
    ('week'=7, 'month'=_APPROX_DAYS_PER_MONTH, same approximation as
    extract_duration_days). Returns None if no such phrase is found. Same
    allow_past/past-date-guard contract as every other resolver here."""
    m = _RELATIVE_DURATION_OFFSET_PATTERN.search(query.lower())
    if not m:
        return None
    g = m.groups()
    qty_raw, unit = (g[0], g[1]) if g[0] is not None else (g[2], g[3])
    qty = _qty_to_int(qty_raw)
    if not qty:
        return None
    result = today + timedelta(days=_days_for_qty_unit(qty, unit))
    if result < today and not allow_past:
        return None
    return {"from_date": result.isoformat(), "matched_phrase": m.group(0), "matched_kind": "relative_duration_offset"}


# ── Bare ordinal day-of-month with no month anchor ("on 15th") ─────────────
# Live bug: "Apply leave on 15th" on 2026-08-27 silently resolved to
# 2026-09-15 (the LLM rolled it to next month, since Aug 15 had already
# passed) with no indication anywhere — not even a stated assumption — that
# a month had been inferred at all. A bare day-of-month that's still
# upcoming THIS month ("the 5th" on Aug 1) is genuinely unambiguous; one
# that's already passed is not — resolution has to silently choose between
# "next month" and "user made a mistake", and today's bug is that choice
# being made with zero disclosure. This is a pure text+today signal (like
# mentions_relative_duration_qualifier above) meant to be OR'd into
# hr_graph._query_needs_relative_date_scrutiny, not a resolver — date_resolver
# still never parses a plain absolute date itself (see module docstring).
_BARE_ORDINAL_DAY_PATTERN = re.compile(r"\b([1-9]|[12]\d|3[01])(?:st|nd|rd|th)\b", re.I)
_MONTH_QUALIFIER_PATTERN = re.compile(r"\b(?:next|this|current|coming)\s+month\b", re.I)


def mentions_ambiguous_bare_day_of_month(query: str, today: date) -> Optional[int]:
    """Returns the day number if `query` names a bare ordinal day-of-month
    ("15th", "on the 3rd") with no month name and no explicit month
    qualifier ("next/this/current/coming month") anywhere in the query, AND
    that day has already passed in the CURRENT month (day < today.day) —
    the one condition that makes the reading genuinely ambiguous. Returns
    None otherwise, including for the safe/unambiguous case (day still
    upcoming this month), an explicitly-named month ("15th August"), or an
    explicit month qualifier ("next month's 15th") — all of those already
    unambiguously resolve without any inference needing to be surfaced.
    Deliberately requires the ordinal suffix (st/nd/rd/th) — a bare "on 15"
    with no suffix is out of scope, same false-positive-risk trade-off this
    module makes elsewhere."""
    m = _BARE_ORDINAL_DAY_PATTERN.search(query)
    if not m:
        return None
    # Abbreviations count ("oct"), as whole words only ("mar" is not in
    # "marriage"). QA: "casul leave from 5th to 7th oct" was asked whether it
    # meant 05 Oct, because only full month names were recognised here.
    if re.search(r"\b(?:" + "|".join(sorted(_ALL_MONTH_TOKENS, key=len, reverse=True)) + r")\b",
                 query, re.IGNORECASE):
        return None
    if _MONTH_QUALIFIER_PATTERN.search(query):
        return None
    day = int(m.group(1))
    if day >= today.day:
        return None
    return day


# ── Explicit numeric dates ("10/09/2026", "21-08-26", "10/09") ─────────────
# Live bug: "From 10/09/2026 to 11/09/2026" (meant: 10 Sep - 11 Sep, 2 days)
# was submitted as 2026-10-09 -> 2026-11-09, a 32-day request the user never
# made. Nothing in this file used to touch literal dates at all — the module
# docstring's "never a replacement for the LLM's own handling of absolute
# dates" carved them out deliberately, on the reasoning that literal parsing
# involves no arithmetic and so is the one thing the LLM is reliable at. That
# reasoning holds for word-form dates ("12th November"), which name their
# month unambiguously. It does NOT hold for the all-numeric form: "10/09/2026"
# carries no signal about which number is the month, so the LLM falls back to
# its own training-data default (US month-first) and there is no arithmetic
# error to detect afterwards — the result is a perfectly well-formed date that
# is simply the wrong one, which is exactly why it sailed past every guard in
# hr_graph (_llm_date_needs_confirmation explicitly waves absolute dates
# through, and the range isn't in the past, so no branch fires).
#
# Day-first is not a guess here, it is this product's stated convention: the
# HRMS renders every date as dd/MM/yyyy, so a user typing 10/09/2026 into the
# assistant is echoing back the format the rest of the app just showed them.
# Resolving it any other way contradicts what the user is looking at.
#
# Deliberately NOT dropped for being in the past (unlike every relative
# resolver above): a past relative phrase means the arithmetic went wrong, but
# a past date typed out in full is a deliberate back-date request, and the
# company-policy-aware back-date check downstream in hr_graph already owns
# that decision.
_NUMERIC_DATE_PATTERN = re.compile(
    r"(\d{1,2})\s*[/-]\s*(\d{1,2})(?:\s*[/-]\s*(\d{4}|\d{2}))?"
)

# ISO dates are already unambiguous and already handled; their inner "09-10"
# would otherwise be re-read as a day-first pair, so their spans are excluded
# outright rather than guarded with regex lookaround (a lookbehind wide enough
# to reject "2026-09-10" also rejects the second endpoint of a hyphen-joined
# range like "10/09/2026-11/09/2026").
_ISO_DATE_PATTERN = re.compile(r"\d{4}-\d{1,2}-\d{1,2}")


def parse_numeric_date(
    day_raw: int, month_raw: int, year_raw: Optional[str], today: date,
) -> Optional[date]:
    """Day-first reading of an all-numeric date's already-split components.

    Returns None (never a guess) for anything that isn't a real calendar
    date, so the caller falls through to the LLM exactly as before.

    The one case read month-first is when the FIRST number can't be a month
    (13-31) and the second can — "09/21/2026" has only one valid reading, so
    taking it is forced by the calendar, not inferred from a preference.
    Both numbers above 12 has no valid reading at all and returns None.

    A missing year resolves to the current one, but ONLY if that lands on or
    after `today`; a year-less date that would land in the past is genuinely
    ambiguous about which year was meant (this year, already gone, vs. next),
    and returns None so the same "ask, don't guess" path that
    mentions_ambiguous_bare_day_of_month feeds already handles it. A 2-digit
    year is read as 20xx."""
    day, month = day_raw, month_raw
    if month > 12:
        if day > 12:
            return None          # no valid reading either way
        day, month = month, day  # forced month-first, not a preference

    if year_raw is None:
        try:
            candidate = date(today.year, month, day)
        except ValueError:
            return None
        return candidate if candidate >= today else None

    year = int(year_raw)
    if len(year_raw) == 2:
        year += 2000
    try:
        return date(year, month, day)
    except ValueError:
        return None


def resolve_numeric_date_range(
    query: str, today: date,
) -> Optional[tuple[ResolvedDate, Optional[ResolvedDate]]]:
    """Finds all-numeric dates in `query`, in the order they appear, and
    reads them day-first (see parse_numeric_date and this section's header).

    Same result shape and same fall-through contract as
    resolve_date_range_phrase:
    - exactly one date: (that ResolvedDate, None) — a single anchor, so a
      duration count elsewhere in the message ("from 10/09/2026 for 3 days")
      still applies on top of it in the caller.
    - two or more: the FIRST TWO become (from, to).
    - nothing recognized, or anything unresolvable: None.

    An inverted pair (second endpoint before the first) returns None rather
    than a backwards range — that's a typo or a misparse, not a request, and
    None routes it to the existing confirmation path instead of asserting a
    range the user can't have meant."""
    iso_spans = [m.span() for m in _ISO_DATE_PATTERN.finditer(query)]

    resolved: list[ResolvedDate] = []
    for m in _NUMERIC_DATE_PATTERN.finditer(query):
        start, end = m.span()
        if any(start < iso_end and iso_start < end for iso_start, iso_end in iso_spans):
            continue
        d = parse_numeric_date(int(m.group(1)), int(m.group(2)), m.group(3), today)
        if d is None:
            return None  # a malformed date in the text — don't half-read the message
        resolved.append({
            "from_date": d.isoformat(),
            "matched_phrase": m.group(0),
            "matched_kind": "numeric_date",
        })
        if len(resolved) == 2:
            break

    if not resolved:
        return None
    if len(resolved) == 1:
        return resolved[0], None
    if resolved[1]["from_date"] < resolved[0]["from_date"]:
        return None
    return resolved[0], resolved[1]


# ── Cheap date-mention pre-check ────────────────────────────────────────────
# Deliberately loose (month names, "today"/"tomorrow"/"yesterday", digit-heavy
# date patterns like ISO or DD/MM) — a false positive just means a caller does
# one harmless extra check, but a false negative would silently skip handling
# a query that really did name a date, so this errs toward matching. Public
# and query-only (no `today` needed) since it answers "does this text mention
# a date at all", not "what date" — any caller across the app can use it as a
# cheap classification signal without pulling in the rest of this module's
# date-math machinery.
DATE_MENTION_PATTERN = re.compile(
    r"\b(jan(uary)?|feb(ruary)?|mar(ch)?|apr(il)?|may|jun(e)?|jul(y)?|aug(ust)?|"
    r"sep(t(ember)?)?|oct(ober)?|nov(ember)?|dec(ember)?|today|tomorrow|yesterday)\b"
    # A bare WEEKDAY name is a date mention too. Its absence here was a
    # silent wrong-day bug rather than a missed optimisation: callers gate
    # date resolution on this check, so "show missing punches for Monday"
    # skipped resolution entirely and answered for TODAY - a plausible-looking
    # summary for the wrong day, with nothing to signal it.
    # resolve_past_weekday_phrase / resolve_relative_date_phrase own which
    # Monday it actually is; this only has to say "a date was named".
    rf"|\b{_WD}\b"
    r"|\b\d{1,2}(st|nd|rd|th)?[/-]\d{1,2}([/-]\d{2,4})?\b"
    r"|\b\d{4}-\d{2}-\d{2}\b",
    re.IGNORECASE,
)


# A date typed with no spaces: QA's "22nsep2026" (and "22sep2026", "22sep
# 2026", "sep22") matched no date pattern at all, so team attendance quietly
# answered for TODAY. Un-glued to "22 sep 2026" before any matching. The
# day's suffix may be cut short ("22n" for "22nd"); the month must be a real
# month name or abbreviation, so ordinary words are never split.
_GLUED_MONTH = (r"(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|"
                r"aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)")
_GLUED_DAY_MONTH_RE = re.compile(
    r"\b(\d{1,2})(?:st|nd|rd|th|n|d|t|s)?[\s./-]*" + _GLUED_MONTH + r"(?![a-z])[\s./-]*(\d{4})?\b",
    re.IGNORECASE)
_GLUED_MONTH_DAY_RE = re.compile(
    r"\b" + _GLUED_MONTH + r"(\d{1,2})(?:st|nd|rd|th)?\b", re.IGNORECASE)


def unglue_dates(text: str) -> str:
    """"22nsep2026" -> "22 sep 2026", "sep22" -> "sep 22"."""
    if not text:
        return text
    text = _GLUED_DAY_MONTH_RE.sub(
        lambda m: f"{m.group(1)} {m.group(2)}" + (f" {m.group(3)}" if m.group(3) else ""), text)
    return _GLUED_MONTH_DAY_RE.sub(lambda m: f"{m.group(1)} {m.group(2)}", text)


def mentions_date_expression(query: str) -> bool:
    """True if `query` plausibly names a date — a whole-app-reusable version
    of what used to be a private, narrower check inside hr_graph.py used only
    to gate one extra LLM call in the leave-status branch. Promoted here so
    classify_node can compute it once per query, for every intent, not just
    leave_status."""
    return bool(DATE_MENTION_PATTERN.search(unglue_dates(query or "")))


# ── Structured resolution (LLM-extracted fields, no free-text regex) ───────
# Every pattern function above recognizes ONE specific English phrasing —
# proven reliable, but each new way of saying the same thing needs its own
# regex (three live bugs in one evening: "next week Wednesday", "next month
# of first Friday", "last Monday this month" — all the same underlying
# concept, three different phrasings, three separate patches). This section
# is a second, complementary route to the SAME underlying arithmetic
# (reusing the exact primitives above — no new date math anywhere in this
# function) for callers that have ALREADY turned free text into a small set
# of structured fields (e.g. via an LLM asked to extract fields only, never
# compute a date itself — see hr_graph's structured date-extraction call).
# This is additive, same contract as every function above: returns None for
# anything it can't confidently resolve from the given fields, never
# guesses, and never invents math it doesn't already have a tested
# primitive for.

_STRUCTURED_WEEKDAY_RELATIONS = ("this", "next", "next_to_next")
_STRUCTURED_ORDINALS = ("first", "second", "third", "fourth", "last")


def _add_months(anchor: date, n: int) -> tuple[int, int]:
    """(year, month) that is `n` calendar months after anchor's own month —
    n=0 is anchor's own month, n=1 is first_of_next_month's month, n=2 is
    two months ahead, etc. Pure month-index arithmetic, no day-of-month
    involved (callers only need year/month, e.g. to find an Nth weekday
    within it) so there's no end-of-month edge case to handle."""
    month_index = anchor.month - 1 + n
    return anchor.year + month_index // 12, month_index % 12 + 1


def resolve_structured_date(
    today: date,
    day_offset: Optional[int] = None,
    target_weekday: Optional[str] = None,
    weekday_relation: Optional[str] = None,
    ordinal: Optional[str] = None,
    month_offset: Optional[int] = None,
    allow_past: bool = False,
) -> Optional[date]:
    """Computes a single date from structured fields instead of matching
    free text. Two independent shapes can each produce a candidate:

      1. day_offset — "tomorrow"=+1, "yesterday"=-1, "today"=0, "day after
         tomorrow"=+2.
      2. target_weekday + EITHER weekday_relation (a bare weekday-relative
         reference, no month anchor: "this"/"next"/"next_to_next") OR
         ordinal + month_offset (an "Nth weekday of month" reference:
         ordinal="first".."fourth"/"last", month_offset=0 for "this month",
         1 for "next month", 2+ for "N months from now" — explicit NAMED
         months stay out of scope here; the regex layer already resolves
         those confidently via resolve_date_range_phrase). Live bug:
         month_offset used to be a two-value "this"/"next" string
         (month_ref) — "next 2 months" had no way to be represented at
         all, so the model silently dropped the "2" and answered as if it
         had said "next month," a wrong answer with no signal anything was
         lost. An integer offset represents any month count the model can
         actually read off the sentence, instead of forcing an
         approximation into a two-value enum.

    The prompt instructs the model to populate only ONE shape, but live
    evidence (this module's own tool-calling diagnostic against a real
    model) showed it frequently populating BOTH anyway — for a simple case
    ("this coming Friday") the two shapes naturally AGREE, so this function
    computes both whenever applicable and only refuses when they actively
    DISAGREE (a real confidence signal: something outside this schema's
    vocabulary, e.g. "a week from next Tuesday" — the model populated
    day_offset=7 alongside weekday fields for "next Tuesday" alone, and the
    two candidates land on different dates because the phrase means
    something this schema can't cleanly represent). Trusting whichever
    single shape happened to be set — this function's original design —
    silently produced a wrong date in exactly that case; refusing on
    disagreement instead means a wrong answer never reaches the user, at
    the cost of occasionally asking for something a smarter parse could
    have gotten right.

    Returns None (never guesses) for: the two shapes' candidates
    disagreeing; no target_weekday when one of the weekday-dependent shapes
    is implied; an unrecognized weekday/relation/ordinal value; a negative
    month_offset (a past month is out of scope — the regex layer's own
    past-date guard convention); ordinal given without month_offset
    (ambiguous which month) or vice versa; a nonexistent Nth occurrence
    (e.g. a 5th Friday); neither shape populated at all; or — unless
    allow_past=True — any resolved date before `today`, same past-date
    contract as every function above.

    allow_past: same contract as resolve_relative_date_phrase /
    resolve_this_month_weekday_phrase — apply-leave callers must use the
    default (False)."""
    day_offset_result: Optional[date] = None
    if day_offset is not None:
        day_offset_result = today + timedelta(days=day_offset)

    weekday_result: Optional[date] = None
    if target_weekday is not None:
        target_weekday = target_weekday.lower()
        if target_weekday not in _WEEKDAYS:
            return None
        wd = _WEEKDAYS[target_weekday]

        if ordinal is not None:
            ordinal = ordinal.lower()
            if ordinal not in _STRUCTURED_ORDINALS or month_offset is None or month_offset < 0:
                return None
            year, month = _add_months(today, month_offset)
            weekday_result = (
                last_weekday_of_month(year, month, wd) if ordinal == "last"
                else nth_weekday_of_month(year, month, wd, _MONTH_ORDINALS[ordinal])
            )
        elif weekday_relation is not None:
            weekday_relation = weekday_relation.lower()
            if weekday_relation not in _STRUCTURED_WEEKDAY_RELATIONS:
                return None
            if weekday_relation == "this":
                weekday_result = this_coming_weekday(today, wd)
            elif weekday_relation == "next":
                weekday_result = next_weekday_strict(today, wd)
            else:  # "next_to_next"
                weekday_result = next_to_next_weekday(today, wd)

    if day_offset_result is not None and weekday_result is not None:
        result = day_offset_result if day_offset_result == weekday_result else None
    else:
        result = day_offset_result if day_offset_result is not None else weekday_result

    if result is None or (result < today and not allow_past):
        return None
    return result


# ── Explicit calendar dates ("July 13", "13 July 2026", "2026-07-13") ────────
# Everything above resolves dates RELATIVE to today. A past-tolerant read
# query (an attendance lookup) also has to handle a date stated outright,
# which the LLM extraction tier gets wrong in a specific and dangerous way:
# asked for "july 13" with today = 2026-09-01 it returns 2023-07-13, three
# years off, silently answering about a different day. Parsing it here
# removes the guess.

_MONTH_ABBREVIATIONS: dict[str, int] = {
    "jan": 1, "feb": 2, "mar": 3, "apr": 4, "jun": 6, "jul": 7,
    "aug": 8, "sep": 9, "sept": 9, "oct": 10, "nov": 11, "dec": 12,
}

_ALL_MONTH_TOKENS = {**_MONTHS, **_MONTH_ABBREVIATIONS}
_MONTH_TOKEN_GROUP = "(" + "|".join(sorted(_ALL_MONTH_TOKENS, key=len, reverse=True)) + ")"
_DAY_GROUP = r"(\d{1,2})(?:st|nd|rd|th)?"
_YEAR_GROUP = r"(?:,?\s*(\d{4}))?"

# "July 13", "Jul 13th, 2026"
_MONTH_DAY_PATTERN = re.compile(
    rf"\b{_MONTH_TOKEN_GROUP}\.?\s+{_DAY_GROUP}{_YEAR_GROUP}\b", re.IGNORECASE
)
# "13 July", "13th of July 2026"
_DAY_MONTH_PATTERN = re.compile(
    rf"\b{_DAY_GROUP}\s+(?:of\s+)?{_MONTH_TOKEN_GROUP}\.?{_YEAR_GROUP}\b", re.IGNORECASE
)
# "2026-07-13"
_ISO_DATE_PATTERN = re.compile(r"\b(\d{4})-(\d{2})-(\d{2})\b")


def _year_for_past_tolerant(today: date, month: int, day: int) -> int:
    """Which year an unqualified "July 13" means for a query that may look
    backwards.

    The most recent occurrence that is not in the future. This is the
    OPPOSITE of _year_for_month's forward-only rule, which exists for
    apply-leave (where a date must not be in the past) and would read
    "July 13" on 1 September as next year. An attendance record for a
    future date cannot exist, so rolling forward there guarantees an empty
    answer for a day the manager can actually see in the HRMS.
    """
    try:
        candidate = date(today.year, month, day)
    except ValueError:
        # 29 Feb in a non-leap year - step back to the most recent leap year.
        year = today.year
        while year > today.year - 8:
            year -= 1
            try:
                return date(year, month, day).year
            except ValueError:
                continue
        return today.year
    return today.year if candidate <= today else today.year - 1


def resolve_explicit_calendar_date(query: str, today: date) -> Optional[str]:
    """An outright-stated calendar date as "YYYY-MM-DD", or None.

    Past-tolerant: an unqualified month/day resolves to its most recent
    occurrence, not the next one. A stated year is always honoured as-is,
    including a future one - if someone says "13 July 2027" they mean it.
    Returns None when the query states no explicit date, leaving relative
    phrases ("yesterday", "last Monday") to resolve_relative_date_phrase.
    """
    query = unglue_dates(query or "")
    iso = _ISO_DATE_PATTERN.search(query)
    if iso:
        try:
            return date(int(iso.group(1)), int(iso.group(2)), int(iso.group(3))).isoformat()
        except ValueError:
            return None

    for pattern, order in ((_MONTH_DAY_PATTERN, "md"), (_DAY_MONTH_PATTERN, "dm")):
        match = pattern.search(query)
        if not match:
            continue
        if order == "md":
            month_token, day_token, year_token = match.group(1), match.group(2), match.group(3)
        else:
            day_token, month_token, year_token = match.group(1), match.group(2), match.group(3)

        month = _ALL_MONTH_TOKENS.get(month_token.lower())
        if not month:
            continue
        day = int(day_token)
        year = int(year_token) if year_token else _year_for_past_tolerant(today, month, day)
        try:
            return date(year, month, day).isoformat()
        except ValueError:
            # e.g. "February 31" - a real month name with an impossible day.
            return None
    return None


# ── Backward-looking weekday phrases (read queries about the past) ───────────
# Everything above resolves weekdays FORWARD, because apply-leave's dates must
# not land in the past. A read query is the opposite case: "why was X marked
# half-day this Monday?" is asking about a day that has already happened, and
# an attendance record cannot exist for one that has not.
#
# Deliberately a separate function rather than a flag on
# resolve_relative_date_phrase. allow_past there is only a GUARD - it rejects
# a result that already landed in the past, so it can never reach backwards:
# on Wednesday, "this Monday" resolves forward to next week's Monday, which
# is in the future, and the guard never fires. Weakening that resolver to
# look backwards would quietly remove the forward-only guarantee apply-leave
# relies on.

# "next <weekday>" is excluded on purpose - it is genuinely forward-looking
# and resolve_relative_date_phrase already owns it.
_PAST_WEEKDAY_PATTERN = re.compile(
    rf"\b(?:(this|last|past|previous)\s+)?(?:on\s+)?{_WD}\b", re.IGNORECASE
)
_FORWARD_WEEKDAY_MARKER = re.compile(
    rf"\b(next|coming|upcoming)\s+(?:week'?s?\s+)?{_WD}\b", re.IGNORECASE
)


def _start_of_week(anchor: date) -> date:
    """Monday of the calendar week containing anchor."""
    return anchor - timedelta(days=anchor.weekday())


def most_recent_weekday(anchor: date, target_weekday: int) -> date:
    """Nearest occurrence ON OR BEFORE anchor - the mirror of
    this_coming_weekday. Returns anchor itself when it is already the target."""
    return anchor - timedelta(days=(anchor.weekday() - target_weekday) % 7)


_WEEKDAY_OF_MONTH_TAIL = re.compile(
    r"\s+(?:of|in)\s+(?:the\s+)?(?:month\s+of\s+)?(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|"
    r"june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?|this\s+month|"
    r"next\s+month|last\s+month|previous\s+month)\b", re.IGNORECASE)


def resolve_past_weekday_phrase(query: str, today: date) -> Optional[ResolvedDate]:
    """A weekday named in a backward-looking query, as a ResolvedDate.

        this Monday   -> that weekday in the CURRENT calendar week
        last Monday   -> that weekday in the PREVIOUS calendar week
        on Monday     -> the most recent occurrence, at or before today
        Monday        -> same as "on Monday"

    Returns None when the query names no weekday, or names one with a
    forward marker ("next Monday", "coming Friday"), which
    resolve_relative_date_phrase resolves instead.

    "this Friday" on a Wednesday stays 'Friday of this week' even though
    that is still ahead - the phrase means the current week, and answering
    a different day would be a guess. The caller decides what to do with a
    future date; individual_report refuses it outright, since an attendance
    record cannot exist for a day that has not happened.
    """
    if _FORWARD_WEEKDAY_MARKER.search(query):
        return None

    match = _PAST_WEEKDAY_PATTERN.search(query)
    if not match:
        return None
    # "last Friday OF AUG" is the last Friday of that month - the ordinal
    # resolver's job - not last week's Friday. QA: it resolved to 18 Sep.
    if _WEEKDAY_OF_MONTH_TAIL.match(query[match.end():]):
        return None

    qualifier = (match.group(1) or "").lower()
    target = _WEEKDAYS[match.group(2).lower()]

    if qualifier == "this":
        resolved = _start_of_week(today) + timedelta(days=target)
    elif qualifier in ("last", "past", "previous"):
        resolved = _start_of_week(today) - timedelta(days=7 - target)
    else:
        resolved = most_recent_weekday(today, target)

    return {
        "from_date": resolved.isoformat(),
        "matched_phrase": match.group(0),
        "matched_kind": f"past_weekday:{qualifier or 'bare'}",
    }
