"""Regression tests for services/date_query_resolver.py — the shared
deterministic date-phrase resolver used by punch_details.py,
attendance.py, and attendance_explain.py.
"""
from datetime import date

import pytest

import services.date_query_resolver as dqr

TODAY = date(2026, 9, 4)  # Friday


def _resolve(query: str, today: date = TODAY):
    return dqr.resolve(query, today)


class TestBareNextMonthIsAFullMonthRangeNotCurrentMonth:
    """Confirmed live bug: bare "next month" (no ordinal weekday attached,
    e.g. "next month attendance") had no standalone handler at all — only
    "first Friday of next month"-style ordinal-weekday-scoped phrasing was
    recognized — so it fell all the way through to the LLM fallback, which
    answered the CURRENT month instead of the one actually asked about."""

    def test_bare_next_month(self):
        assert _resolve("next month attendance") == {
            "type": "range", "start_date": date(2026, 10, 1), "end_date": date(2026, 10, 31),
        }

    def test_bare_next_month_alternate_word_order(self):
        assert _resolve("attendance for next month") == {
            "type": "range", "start_date": date(2026, 10, 1), "end_date": date(2026, 10, 31),
        }

    def test_bare_next_month_december_rolls_year_forward(self):
        assert _resolve("next month attendance", date(2026, 12, 15)) == {
            "type": "range", "start_date": date(2027, 1, 1), "end_date": date(2027, 1, 31),
        }

    def test_ordinal_weekday_of_next_month_still_takes_priority(self):
        """"first Friday of next month" must still resolve to that single
        Friday, not be swallowed by the new bare "next month" handler."""
        assert _resolve("first friday of next month") == {
            "type": "single", "date": date(2026, 10, 2),
        }


class TestBarePreviousMonthUnaffectedByTheFix:
    """"previous month" is a synonym for "last month" — must keep resolving
    correctly alongside the new bare "next month" handler, not regress."""

    def test_previous_month(self):
        assert _resolve("previous month attendance") == {
            "type": "range", "start_date": date(2026, 8, 1), "end_date": date(2026, 8, 31),
        }


class TestConfigurableWeekStart:
    """week_start (default 0 = Monday, Python's own date.weekday()
    numbering) lets a caller honor a company/user's own configured
    week-start day for every week-boundary-anchored phrase — "this/last/
    next week", "last week to next week", "last week <weekday>", and bare
    "this <weekday>". TODAY is Friday 2026-09-04 throughout."""

    def test_default_week_start_is_unaffected_monday(self):
        """No week_start argument (or 0) must reproduce every pre-existing
        Monday-anchored result exactly — this is the regression guard for
        every caller that doesn't pass week_start at all."""
        assert _resolve("attendance for last week Sunday") == {
            "type": "single", "date": date(2026, 8, 30),
        }
        assert _resolve("attendance for this week") == {
            "type": "range", "start_date": date(2026, 8, 31), "end_date": TODAY,
        }

    def test_sunday_start_this_week(self):
        # Sunday-starting week containing Friday 9/4: Sun 8/30 - Sat 9/5,
        # truncated at today for "this_week"'s own existing convention.
        assert dqr.resolve("attendance for this week", TODAY, week_start=6) == {
            "type": "range", "start_date": date(2026, 8, 30), "end_date": TODAY,
        }

    def test_sunday_start_last_week(self):
        assert dqr.resolve("attendance for last week", TODAY, week_start=6) == {
            "type": "range", "start_date": date(2026, 8, 23), "end_date": date(2026, 8, 29),
        }

    def test_sunday_start_last_week_weekday(self):
        # Last Sunday-starting week is Aug 23 (Sun) - Aug 29 (Sat); its
        # own Sunday is the week's first day, its Wednesday the 4th.
        assert dqr.resolve("attendance for last week Sunday", TODAY, week_start=6) == {
            "type": "single", "date": date(2026, 8, 23),
        }
        assert dqr.resolve("attendance for last week Wednesday", TODAY, week_start=6) == {
            "type": "single", "date": date(2026, 8, 26),
        }

    def test_tuesday_start_this_week(self):
        # Tuesday-starting week containing Friday 9/4 begins Tue 9/1.
        assert dqr.resolve("attendance for this week", TODAY, week_start=1) == {
            "type": "range", "start_date": date(2026, 9, 1), "end_date": TODAY,
        }

    def test_tuesday_start_last_week_weekday(self):
        # Last Tuesday-starting week: Tue 8/25 - Mon 8/31 (Monday is its
        # LAST day, 6 days after the Tuesday it starts on).
        assert dqr.resolve("attendance for last week Monday", TODAY, week_start=1) == {
            "type": "single", "date": date(2026, 8, 31),
        }

    def test_bare_this_weekday_honors_week_start(self):
        # "this Sunday" under a Sunday-starting week (today=Friday, within
        # that week) means the Sunday that started THIS week, 5 days ago
        # — not the upcoming one 2 days ahead a Monday-start would imply.
        assert dqr.resolve("attendance for this sunday", TODAY, week_start=6) == {
            "type": "single", "date": date(2026, 8, 30),
        }


class TestRelativeAgoFamily:
    """Confirmed live bug: the whole BACKWARD-anchored count family ("one
    month ago", "2 weeks back", "3 days ago") had no matcher at all — the
    resolver only knew the forward-anchored "last N days"/"last N months"
    spellings — so every one of these phrases fell through the entire
    dispatcher unrecognized.

    TODAY here is Tuesday 2026-09-08, the day the bug was reported on, NOT
    the module-level Friday TODAY: the original report ("what was punch
    time on Friday one month ago?") depends on today NOT being a Friday to
    show the wrong answer at all."""

    REPORTED = date(2026, 9, 8)  # Tuesday

    def test_weekday_with_month_ago_is_not_the_most_recent_weekday(self):
        """The reported case. Before the fix this returned Fri 2026-09-04
        — the most recent Friday — because "one month ago" matched nothing
        and the bare-weekday matcher claimed the "friday" token on its
        own, silently discarding the qualifier."""
        assert _resolve("What was punch time on Friday one month ago?", self.REPORTED) == {
            "type": "single", "date": date(2026, 8, 7),
        }

    def test_weekday_ago_anchors_the_count_before_selecting_the_weekday(self):
        # Anchor = 2026-09-08 minus 2 calendar months = 2026-07-08 (a
        # Wednesday); the most recent Friday on or before it is 07-03.
        assert _resolve("friday 2 months ago", self.REPORTED) == {
            "type": "single", "date": date(2026, 7, 3),
        }

    def test_weekday_ago_accepts_back_as_a_synonym_for_ago(self):
        assert _resolve("friday a month back", self.REPORTED) == {
            "type": "single", "date": date(2026, 8, 7),
        }

    def test_weekday_a_week_ago_is_the_prior_calendar_weeks_weekday(self):
        # Anchor = 2026-09-01 (Tue); most recent Monday on or before it is
        # 08-31 — last week's Monday, not this week's.
        assert _resolve("monday one week ago", self.REPORTED) == {
            "type": "single", "date": date(2026, 8, 31),
        }

    def test_weekday_two_weeks_ago(self):
        # Anchor = 2026-08-25 (Tue); most recent Friday on or before = 08-21.
        assert _resolve("friday two weeks ago", self.REPORTED) == {
            "type": "single", "date": date(2026, 8, 21),
        }

    def test_weekday_ago_includes_the_anchor_day_itself(self):
        """Anchor 2026-09-01 is a Tuesday, so "tuesday a week ago" is that
        very day — the on-or-BEFORE rule is inclusive, matching
        weekday_retrospective's own convention for a bare weekday."""
        assert _resolve("tuesday a week ago", self.REPORTED) == {
            "type": "single", "date": date(2026, 9, 1),
        }

    def test_n_days_ago_is_a_single_day(self):
        assert _resolve("3 days ago", self.REPORTED) == {
            "type": "single", "date": date(2026, 9, 5),
        }

    def test_bare_month_ago_is_that_whole_calendar_month(self):
        """No weekday named — a whole-month RANGE, deliberately identical
        to "last month" rather than a silently-picked single day out of
        ~30. A single-day-only caller (punch_details) asks which day."""
        assert _resolve("one month ago", self.REPORTED) == {
            "type": "range", "start_date": date(2026, 8, 1), "end_date": date(2026, 8, 31),
        }

    def test_one_unit_ago_is_equivalent_to_last_unit(self):
        """The consistency guarantee the range choice above rests on."""
        for ago, last in [("one month ago", "last month"),
                          ("one week ago", "last week"),
                          ("a year ago", "last year")]:
            assert _resolve(ago, self.REPORTED) == _resolve(last, self.REPORTED), ago

    def test_two_months_ago_is_equivalent_to_last_to_last_month(self):
        assert _resolve("2 months ago", self.REPORTED) == _resolve("last to last month", self.REPORTED)

    def test_two_weeks_ago_is_that_whole_calendar_week(self):
        assert _resolve("2 weeks ago", self.REPORTED) == {
            "type": "range", "start_date": date(2026, 8, 24), "end_date": date(2026, 8, 30),
        }

    def test_bare_unit_with_no_count_means_one(self):
        assert _resolve("month back", self.REPORTED) == _resolve("last month", self.REPORTED)

    def test_month_arithmetic_clamps_the_day_to_a_real_date(self):
        """31 March minus one calendar month has no 31st to land on."""
        assert dqr.date_before(date(2026, 3, 31), 1, "month") == date(2026, 2, 28)

    def test_year_arithmetic_clamps_leap_day(self):
        assert dqr.date_before(date(2028, 2, 29), 1, "year") == date(2027, 2, 28)

    def test_month_ago_across_a_year_boundary(self):
        assert _resolve("friday 2 months ago", date(2026, 1, 15)) == {
            "type": "single", "date": date(2025, 11, 14),
        }


class TestCompoundRelativeAgo:
    """Confirmed live/reported: "missing punch 1 month 3 days ago" resolved
    to the SAME date as bare "3 days ago" — the "1 month" component was
    silently dropped entirely. _RELATIVE_AGO_PATTERN's own .search() found
    its first match starting at "3 days ago" (since "1 month" isn't
    directly followed by the ago-suffix, "3 days ago" is), so the coarser
    unit never even reached the resolver. Fixed by matching the two-unit
    shape as its own pattern, checked before the single-unit one, and
    chaining a second date_before() from the first anchor. TODAY here is
    Friday 2026-09-04, matching the rest of this file's default."""

    def test_month_and_days_chain_correctly(self):
        # 1 month before 09-04 is 08-04; 3 days before THAT is 08-01.
        assert _resolve("1 month 3 days ago") == {"type": "single", "date": date(2026, 8, 1)}

    def test_never_silently_drops_the_coarser_unit(self):
        """The exact live failure mode: the compound phrase must not
        resolve to the same date as its bare finer-unit tail alone."""
        assert _resolve("1 month 3 days ago") != _resolve("3 days ago")

    def test_realistic_reported_phrasing(self):
        assert _resolve("what was the reason for missing punch 1 month 3 days ago") == {
            "type": "single", "date": date(2026, 8, 1),
        }

    def test_weeks_and_days_chain_correctly(self):
        assert _resolve("2 weeks 1 day back") == {"type": "single", "date": date(2026, 8, 20)}

    def test_compound_with_a_weekday_chains_before_selecting_the_weekday(self):
        # Anchor after chaining (08-01) is a Saturday; most recent Friday
        # on or before it is 07-31.
        assert _resolve("friday 1 month 3 days ago") == {"type": "single", "date": date(2026, 7, 31)}

    def test_compound_always_resolves_a_single_day_never_a_range(self):
        """Unlike a bare "1 month ago" (a whole-month RANGE), a compound
        anchor is always pinned to one exact day."""
        result = _resolve("1 month 3 days ago")
        assert result["type"] == "single"

    def test_single_unit_phrasing_is_unaffected(self):
        assert _resolve("1 month ago") == {
            "type": "range", "start_date": date(2026, 8, 1), "end_date": date(2026, 8, 31),
        }
        assert _resolve("3 days ago") == {"type": "single", "date": date(2026, 9, 1)}


class TestVagueAgoQuantifierIsNeverGuessedAt:
    """A count too vague to resolve ("a few weeks ago", "a couple of
    months back") must return None so the caller's LLM fallback sees the
    query — NOT fall through to the bare-weekday matcher, which would
    answer the most recent occurrence of that weekday and silently discard
    the qualifier. Same choice the pre-existing unscoped-ordinal gate
    ("second friday") already makes."""

    REPORTED = date(2026, 9, 8)

    def test_few_weeks_ago_with_weekday(self):
        assert _resolve("friday a few weeks ago", self.REPORTED) is None

    def test_couple_of_months_back_with_weekday(self):
        assert _resolve("friday couple of months back", self.REPORTED) is None

    def test_vague_quantifier_without_weekday(self):
        assert _resolve("a few weeks ago", self.REPORTED) is None
        assert _resolve("several months ago", self.REPORTED) is None


class TestExistingDatePhrasingUnaffectedByTheAgoFamily:
    """The "ago" matcher runs before the bare-weekday/bare-month matchers,
    so every phrasing that already worked must keep resolving identically."""

    REPORTED = date(2026, 9, 8)

    def test_last_and_bare_weekday_unchanged(self):
        assert _resolve("last friday", self.REPORTED) == {"type": "single", "date": date(2026, 9, 4)}
        assert _resolve("friday", self.REPORTED) == {"type": "single", "date": date(2026, 9, 4)}
        assert _resolve("next monday", self.REPORTED) == {"type": "single", "date": date(2026, 9, 14)}

    def test_forward_anchored_counts_unchanged(self):
        assert _resolve("last 2 months", self.REPORTED) == {
            "type": "range", "start_date": date(2026, 7, 1), "end_date": date(2026, 8, 31),
        }
        assert _resolve("last 7 days", self.REPORTED) == {
            "type": "range", "start_date": date(2026, 9, 2), "end_date": date(2026, 9, 8),
        }

    def test_day_before_yesterday_still_owned_by_the_relative_day_matcher(self):
        """"day before" also matches the ago-suffix vocabulary, but
        _match_relative_day is checked far earlier in the dispatcher."""
        assert _resolve("day before yesterday", self.REPORTED) == {
            "type": "single", "date": date(2026, 9, 6),
        }

    def test_unscoped_ordinal_weekday_still_gated(self):
        assert _resolve("second friday", self.REPORTED) is None

    def test_ordinal_weekday_of_month_unchanged(self):
        assert _resolve("first friday of next month", self.REPORTED) == {
            "type": "single", "date": date(2026, 10, 2),
        }

    def test_back_alone_is_not_treated_as_a_date_qualifier(self):
        """"back" is far too common a word in ordinary attendance phrasing
        to gate on by itself — only a "back" directly following a time
        unit counts, so this must still resolve its weekday normally."""
        assert _resolve("when did I get back on friday", self.REPORTED) == {
            "type": "single", "date": date(2026, 9, 4),
        }


class TestUnicodeSeparatorsInExplicitDates:
    """Confirmed live/reported (2026-09-08): "why was i absent or present on
    10 – 08 – 2026" — typed with EN DASHES rather than ASCII hyphens —
    answered "which date between 01 Jan 2026 and 08 Sep 2026 would you
    like?". _NUMERIC_DATE_PATTERN is written against ASCII "-" and "/", so
    it never matched; the day and month were dropped entirely and only the
    trailing "2026" survived, via _match_bare_year, as a whole-YEAR range.

    A fully specified date silently widened to eight months because of one
    non-ASCII character — the same "confidently answered the wrong
    question" class as every other bug in this file."""

    REPORTED = date(2026, 9, 8)
    EXPECTED = {"type": "single", "date": date(2026, 8, 10)}

    @pytest.mark.parametrize("separator,name", [
        ("-", "ascii hyphen"),
        ("‐", "hyphen"),
        ("‑", "non-breaking hyphen"),
        ("‒", "figure dash"),
        ("–", "en dash"),          # the one confirmed live
        ("—", "em dash"),
        ("―", "horizontal bar"),
        ("−", "minus sign"),
        ("－", "fullwidth hyphen-minus"),
        ("/", "ascii slash"),
        ("∕", "division slash"),
        ("／", "fullwidth solidus"),
    ])
    def test_every_separator_form_resolves_to_the_same_single_day(self, separator, name):
        query = f"why was i absent or present on 10 {separator} 08 {separator} 2026 hw"
        assert _resolve(query, self.REPORTED) == self.EXPECTED, name

    def test_unspaced_unicode_separator(self):
        assert _resolve("attendance on 10–08–2026", self.REPORTED) == self.EXPECTED

    def test_non_breaking_spaces_around_the_separator(self):
        assert _resolve(
            "attendance on 10 – 08 – 2026", self.REPORTED,
        ) == self.EXPECTED

    def test_iso_form_with_unicode_dashes(self):
        assert _resolve("attendance on 2026–08–10", self.REPORTED) == self.EXPECTED

    def test_day_first_convention_survives_normalization(self):
        """10-08 is the 10th of August, never October 8th — normalization
        must not quietly change which component is the day."""
        assert _resolve("punch time 10–08–2026", self.REPORTED) == {
            "type": "single", "date": date(2026, 8, 10),
        }

    def test_an_invalid_date_is_still_reported_as_invalid(self):
        """Normalizing the separator must not turn an impossible date into
        a bare-year range either — it has its own answer."""
        result = _resolve("attendance on 31 – 02 – 2026", self.REPORTED)
        assert isinstance(result, dqr.InvalidExplicitDate)

    def test_a_genuine_bare_year_still_resolves_as_a_year(self):
        """The regression guard for the fix: "2026" with no day/month
        really is a whole-year range — that behavior must survive."""
        assert _resolve("attendance for 2026", self.REPORTED) == {
            "type": "range", "start_date": date(2026, 1, 1), "end_date": self.REPORTED,
        }

    def test_decimals_are_not_parsed_as_dates(self):
        """"." is deliberately NOT normalized into a date separator —
        "8.5 hours" must never become the 8th of May. Documents the
        deliberate limit of this fix."""
        assert _resolve("i worked 8.5 hours yesterday that day", self.REPORTED) == {
            "type": "single", "date": date(2026, 9, 7),
        }

    def test_normalize_separators_is_pure_text_substitution(self):
        """Same length, same offsets — it must not reflow the string, or
        every matcher's own \\b anchoring shifts underneath it."""
        original = "10 – 08 – 2026"
        normalized = dqr.normalize_separators(original)
        assert normalized == "10 - 08 - 2026"
        assert len(normalized) == len(original)
class TestNDaysAgoResolvesDeterministically:
    """Audit finding: "2 days ago" resolved to nothing here, AND
    punch_details' own _DATE_HINT_PATTERN doesn't match that phrasing either
    — so the LLM fallback never ran, the date stayed None, and erp-api's
    default (TODAY) answered a question about a different day with nothing
    indicating the date was never resolved. A silently wrong answer, not a
    visible failure.

    Shared module, so this covers punch_details, attendance and
    attendance_explain at once.
    """

    def test_digit_form(self):
        # TODAY is Friday 4 Sep; 2 days back is Wednesday 2 Sep.
        assert _resolve("punch details 2 days ago") == {
            "type": "single", "date": date(2026, 9, 2),
        }

    def test_word_form(self):
        assert _resolve("punch details two days ago") == {
            "type": "single", "date": date(2026, 9, 2),
        }

    def test_back_and_earlier_synonyms(self):
        for phrasing in ("5 days back", "5 days earlier"):
            assert _resolve("attendance %s" % phrasing) == {
                "type": "single", "date": date(2026, 8, 30),
            }, phrasing

    def test_multi_digit(self):
        assert _resolve("attendance 10 days ago") == {
            "type": "single", "date": date(2026, 8, 25),
        }

    # ── Negative controls — the pattern is deliberately narrow ──────────────

    def test_last_n_days_is_still_a_range(self):
        """"last 3 days" is a RANGE and must not be re-read as a single day."""
        assert _resolve("attendance last 3 days") == {
            "type": "range", "start_date": date(2026, 9, 2), "end_date": TODAY,
        }

    def test_a_duration_is_not_a_date(self):
        """"3 days leave" is a length, not a day — it must not resolve."""
        assert _resolve("apply 3 days leave") is None
        assert _resolve("apply 2 days leave") is None

    def test_day_before_yesterday_is_untouched(self):
        """Already handled by the relative-day pattern; the new one excludes
        "before" precisely so it cannot double-match here."""
        assert _resolve("attendance day before yesterday") == {
            "type": "single", "date": date(2026, 9, 2),
        }

    def test_plain_relative_words_are_untouched(self):
        assert _resolve("attendance yesterday") == {"type": "single", "date": date(2026, 9, 3)}
        assert _resolve("attendance today") == {"type": "single", "date": TODAY}


class TestBareNumeralOrdinalWeekdayOfMonth:
    """Confirmed live/reported: "2 Thursday of August" (a bare numeral, no
    "nd"/"rd"/"th" suffix — a common shorthand for "2nd Thursday of
    August") matched nothing in ORDINAL_WEEKDAY_WORDS, so the ordinal
    matcher returned None and the query fell all the way through to the
    bare-weekday matcher at the end of the dispatcher. That matcher
    discarded both the ordinal and "of August" entirely and resolved to
    the most recent Thursday relative to TODAY instead — asked on a
    Thursday, it silently answered TODAY'S own date."""

    def test_bare_numeral_ordinal_resolves_like_its_suffixed_form(self):
        assert _resolve("why was I late on 2 Thursday of August") == \
            _resolve("why was I late on 2nd Thursday of August") == \
            {"type": "single", "date": date(2026, 8, 13)}

    def test_bare_numeral_does_not_default_to_today(self):
        result = _resolve("why was I late on 2 Thursday of August")
        assert result != {"type": "single", "date": TODAY}

    def test_other_bare_numerals_also_work(self):
        assert _resolve("first friday of august") == _resolve("1 friday of august")
        assert _resolve("third monday of august") == _resolve("3 monday of august")

    def test_no_such_ordinal_weekday_still_reported_for_bare_numeral(self):
        result = _resolve("5 wednesday of august")
        assert isinstance(result, dqr.NoSuchOrdinalWeekday)

    def test_unrelated_bare_numbers_next_to_a_weekday_word_unaffected(self):
        """A bare number is only ever read as an ordinal when it sits
        immediately before a weekday name — these phrasings, where the
        number belongs to something else, must keep resolving exactly as
        before."""
        assert _resolve("last 2 Tuesdays") == {
            "type": "multiple", "dates": [date(2026, 8, 25), date(2026, 9, 1)],
        }
        assert _resolve("2 days ago") == {"type": "single", "date": date(2026, 9, 2)}


class TestBareOrdinalDayOfMonth:
    """Confirmed live/reported: "explain my attendance for 5th" (a bare
    ordinal day-of-month, no month name attached) matched nothing in this
    module at all, so it fell through to the caller's own LLM date
    extraction, which had no rule for this shape either and guessed
    inconsistently — including, on at least one run, misreading the lone
    "5" as BOTH the day and the month ("05-05" -> 5th of May), a date with
    no relation to what was actually asked. TODAY = Friday 2026-09-04."""

    def test_day_already_passed_this_month_resolves_within_this_month(self):
        assert _resolve("why was I absent on the 3rd") == {
            "type": "single", "date": date(2026, 9, 3),
        }

    def test_day_not_yet_reached_this_month_falls_back_to_last_month(self):
        """The 5th hasn't happened yet this month (today is only the 4th),
        and attendance is never asked about a future day, so this must
        mean last month's 5th, not this month's."""
        assert _resolve("explain my attendance for 5th") == {
            "type": "single", "date": date(2026, 8, 5),
        }

    def test_never_misreads_the_bare_number_as_a_month(self):
        """The exact live failure mode: the resolved date must never be
        the 5th of MAY just because "5" also looks like a month number."""
        result = _resolve("explain my attendance for 5th")
        assert result != {"type": "single", "date": date(2026, 5, 5)}

    def test_day_out_of_range_for_last_month_is_clamped(self):
        """"31st" asked when this month hasn't reached the 31st yet falls
        back to last month, which may not have 31 days — clamp instead of
        raising."""
        assert _resolve("why was I late on 31st") == {
            "type": "single", "date": date(2026, 8, 31),
        }

    def test_a_month_name_still_takes_priority_unchanged(self):
        """"5th august" is already unambiguous and handled by the explicit-
        date matcher — this new bare-day matcher must never override it."""
        assert _resolve("attendance for 5th august") == {
            "type": "single", "date": date(2026, 8, 5),
        }

    def test_an_explicit_month_qualifier_is_left_to_existing_behavior(self):
        """"5th of last month" already names a month via "last month" —
        left to whatever this file already does for that qualifier,
        deliberately not claimed by the new bare-day matcher."""
        assert _resolve("5th of last month") == {
            "type": "range", "start_date": date(2026, 8, 1), "end_date": date(2026, 8, 31),
        }

    def test_a_weekday_named_alongside_the_day_is_left_to_existing_behavior(self):
        """"friday 5th" names both a weekday and a day-of-month — genuinely
        ambiguous, so left to the existing bare-weekday resolution rather
        than claimed by the new matcher."""
        assert _resolve("friday 5th") == {"type": "single", "date": date(2026, 9, 4)}


class TestNumericDateYearSplitByWhitespace:
    """Confirmed live/reported: "why was attendance status for the
    21 - 08 - 20 26" (a stray space landing inside the year — from chat-UI
    line wrapping, a copy-paste artifact, or similar) resolved to
    2020-08-21 instead of 2026-08-21. _NUMERIC_DATE_PATTERN's year group
    was a plain \\d{2,4}, which can only match contiguous digits — hitting
    the space after "20" stopped it there, and a 2-digit year silently
    gets +2000 added, so "20" quietly became 2020 rather than being
    rejected or completed to 2026."""

    def test_space_split_year_after_dashes(self):
        assert _resolve("why was attendance status for the 21 - 08 - 20 26") == {
            "type": "single", "date": date(2026, 8, 21),
        }

    def test_space_split_year_tight_dashes(self):
        assert _resolve("21-08-20 26") == {"type": "single", "date": date(2026, 8, 21)}

    def test_ordinary_contiguous_year_is_unaffected(self):
        assert _resolve("21-08-2026") == {"type": "single", "date": date(2026, 8, 21)}
        assert _resolve("21 - 08 - 2026") == {"type": "single", "date": date(2026, 8, 21)}

    def test_genuine_two_digit_year_is_unaffected(self):
        assert _resolve("21-08-26") == {"type": "single", "date": date(2026, 8, 21)}


class TestSpelledOutOrdinalDayOfMonth:
    """Confirmed live/reported: "explain my attendance for fourth" (and its
    common misspelling "foruth") matched nothing at all — only the numeral
    form ("4th") was recognized by _BARE_ORDINAL_DAY_PATTERN, so a
    spelled-out ordinal word fell all the way through to the LLM fallback
    with no rule for this shape."""

    def test_spelled_out_ordinal_resolves_like_its_numeral_form(self):
        assert _resolve("explain my attendance for fourth") == {
            "type": "single", "date": date(2026, 9, 4),
        }

    @pytest.mark.parametrize("query,day", [
        ("explain my attendance for foruth", 4),   # transposed letters
        ("attendance for fith", 5),                 # deleted letter
        ("attendance for sxth", 6),                  # deleted letter
        ("attendance for frist", 1),                 # transposed letters
    ])
    def test_common_misspellings_still_resolve(self, query, day):
        # today is 2026-09-04: a day already reached this month resolves
        # within September, otherwise it falls back to August.
        expected_date = date(2026, 9, day) if day <= 4 else date(2026, 8, day)
        assert _resolve(query) == {"type": "single", "date": expected_date}

    @pytest.mark.parametrize("query", [
        "attendance for twenty first",
        "attendance for twenty-first",
        "attendance for twenty 1st",
        "attendance for twenty-1st",
    ])
    def test_twenty_something_compound_forms_all_agree(self, query):
        # The word form, the hyphenated word form, and the mixed
        # word-tens + numeral-ones form ("twenty 1st") must all resolve
        # identically — confirmed while building this fix: "twenty 1st"
        # was silently resolving to the 1st of the month, because the
        # plain numeral ordinal pattern matched "1st" on its own before the
        # "twenty" tens part was ever considered.
        assert _resolve(query) == {"type": "single", "date": date(2026, 8, 21)}

    @pytest.mark.parametrize("query", [
        "attendance for thirty first",
        "attendance for thirty 1st",
    ])
    def test_thirty_first_compound_forms_agree(self, query):
        assert _resolve(query) == {"type": "single", "date": date(2026, 8, 31)}

    def test_bare_cardinal_twenty_one_is_not_treated_as_a_day(self):
        # No ordinal marker anywhere ("twenty one", not "twenty-first" or
        # "twenty 1st") — deliberately left unresolved, the same rule
        # _BARE_ORDINAL_DAY_PATTERN already applies to a bare numeral
        # ("21" alone is never a day reference, only "21st" is). Without
        # this, an unrelated count ("twenty one employees are absent")
        # would risk being misread as a date.
        assert _resolve("attendance for twenty one") is None

    def test_ordinal_weekday_of_month_still_takes_priority_unchanged(self):
        # "fourth Wednesday of august" must still resolve as the ordinal
        # WEEKDAY-of-month feature, never as a bare day-of-month=4 — the
        # weekday guard inside _match_bare_ordinal_day_of_month exists
        # for exactly this, and this new spelled-out-word path must not
        # bypass it.
        assert _resolve("attendance for fourth wednesday of august") == {
            "type": "single", "date": date(2026, 8, 26),
        }

    def test_explicit_month_qualifier_still_takes_priority_unchanged(self):
        assert _resolve("attendance for fourth of last month") == {
            "type": "range", "start_date": date(2026, 8, 1), "end_date": date(2026, 8, 31),
        }
