"""
Pure unit tests for services/date_resolver.py — no mocking needed, every
function takes `today` explicitly. Reference dates deliberately span a
Monday, a Sunday, and a mid-week Wednesday so the "today is itself the
target weekday" edge cases are exercised, not just the common case.
"""

from datetime import date, timedelta

import pytest

from services import date_resolver as dr

MONDAY = date(2026, 8, 24)      # a Monday
SUNDAY = date(2026, 8, 23)      # a Sunday
WEDNESDAY = date(2026, 8, 19)   # a mid-week Wednesday

_REFERENCE_DATES = [MONDAY, SUNDAY, WEDNESDAY]


class TestDateMathPrimitives:

    def test_this_coming_weekday_returns_today_when_today_is_target_weekday(self):
        assert dr.this_coming_weekday(MONDAY, 0) == MONDAY

    def test_this_coming_weekday_returns_upcoming_occurrence_from_midweek(self):
        # Wednesday -> next Monday is 5 days away.
        assert dr.this_coming_weekday(WEDNESDAY, 0) == date(2026, 8, 24)

    def test_this_coming_weekday_returns_upcoming_occurrence_from_sunday(self):
        # Sunday -> Monday is tomorrow.
        assert dr.this_coming_weekday(SUNDAY, 0) == date(2026, 8, 24)

    def test_next_weekday_strict_never_returns_today_even_when_today_is_target_weekday(self):
        assert dr.next_weekday_strict(MONDAY, 0) == MONDAY + timedelta(days=7)

    def test_next_weekday_strict_from_midweek_reference(self):
        assert dr.next_weekday_strict(WEDNESDAY, 0) == date(2026, 8, 24)

    def test_next_weekday_strict_from_sunday_reference(self):
        assert dr.next_weekday_strict(SUNDAY, 0) == date(2026, 8, 24)

    def test_weekday_of_next_calendar_week_from_monday_reference(self):
        # 2026-08-24 is a Monday; next calendar week's Thursday is 2026-09-03
        # (NOT 2026-08-27, which is still this same week — see next_weekday_
        # strict's own Thursday result for the contrast).
        assert dr.weekday_of_next_calendar_week(MONDAY, 3) == date(2026, 9, 3)

    def test_weekday_of_next_calendar_week_from_midweek_reference(self):
        # 2026-08-19 is a Wednesday, in the Mon-Sun week of Aug 17-23. Next
        # calendar week is Aug 24-30; its Thursday is 2026-08-27.
        assert dr.weekday_of_next_calendar_week(WEDNESDAY, 3) == date(2026, 8, 27)

    @pytest.mark.parametrize("today", _REFERENCE_DATES)
    def test_weekday_of_next_calendar_week_never_lands_within_todays_own_week(self, today):
        monday_this_week = today - timedelta(days=today.weekday())
        result = dr.weekday_of_next_calendar_week(today, 3)  # Thursday
        assert result >= monday_this_week + timedelta(weeks=1)
        assert result < monday_this_week + timedelta(weeks=2)

    @pytest.mark.parametrize("today", _REFERENCE_DATES)
    def test_next_to_next_weekday_is_exactly_one_week_after_next_weekday_strict(self, today):
        assert dr.next_to_next_weekday(today, 0) == dr.next_weekday_strict(today, 0) + timedelta(days=7)

    def test_week_after_next_from_monday_reference(self):
        assert dr.week_after_next(MONDAY) == date(2026, 9, 7)

    def test_week_after_next_from_midweek_reference_lands_on_a_monday(self):
        result = dr.week_after_next(WEDNESDAY)
        assert result.weekday() == 0
        assert result == date(2026, 8, 31)

    def test_week_after_next_from_sunday_reference(self):
        result = dr.week_after_next(SUNDAY)
        assert result.weekday() == 0
        assert result == date(2026, 8, 31)

    def test_first_of_next_month_handles_ordinary_month_rollover(self):
        assert dr.first_of_next_month(date(2026, 8, 21)) == date(2026, 9, 1)

    def test_first_of_next_month_handles_december_to_january_year_rollover(self):
        assert dr.first_of_next_month(date(2026, 12, 15)) == date(2027, 1, 1)

    def test_first_weekday_of_next_month_when_the_1st_is_itself_the_target_weekday(self):
        # 2026-09-01 is a Tuesday.
        assert dr.first_weekday_of_next_month(date(2026, 8, 21), 1) == date(2026, 9, 1)

    def test_first_weekday_of_next_month_when_the_1st_is_not_the_target_weekday(self):
        # 2026-09-01 is a Tuesday; first Friday of September 2026 is 2026-09-04.
        assert dr.first_weekday_of_next_month(date(2026, 8, 21), 4) == date(2026, 9, 4)

    def test_nth_weekday_of_next_month_matches_nth_weekday_of_month_on_the_right_month(self):
        # September 2026: Wednesdays fall on 2, 9, 16, 23, 30.
        assert dr.nth_weekday_of_next_month(date(2026, 8, 21), 2, 2) == date(2026, 9, 9)

    def test_nth_weekday_of_next_month_returns_none_for_a_nonexistent_5th_occurrence(self):
        # September 2026 has only 4 Fridays (4, 11, 18, 25) — no 5th.
        assert dr.nth_weekday_of_next_month(date(2026, 8, 21), 4, 5) is None

    def test_last_weekday_of_next_month(self):
        # Last Wednesday of September 2026 is 2026-09-30.
        assert dr.last_weekday_of_next_month(date(2026, 8, 21), 2) == date(2026, 9, 30)


class TestResolveNextMonthWeekdayPhrase:
    """Live bug: 'next month of first friday' / 'next month's second
    wednesday' — word orders/connectors first_weekday_of_next_month's own
    regex never covered — fell all the way through to the unrelated bare
    'next month' pattern, silently discarding the weekday and resolving to
    just the 1st. resolve_next_month_weekday_phrase covers every ordinal
    (not just 'first') in every supported word order."""

    def test_ordinal_weekday_of_next_month(self):
        result = dr.resolve_next_month_weekday_phrase("first friday of next month", date(2026, 8, 24))
        assert result["from_date"] == "2026-09-04"

    def test_next_month_apostrophe_s_ordinal_weekday(self):
        result = dr.resolve_next_month_weekday_phrase("next month's second wednesday", date(2026, 8, 24))
        assert result["from_date"] == "2026-09-09"

    def test_next_month_bare_ordinal_weekday_no_connector(self):
        result = dr.resolve_next_month_weekday_phrase("next month second wednesday", date(2026, 8, 24))
        assert result["from_date"] == "2026-09-09"

    def test_next_month_of_ordinal_weekday(self):
        # The exact live bug report's phrasing.
        result = dr.resolve_next_month_weekday_phrase(
            "apply leave for in the next month of first friday reason is sick leave", date(2026, 8, 24),
        )
        assert result["from_date"] == "2026-09-04"

    def test_last_ordinal_supported(self):
        result = dr.resolve_next_month_weekday_phrase("last wednesday of next month", date(2026, 8, 24))
        assert result["from_date"] == "2026-09-30"

    def test_no_match_for_bare_next_month_alone(self):
        assert dr.resolve_next_month_weekday_phrase("apply leave next month", date(2026, 8, 24)) is None

    def test_no_match_for_unrecognized_weekday_typo(self):
        # "webnesday" — the exact live bug's typo — must not fuzzy-match.
        assert dr.resolve_next_month_weekday_phrase(
            "next month first week webnesday", date(2026, 8, 24),
        ) is None

    def test_no_match_for_first_week_without_a_weekday(self):
        assert dr.resolve_next_month_weekday_phrase("first week of next month", date(2026, 8, 24)) is None

    def test_no_match_for_next_to_next_month(self):
        # Live bug, found by mining real production queries: "next to next
        # month first friday" matched via embedded substring ("next month
        # first friday" found inside the larger phrase), silently dropping
        # the "to next" doubling and resolving against the WRONG month
        # (next month instead of the month after next). "next to next
        # month" has no tier-1 support at all (only weekdays have a
        # next_to_next construct) — must decline so the caller falls
        # through to tier 2, which does have month_offset=2 support.
        assert dr.resolve_next_month_weekday_phrase(
            "apply leave for next to next month first friday", date(2026, 8, 24),
        ) is None


class TestResolveWeekOfNextMonthPhrase:
    """Live bug, found by mining real production queries (not a single
    report — the same underlying concept was retried at least 7 times
    across different word orders): 'next month first week wednesday' /
    'monday in next month first week' / 'wednesday in the second week of
    next month' matched no deterministic pattern at all — only bare
    'next_month' matched, which is deliberately discarded elsewhere as
    ambiguous. 'next month's Nth week, narrowed to a weekday' is exactly
    as well-defined as the already-supported 'first week of November',
    just anchored to 'next month' instead of a named one."""

    TODAY = date(2026, 8, 24)  # a Monday; September 2026's 1st is a Tuesday

    def test_ordinal_week_of_next_month_word_order(self):
        span = dr.resolve_week_of_next_month_phrase("first week of next month", self.TODAY)
        assert span == (date(2026, 9, 1), date(2026, 9, 7))

    def test_next_month_ordinal_week_word_order(self):
        span = dr.resolve_week_of_next_month_phrase("next month first week", self.TODAY)
        assert span == (date(2026, 9, 1), date(2026, 9, 7))

    def test_next_month_apostrophe_s_ordinal_week(self):
        span = dr.resolve_week_of_next_month_phrase("next month's second week", self.TODAY)
        assert span == (date(2026, 9, 8), date(2026, 9, 14))

    def test_third_week_of_next_month(self):
        span = dr.resolve_week_of_next_month_phrase("third week of next month", self.TODAY)
        assert span == (date(2026, 9, 15), date(2026, 9, 21))

    def test_last_week_of_next_month(self):
        span = dr.resolve_week_of_next_month_phrase("last week of next month", self.TODAY)
        assert span == (date(2026, 9, 24), date(2026, 9, 30))

    def test_december_to_january_year_rollover(self):
        span = dr.resolve_week_of_next_month_phrase("first week of next month", date(2026, 12, 15))
        assert span == (date(2027, 1, 1), date(2027, 1, 7))

    def test_no_match_for_bare_next_month_alone(self):
        assert dr.resolve_week_of_next_month_phrase("apply leave next month", self.TODAY) is None

    def test_no_match_for_this_month_variant(self):
        assert dr.resolve_week_of_next_month_phrase("first week of this month", self.TODAY) is None

    def test_no_match_for_next_to_next_month(self):
        # Same collision as resolve_next_month_weekday_phrase's own guard:
        # "next to next month first week" matched via embedded substring
        # and silently resolved against the wrong month. Must decline so
        # the caller falls through to tier 2 (month_offset=2 support).
        assert dr.resolve_week_of_next_month_phrase(
            "apply leave for next to next month first week", self.TODAY,
        ) is None

    def test_full_real_phrasings_resolve_and_narrow_to_the_named_weekday(self):
        # Exact real phrasings from production, combined with weekday_
        # within_span the same way hr_graph._apply_deterministic_date_
        # overrides wires them together.
        cases = [
            ("apply leave for next month first week wednesday", "2026-09-02"),
            ("apply leave for the next month first week monday", "2026-09-07"),
            ("Apply casual leave for next month third week friday", "2026-09-18"),
            ("please apply sick for monday in next month first week", "2026-09-07"),
            ("please apply sick leave for Monday in the second week of next month", "2026-09-14"),
            ("Apply leave for wednesday in the second week of next month", "2026-09-09"),
        ]
        for query, expected in cases:
            span = dr.resolve_week_of_next_month_phrase(query, self.TODAY)
            assert span is not None, query
            narrowed = dr.weekday_within_span(query, span[0], span[1])
            assert narrowed is not None, query
            assert narrowed["from_date"] == expected, query


class TestResolveThisMonthWeekdayPhrase:
    """Live bug: 'last monday this month' had no pattern at all — fell to
    the LLM, which gave a DIFFERENT wrong answer on every call for the
    identical query (2026-08-22 then 2026-08-15, one minute apart).
    resolve_this_month_weekday_phrase mirrors resolve_next_month_weekday_
    phrase but anchored to the current month."""

    def test_last_ordinal_this_month(self):
        # August 2026 Mondays: 3, 10, 17, 24, 31 — last is 2026-08-31.
        result = dr.resolve_this_month_weekday_phrase("last monday this month", date(2026, 8, 24))
        assert result["from_date"] == "2026-08-31"

    def test_numbered_ordinal_this_month(self):
        # August 2026 Wednesdays: 5, 12, 19, 26 — second is 2026-08-12.
        result = dr.resolve_this_month_weekday_phrase("second wednesday this month", date(2026, 8, 1))
        assert result["from_date"] == "2026-08-12"

    def test_this_month_apostrophe_s_ordinal_weekday(self):
        result = dr.resolve_this_month_weekday_phrase("this month's last wednesday", date(2026, 8, 1))
        assert result["from_date"] == "2026-08-26"

    def test_of_this_month_connector(self):
        result = dr.resolve_this_month_weekday_phrase("last wednesday of this month", date(2026, 8, 1))
        assert result["from_date"] == "2026-08-26"

    def test_current_month_is_a_synonym_for_this_month(self):
        # Live bug, found by mining real production queries: "current
        # month" (not "this month") matched no pattern at all — only
        # _THIS_WEEK_WEEKDAY_PATTERN treated "current" as a synonym for
        # "this", this pattern didn't.
        result = dr.resolve_this_month_weekday_phrase("last wednesday of current month", date(2026, 8, 24))
        assert result["from_date"] == "2026-08-26"
        result2 = dr.resolve_this_month_weekday_phrase("last saturday of current month", date(2026, 8, 24))
        assert result2["from_date"] == "2026-08-29"

    def test_resolved_date_before_today_returns_none_by_default(self):
        # September 2026 Mondays: 7, 14, 21, 28 — last is 2026-09-28, which
        # is BEFORE today (2026-09-29) here. The phrase is recognized but
        # declined, same contract as resolve_relative_date_phrase's
        # "yesterday" handling.
        assert dr.resolve_this_month_weekday_phrase("last monday this month", date(2026, 9, 29)) is None

    def test_allow_past_true_returns_the_past_date_anyway(self):
        result = dr.resolve_this_month_weekday_phrase(
            "last monday this month", date(2026, 9, 29), allow_past=True,
        )
        assert result["from_date"] == "2026-09-28"

    def test_no_match_for_bare_this_month_alone(self):
        assert dr.resolve_this_month_weekday_phrase("apply leave this month", date(2026, 8, 24)) is None


class TestResolveThisWeekWeekdayPhrase:
    """Live bug: 'Monday of current week', asked on a Tuesday (this week's
    Monday is chronologically yesterday relative to today) — a genuinely
    different concept from 'this Monday' (this_coming_weekday, which always
    searches forward from today and would never mean a day already passed
    within the week). No pattern existed for "anchor to the week boundary,
    not the search direction", so it fell to the LLM's structured
    extraction — which had no way to represent it either and hallucinated
    an unrelated date that wasn't even a Monday."""

    TUESDAY = date(2026, 8, 25)  # this week's Monday (Aug 24) is yesterday

    def test_weekday_of_current_week_already_passed_still_resolves_to_the_real_date(self):
        result = dr.resolve_this_week_weekday_phrase(
            "monday of current week", self.TUESDAY, allow_past=True,
        )
        assert result["from_date"] == "2026-08-24"

    def test_declines_a_past_result_by_default(self):
        # Same contract as every other resolver here — apply-leave callers
        # must not silently get a past date back.
        assert dr.resolve_this_week_weekday_phrase("monday of current week", self.TUESDAY) is None

    def test_weekday_of_this_week_still_ahead_resolves_normally(self):
        # Asked on a Tuesday, this week's Friday hasn't passed yet.
        result = dr.resolve_this_week_weekday_phrase("friday of this week", self.TUESDAY)
        assert result["from_date"] == "2026-08-28"

    def test_this_week_apostrophe_s_word_order(self):
        result = dr.resolve_this_week_weekday_phrase("this week's friday", self.TUESDAY)
        assert result["from_date"] == "2026-08-28"

    def test_this_week_bare_word_order_no_connector(self):
        result = dr.resolve_this_week_weekday_phrase("this week friday", self.TUESDAY)
        assert result["from_date"] == "2026-08-28"

    def test_current_week_word_order(self):
        result = dr.resolve_this_week_weekday_phrase("friday of the current week", self.TUESDAY)
        assert result["from_date"] == "2026-08-28"

    def test_today_itself_resolves_to_today(self):
        # Asked ON a Monday, "Monday of current week" is today itself —
        # not in the past, so no allow_past needed.
        result = dr.resolve_this_week_weekday_phrase("monday of current week", MONDAY)
        assert result["from_date"] == MONDAY.isoformat()

    def test_no_match_for_bare_this_week_alone(self):
        assert dr.resolve_this_week_weekday_phrase("apply leave this week", self.TUESDAY) is None

    def test_no_match_for_unrecognized_weekday_typo(self):
        assert dr.resolve_this_week_weekday_phrase("mondey of current week", self.TUESDAY) is None

    def test_no_match_for_unrecognized_weekday_typo(self):
        assert dr.resolve_this_month_weekday_phrase("last webnesday this month", date(2026, 8, 24)) is None


class TestResolveMonthAndWeekWeekdayRangePhrases:
    """Live bug (found via audit, not yet reported): resolve_next_month_
    weekday_phrase/resolve_this_month_weekday_phrase/resolve_this_week_
    weekday_phrase each did a plain first-match .search() with no range-
    aware counterpart — the exact bug shape resolve_date_range_phrase and
    resolve_relative_date_range_phrase were already built to fix for their
    own phrase families, just never extended to these three. A two-sided
    range using their phrasing silently collapsed to just the first
    endpoint, discarding the second entirely."""

    def test_this_week_monday_to_friday(self):
        result = dr.resolve_this_week_weekday_range_phrase(
            "apply leave monday of this week to friday of this week", MONDAY,
        )
        assert result is not None
        first, second = result
        assert first["from_date"] == MONDAY.isoformat()
        assert second is not None
        assert second["from_date"] == (MONDAY + timedelta(days=4)).isoformat()

    def test_next_month_first_friday_to_last_friday(self):
        result = dr.resolve_next_month_weekday_range_phrase(
            "first friday of next month to last friday of next month", date(2026, 8, 24),
        )
        assert result is not None
        first, second = result
        assert first["from_date"] == "2026-09-04"
        assert second is not None
        assert second["from_date"] == "2026-09-25"

    def test_this_month_last_monday_to_last_friday(self):
        result = dr.resolve_this_month_weekday_range_phrase(
            "last monday this month to last friday this month", date(2026, 8, 1),
        )
        assert result is not None
        first, second = result
        # August 2026: last Monday is the 31st, last Friday is the 28th —
        # the SECOND anchor resolves independently against today, not
        # relative to the first, so an inversion here is expected and must
        # be dropped, not silently reordered.
        assert date.fromisoformat(first["from_date"]) == date(2026, 8, 31)
        assert second is None

    def test_this_month_first_monday_to_last_friday_forward_order(self):
        result = dr.resolve_this_month_weekday_range_phrase(
            "first monday this month to last friday this month", date(2026, 8, 1),
        )
        assert result is not None
        first, second = result
        assert first["from_date"] == "2026-08-03"
        assert second is not None
        assert second["from_date"] == "2026-08-28"

    def test_single_match_still_returns_second_none(self):
        result = dr.resolve_this_week_weekday_range_phrase("friday of this week", MONDAY)
        assert result is not None
        assert result[1] is None

    def test_no_match_returns_none(self):
        assert dr.resolve_this_week_weekday_range_phrase("apply casual leave tomorrow", MONDAY) is None

    def test_first_anchor_in_the_past_returns_none(self):
        # Same past-date-guard contract as the single-match resolvers —
        # not just carried over for the first endpoint, the whole range.
        wednesday = date(2026, 8, 26)
        assert dr.resolve_this_week_weekday_range_phrase(
            "monday of this week to friday of this week", wednesday,
        ) is None


class TestResolveRelativeDatePhrase:

    def test_resolves_today(self):
        result = dr.resolve_relative_date_phrase("apply leave today", WEDNESDAY)
        assert result["from_date"] == WEDNESDAY.isoformat()

    def test_resolves_tomorrow(self):
        result = dr.resolve_relative_date_phrase("apply leave tomorrow", WEDNESDAY)
        assert result["from_date"] == "2026-08-20"

    def test_resolves_day_after_tomorrow(self):
        result = dr.resolve_relative_date_phrase("apply leave day after tomorrow", WEDNESDAY)
        assert result["from_date"] == "2026-08-21"

    @pytest.mark.parametrize("phrase", [
        "this Monday", "this coming Monday", "coming Monday", "upcoming Monday",
    ])
    def test_resolves_this_monday_synonyms(self, phrase):
        result = dr.resolve_relative_date_phrase(f"apply leave {phrase}", WEDNESDAY)
        assert result["from_date"] == "2026-08-24"

    def test_resolves_next_monday(self):
        result = dr.resolve_relative_date_phrase("apply leave next Monday", WEDNESDAY)
        assert result["from_date"] == "2026-08-24"

    @pytest.mark.parametrize("today", _REFERENCE_DATES)
    def test_next_monday_and_next_week_monday_coincide_only_because_monday_starts_the_week(self, today):
        # Monday is a special case, not proof of a general equivalence: it's
        # the FIRST day of the ISO week, so "nearest Monday strictly after
        # today" and "the Monday of next calendar week" land on the same
        # date for any anchor. See test_next_thursday_and_next_week_thursday_
        # diverge_from_a_monday_anchor below for the actual (previously
        # mishandled) general case.
        a = dr.resolve_relative_date_phrase("apply leave next Monday", today)
        b = dr.resolve_relative_date_phrase("apply leave next week Monday", today)
        assert a["from_date"] == b["from_date"]

    def test_next_thursday_and_next_week_thursday_diverge_from_a_monday_anchor(self):
        # Live bug: "next week Thursday" used to be aliased to bare "next
        # Thursday" — asked on a Monday, that landed on the Thursday only 3
        # days away (still THIS calendar week), not the Thursday of the
        # following week a user actually means by "next week Thursday".
        next_thursday = dr.resolve_relative_date_phrase("apply leave next Thursday", MONDAY)
        next_week_thursday = dr.resolve_relative_date_phrase("apply leave next week Thursday", MONDAY)
        assert next_thursday["from_date"] == "2026-08-27"       # this week's Thursday
        assert next_week_thursday["from_date"] == "2026-09-03"  # next calendar week's Thursday
        assert next_thursday["from_date"] != next_week_thursday["from_date"]

    def test_upcoming_week_weekday_matches_the_same_construct_as_next_week(self):
        # Live bug: "apply casual leave for upcoming week friday" matched
        # no _PATTERNS entry at all (the trigger regex only recognized
        # literal "next week <weekday>") — fell through to tier 2, which
        # collapsed it to plain "upcoming Friday" and silently returned
        # THIS week's Friday (2026-08-28) instead of the actual upcoming
        # calendar week's Friday (2026-09-04). "upcoming"/"coming" must be
        # synonyms for "next" here, same as everywhere else in this module.
        wednesday = date(2026, 8, 26)
        upcoming = dr.resolve_relative_date_phrase("apply casual leave for upcoming week friday", wednesday)
        coming = dr.resolve_relative_date_phrase("apply casual leave for coming week friday", wednesday)
        next_week = dr.resolve_relative_date_phrase("apply casual leave for next week friday", wednesday)
        assert upcoming["from_date"] == "2026-09-04"
        assert coming["from_date"] == "2026-09-04"
        assert upcoming["from_date"] == next_week["from_date"]
        assert upcoming["matched_kind"] == "weekday_of_next_calendar_week"

    def test_upcoming_week_weekday_tolerates_extra_whitespace(self):
        # The exact live repro had a double space between "week" and "friday".
        result = dr.resolve_relative_date_phrase(
            "apply casaul leave for upcoming week  friday reason is health issue for full day",
            date(2026, 8, 26),
        )
        assert result["from_date"] == "2026-09-04"

    def test_this_monday_and_next_monday_diverge_when_today_is_monday(self):
        this_result = dr.resolve_relative_date_phrase("apply leave this Monday", MONDAY)
        next_result = dr.resolve_relative_date_phrase("apply leave next Monday", MONDAY)
        assert this_result["from_date"] == MONDAY.isoformat()
        assert next_result["from_date"] == (MONDAY + timedelta(days=7)).isoformat()

    def test_resolves_next_to_next_monday(self):
        result = dr.resolve_relative_date_phrase("apply leave next to next Monday", WEDNESDAY)
        assert result["from_date"] == "2026-08-31"

    def test_resolves_next_to_next_friday(self):
        result = dr.resolve_relative_date_phrase("apply leave next to next Friday", WEDNESDAY)
        # next Friday strict from Wed 2026-08-19 -> 2026-08-21; +7 -> 2026-08-28.
        assert result["from_date"] == "2026-08-28"

    def test_next_to_next_monday_does_not_get_shadowed_by_the_plain_next_monday_pattern(self):
        result = dr.resolve_relative_date_phrase("apply casual leave for next to next Monday", WEDNESDAY)
        assert result["matched_kind"] == "next_to_next_weekday"
        assert result["from_date"] == "2026-08-31"

    def test_resolves_week_after_next_bare(self):
        result = dr.resolve_relative_date_phrase("apply leave week after next", MONDAY)
        assert result["from_date"] == "2026-09-07"

    def test_resolves_next_month_bare(self):
        result = dr.resolve_relative_date_phrase("apply leave next month", WEDNESDAY)
        assert result["from_date"] == "2026-09-01"

    def test_resolves_next_month_bare_handles_december_reference(self):
        result = dr.resolve_relative_date_phrase("apply leave next month", date(2026, 12, 10))
        assert result["from_date"] == "2027-01-01"

    def test_resolves_first_monday_of_next_month(self):
        # September 2026's 1st is a Tuesday, so the first Monday is the 7th.
        result = dr.resolve_relative_date_phrase("apply leave first Monday of next month", date(2026, 8, 21))
        assert result["from_date"] == "2026-09-07"

    def test_yesterday_returns_none_by_default_past_date_guard(self):
        result = dr.resolve_relative_date_phrase("apply leave yesterday", WEDNESDAY)
        assert result is None

    def test_yesterday_resolves_when_allow_past_true(self):
        result = dr.resolve_relative_date_phrase("show my leave yesterday", WEDNESDAY, allow_past=True)
        assert result["from_date"] == "2026-08-18"

    def test_unrecognized_phrase_returns_none(self):
        assert dr.resolve_relative_date_phrase("apply leave sometime soon", WEDNESDAY) is None
        assert dr.resolve_relative_date_phrase("apply leave whenever works", WEDNESDAY) is None

    def test_case_insensitive_matching(self):
        result = dr.resolve_relative_date_phrase("apply leave NEXT MONDAY", WEDNESDAY)
        assert result["from_date"] == "2026-08-24"

    def test_reference_date_that_is_itself_sunday(self):
        # From Sunday 2026-08-23, "this Friday" -> the coming Friday, 2026-08-28.
        result = dr.resolve_relative_date_phrase("apply leave this Friday", SUNDAY)
        assert result["from_date"] == "2026-08-28"


class TestExtractDurationDays:

    def test_extracts_bare_digit_count(self):
        assert dr.extract_duration_days("I want to apply 20 days leaves from 12th november") == 20

    def test_extracts_for_n_days_phrasing(self):
        assert dr.extract_duration_days("apply leave for 5 days") == 5

    def test_extracts_a_week(self):
        assert dr.extract_duration_days("apply leave for a week") == 7

    def test_extracts_two_weeks(self):
        assert dr.extract_duration_days("apply leave for two weeks") == 14

    def test_extracts_a_month(self):
        assert dr.extract_duration_days("apply leave for a month") == 30

    @pytest.mark.parametrize("word,expected", [
        ("one", 1), ("two", 2), ("three", 3), ("four", 4), ("five", 5),
        ("six", 6), ("seven", 7), ("eight", 8), ("nine", 9), ("ten", 10),
        ("eleven", 11), ("twelve", 12),
    ])
    def test_extracts_spelled_out_numbers_one_through_twelve(self, word, expected):
        assert dr.extract_duration_days(f"apply leave for {word} days") == expected

    def test_a_and_an_both_mean_one(self):
        assert dr.extract_duration_days("apply leave for a day") == 1
        assert dr.extract_duration_days("apply leave for an day") == 1

    def test_returns_none_when_no_duration_phrase_present(self):
        assert dr.extract_duration_days("apply casual leave tomorrow") is None

    def test_half_day_is_not_mistaken_for_a_duration_count(self):
        assert dr.extract_duration_days("half day tomorrow") is None

    def test_case_insensitive_duration_matching(self):
        assert dr.extract_duration_days("apply leave for 20 DAYS") == 20


class TestExtractDurationDaysExcludeParam:
    """Live bug: 'apply leave a week after next' resolved 'week after next'
    to a single day via resolve_relative_date_phrase, but extract_duration_
    days ALSO separately matched 'a week' in the very same sentence and
    returned 7 — silently corrupting a single-day request into a 7-day
    range when the caller applied it as an explicit duration. A resolver's
    own already-consumed phrase must never double as a separate duration
    count."""

    def test_matched_phrase_excluded_prevents_double_count(self):
        assert dr.extract_duration_days("apply leave a week after next", exclude="week after next") is None

    def test_unrelated_duration_after_excluded_phrase_still_found(self):
        result = dr.extract_duration_days("in two weeks for 3 days", exclude="in two weeks")
        assert result == 3

    def test_no_exclude_behaves_as_before(self):
        assert dr.extract_duration_days("for 5 days") == 5

    def test_exclude_is_case_insensitive(self):
        assert dr.extract_duration_days(
            "Apply Leave A Week After Next", exclude="week after next",
        ) is None

    def test_exclude_not_present_in_query_is_a_noop(self):
        assert dr.extract_duration_days("apply leave for 5 days", exclude="next month") == 5


class TestResolveRelativeDurationOffsetPhrase:
    """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 a weekday name or a fixed qualifier-word list — a phrase with
    neither ('in two weeks', 'a month from now', '15 days from now') was
    completely invisible to both, riding on the plain first-pass LLM
    extraction's own unchecked guess. This is genuinely deterministic day
    arithmetic though, so it gets a real tier-1 resolver instead."""

    def test_in_two_weeks(self):
        result = dr.resolve_relative_duration_offset_phrase("apply leave in two weeks", MONDAY)
        assert result["from_date"] == (MONDAY + timedelta(days=14)).isoformat()
        assert result["matched_kind"] == "relative_duration_offset"

    def test_in_digit_weeks(self):
        result = dr.resolve_relative_duration_offset_phrase("in 2 weeks", MONDAY)
        assert result["from_date"] == (MONDAY + timedelta(days=14)).isoformat()

    def test_after_n_days(self):
        result = dr.resolve_relative_duration_offset_phrase("apply leave after 15 days", MONDAY)
        assert result["from_date"] == (MONDAY + timedelta(days=15)).isoformat()

    def test_n_days_from_now(self):
        result = dr.resolve_relative_duration_offset_phrase("15 days from now", MONDAY)
        assert result["from_date"] == (MONDAY + timedelta(days=15)).isoformat()

    def test_n_days_from_today(self):
        result = dr.resolve_relative_duration_offset_phrase("15 days from today", MONDAY)
        assert result["from_date"] == (MONDAY + timedelta(days=15)).isoformat()

    def test_a_month_from_now_uses_approx_30_days(self):
        result = dr.resolve_relative_duration_offset_phrase("a month from now", MONDAY)
        assert result["from_date"] == (MONDAY + timedelta(days=30)).isoformat()

    def test_in_a_month(self):
        result = dr.resolve_relative_duration_offset_phrase("in a month", MONDAY)
        assert result["from_date"] == (MONDAY + timedelta(days=30)).isoformat()

    def test_no_match_returns_none(self):
        assert dr.resolve_relative_duration_offset_phrase("apply casual leave tomorrow", MONDAY) is None

    def test_mentions_relative_duration_qualifier_true_cases(self):
        assert dr.mentions_relative_duration_qualifier("apply leave in two weeks") is True
        assert dr.mentions_relative_duration_qualifier("15 days from now") is True

    def test_mentions_relative_duration_qualifier_false_case(self):
        assert dr.mentions_relative_duration_qualifier("apply casual leave tomorrow") is False


class TestMentionsAmbiguousBareDayOfMonth:
    """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 the month-rollover never disclosed anywhere. This is a
    pure text+today signal, OR'd into hr_graph._query_needs_relative_date_
    scrutiny — a bare day-of-month is only ambiguous once a same-month
    reading is impossible; still-upcoming, explicitly-month-named, and
    explicitly-qualified mentions all stay unambiguous, same as before."""

    def test_live_repro_already_passed_day_is_ambiguous(self):
        assert dr.mentions_ambiguous_bare_day_of_month("on 15th", date(2026, 8, 27)) == 15

    def test_still_upcoming_this_month_is_not_ambiguous(self):
        assert dr.mentions_ambiguous_bare_day_of_month("on the 5th", date(2026, 8, 1)) is None

    def test_explicit_month_name_is_not_ambiguous(self):
        assert dr.mentions_ambiguous_bare_day_of_month("15th August", date(2026, 8, 27)) is None

    def test_explicit_next_month_qualifier_is_not_ambiguous(self):
        assert dr.mentions_ambiguous_bare_day_of_month("next month's 15th", date(2026, 8, 27)) is None

    def test_explicit_this_month_qualifier_is_not_ambiguous(self):
        assert dr.mentions_ambiguous_bare_day_of_month("this month's 5th", date(2026, 8, 27)) is None

    def test_no_ordinal_suffix_is_out_of_scope(self):
        assert dr.mentions_ambiguous_bare_day_of_month("on 15", date(2026, 8, 27)) is None

    def test_day_equal_to_today_is_not_ambiguous(self):
        assert dr.mentions_ambiguous_bare_day_of_month("on 27th", date(2026, 8, 27)) is None

    def test_no_bare_day_mention_at_all_returns_none(self):
        assert dr.mentions_ambiguous_bare_day_of_month("apply leave tomorrow", date(2026, 8, 27)) is None


class TestNamedMonthAnchoringPrimitives:

    def test_nth_weekday_of_month_returns_first_occurrence(self):
        # October 2026: Wednesdays fall on 7, 14, 21, 28.
        assert dr.nth_weekday_of_month(2026, 10, 2, 1) == date(2026, 10, 7)

    def test_nth_weekday_of_month_returns_fourth_occurrence(self):
        assert dr.nth_weekday_of_month(2026, 10, 2, 4) == date(2026, 10, 28)

    def test_nth_weekday_of_month_returns_none_when_fifth_occurrence_does_not_exist(self):
        assert dr.nth_weekday_of_month(2026, 10, 2, 5) is None

    def test_last_weekday_of_month(self):
        # October 2026's last Friday is the 30th.
        assert dr.last_weekday_of_month(2026, 10, 4) == date(2026, 10, 30)

    def test_last_weekday_of_month_handles_december(self):
        result = dr.last_weekday_of_month(2026, 12, 3)  # last Thursday of December
        assert result.month == 12
        assert result.weekday() == 3
        assert result + timedelta(days=7) > date(2026, 12, 31)


class TestWeekdayInNamedMonth:

    def test_ordinal_first(self):
        result = dr.weekday_in_named_month(WEDNESDAY, month=10, target_weekday=2, ordinal="first")
        assert result == date(2026, 10, 7)

    def test_ordinal_last(self):
        result = dr.weekday_in_named_month(WEDNESDAY, month=10, target_weekday=4, ordinal="last")
        assert result == date(2026, 10, 30)

    def test_ordinal_fourth(self):
        result = dr.weekday_in_named_month(WEDNESDAY, month=10, target_weekday=2, ordinal="fourth")
        assert result == date(2026, 10, 28)

    def test_ordinal_that_does_not_exist_in_month_returns_none(self):
        # October 2026 has only 4 Wednesdays.
        result = dr.weekday_in_named_month(WEDNESDAY, month=10, target_weekday=2, ordinal="fourth")
        assert result is not None
        fifth = dr.nth_weekday_of_month(2026, 10, 2, 5)
        assert fifth is None

    def test_ordinal_next_without_after_resolves_standalone_within_named_month(self):
        # From Wed 2026-08-19, "next Saturday of October" is standalone (no
        # preceding range endpoint) -> nearest Saturday on/after October 1st,
        # NOT the nearest Saturday from today (which would fall in August).
        result = dr.weekday_in_named_month(WEDNESDAY, month=10, target_weekday=5, ordinal="next")
        assert result == date(2026, 10, 3)

    def test_ordinal_next_with_after_resolves_relative_to_after_not_month_start(self):
        # This is the exact anchored-range design: the second endpoint of a
        # range must land after the first endpoint, never before it.
        after = date(2026, 10, 7)  # first Wednesday of October
        result = dr.weekday_in_named_month(WEDNESDAY, month=10, target_weekday=5, ordinal="next", after=after)
        assert result == date(2026, 10, 10)
        assert result > after

    def test_year_inferred_as_current_year_when_month_has_not_passed(self):
        # today is August (month 8); October (month 10) hasn't passed yet.
        result = dr.weekday_in_named_month(WEDNESDAY, month=10, target_weekday=2, ordinal="first")
        assert result.year == 2026

    def test_year_rolls_over_when_named_month_has_already_passed(self):
        # today is in November; asking about October means next year's October.
        today = date(2026, 11, 15)
        result = dr.weekday_in_named_month(today, month=10, target_weekday=2, ordinal="first")
        assert result.year == 2027
        assert result.month == 10
        assert result.weekday() == 2


class TestResolveDateRangePhrase:

    def test_single_named_month_anchored_phrase_returns_no_second_date(self):
        result = dr.resolve_date_range_phrase("apply sick leave first wednesday of october", WEDNESDAY)
        assert result is not None
        first, second = result
        assert first["from_date"] == "2026-10-07"
        assert first["matched_kind"] == "month_anchored_weekday"
        assert second is None

    def test_reported_bug_october_first_wednesday_to_october_next_saturday(self):
        result = dr.resolve_date_range_phrase(
            "I want to apply sick leave october first wednesday to october next saturday", WEDNESDAY,
        )
        assert result is not None
        first, second = result
        assert first["from_date"] == "2026-10-07"
        assert second is not None
        assert second["from_date"] == "2026-10-10"

    def test_second_endpoint_next_does_not_invert_the_range(self):
        # A naive "nearest Saturday from month-start" reading of the second
        # endpoint would give 2026-10-03, which is BEFORE the first endpoint
        # (2026-10-07) and would produce a backwards range. The anchored
        # design must never do that.
        result = dr.resolve_date_range_phrase(
            "october first wednesday to october next saturday", WEDNESDAY,
        )
        first, second = result
        assert date.fromisoformat(second["from_date"]) > date.fromisoformat(first["from_date"])

    def test_no_named_month_anchored_phrase_returns_none(self):
        assert dr.resolve_date_range_phrase("apply casual leave tomorrow", WEDNESDAY) is None

    def test_alternate_phrasing_month_name_then_ordinal_then_weekday(self):
        result = dr.resolve_date_range_phrase("apply leave october's first wednesday", WEDNESDAY)
        assert result is not None
        first, second = result
        assert first["from_date"] == "2026-10-07"
        assert second is None

    def test_second_endpoint_resolving_before_first_is_dropped_not_inverted(self):
        # "last Friday of October" (Oct 30) followed by "first Monday of
        # October" (Oct 5, ordinal "first" ignores the `after` anchor) would
        # be a backwards range -> the second date must be dropped, not kept
        # as an inverted range.
        result = dr.resolve_date_range_phrase(
            "last friday of october to first monday of october", WEDNESDAY,
        )
        assert result is not None
        first, second = result
        assert first["from_date"] == "2026-10-30"
        assert second is None

    def test_past_first_endpoint_within_current_month_returns_none(self):
        # If today is already past the ordinal occurrence within the named
        # month this year, the result is a genuinely past date -> None.
        today = date(2026, 10, 20)
        result = dr.resolve_date_range_phrase("apply leave first wednesday of october", today)
        assert result is None


class TestWeekOfMonth:

    def test_first_week_is_days_one_through_seven(self):
        assert dr.week_of_month(WEDNESDAY, month=11, ordinal="first") == (date(2026, 11, 1), date(2026, 11, 7))

    def test_second_week_is_days_eight_through_fourteen(self):
        assert dr.week_of_month(WEDNESDAY, month=11, ordinal="second") == (date(2026, 11, 8), date(2026, 11, 14))

    def test_fourth_week_of_a_31_day_month(self):
        assert dr.week_of_month(WEDNESDAY, month=10, ordinal="fourth") == (date(2026, 10, 22), date(2026, 10, 28))

    def test_last_week_is_final_seven_days_of_month(self):
        # October 2026 has 31 days -> last week is 25-31.
        assert dr.week_of_month(WEDNESDAY, month=10, ordinal="last") == (date(2026, 10, 25), date(2026, 10, 31))

    def test_last_week_of_february_non_leap_year(self):
        result = dr.week_of_month(WEDNESDAY, month=2, ordinal="last")
        assert result == (date(2027, 2, 22), date(2027, 2, 28))

    def test_year_rolls_over_when_named_month_has_already_passed(self):
        today = date(2026, 12, 15)
        assert dr.week_of_month(today, month=11, ordinal="first") == (date(2027, 11, 1), date(2027, 11, 7))

    def test_unrecognized_ordinal_returns_none(self):
        assert dr.week_of_month(WEDNESDAY, month=11, ordinal="fifth") is None


class TestResolveWeekOfMonthPhrase:

    def test_reported_bug_november_first_week_to_end_of_first_week(self):
        result = dr.resolve_week_of_month_phrase(
            "i want to apply leave from november first week to end of the first week", WEDNESDAY,
        )
        assert result is not None
        first, second = result
        assert first["from_date"] == "2026-11-01"
        assert second["from_date"] == "2026-11-07"
        assert first["matched_kind"] == "week_of_month"

    def test_resolves_ordinal_week_of_month_order(self):
        result = dr.resolve_week_of_month_phrase("apply leave first week of november", WEDNESDAY)
        assert result is not None
        first, second = result
        assert (first["from_date"], second["from_date"]) == ("2026-11-01", "2026-11-07")

    def test_resolves_month_ordinal_week_order(self):
        result = dr.resolve_week_of_month_phrase("apply leave november's second week", WEDNESDAY)
        assert result is not None
        first, second = result
        assert (first["from_date"], second["from_date"]) == ("2026-11-08", "2026-11-14")

    def test_no_week_of_month_phrase_returns_none(self):
        assert dr.resolve_week_of_month_phrase("apply casual leave tomorrow", WEDNESDAY) is None

    def test_misspelled_month_name_is_not_recognized_and_falls_through(self):
        # Deterministic matching is exact, not fuzzy — a typo'd month name
        # ("novermber") is correctly left for the LLM fallback to handle,
        # same fall-through contract as every other resolver in this module.
        result = dr.resolve_week_of_month_phrase(
            "i want to apply leave from novermber first week to end of the first week", WEDNESDAY,
        )
        assert result is None

    def test_past_week_within_current_month_returns_none(self):
        today = date(2026, 11, 20)
        result = dr.resolve_week_of_month_phrase("apply leave first week of november", today)
        assert result is None


class TestResolveNextCalendarWeekPhrase:
    """Live bug: 'apply leave for upcoming week' (bare, no weekday) had no
    deterministic pattern at all and fell through to tier 2's structured
    extraction — whose schema can only represent a single day, not a week
    span — which guessed a rolling 7-day window starting a week from today
    instead of the actual next Mon-Sun calendar week."""

    def test_upcoming_week_resolves_to_next_monday_through_sunday(self):
        result = dr.resolve_next_calendar_week_phrase("apply leave for upcoming week", WEDNESDAY)
        assert result is not None
        first, second = result
        assert (first["from_date"], second["from_date"]) == ("2026-08-24", "2026-08-30")
        assert first["matched_kind"] == "next_calendar_week"

    def test_next_week_bare_also_resolves(self):
        result = dr.resolve_next_calendar_week_phrase("apply leave next week", WEDNESDAY)
        assert result is not None
        first, second = result
        assert (first["from_date"], second["from_date"]) == ("2026-08-24", "2026-08-30")

    def test_coming_week_also_resolves(self):
        result = dr.resolve_next_calendar_week_phrase("apply leave for coming week", WEDNESDAY)
        assert result is not None

    def test_next_week_with_a_named_weekday_does_not_match(self):
        # "next week Wednesday" names a single day within that week — a
        # DIFFERENT, already-handled construct (weekday_of_next_calendar_week
        # via _PATTERNS) — must not also be claimed by the bare-week pattern.
        assert dr.resolve_next_calendar_week_phrase("apply leave next week wednesday", WEDNESDAY) is None

    def test_no_week_phrase_returns_none(self):
        assert dr.resolve_next_calendar_week_phrase("apply casual leave tomorrow", WEDNESDAY) is None

    def test_next_calendar_week_bounds_primitive(self):
        start, end = dr.next_calendar_week_bounds(WEDNESDAY)
        assert (start, end) == (date(2026, 8, 24), date(2026, 8, 30))


class TestWeekdayWithinSpan:
    """Regression coverage for the live bug: 'apply casual leave for
    november first week coming wednesday for 1 day' was treated as a
    7-day request for the whole week, ignoring both the weekday narrowing
    and the explicit duration."""

    def test_narrows_to_the_named_weekday_within_the_span(self):
        # November 2026's first week is Sun 1 - Sat 7; the Wednesday in it
        # is the 4th.
        result = dr.weekday_within_span(
            "november first week coming wednesday", date(2026, 11, 1), date(2026, 11, 7),
        )
        assert result == {
            "from_date": "2026-11-04", "matched_phrase": "wednesday", "matched_kind": "weekday_within_week",
        }

    def test_modifier_word_does_not_change_which_date_is_meant(self):
        # "this"/"next"/etc. don't matter within an already-resolved single
        # week — there's only one Wednesday in it either way.
        for phrase in ["this wednesday", "next wednesday", "upcoming wednesday", "wednesday"]:
            result = dr.weekday_within_span(phrase, date(2026, 11, 1), date(2026, 11, 7))
            assert result["from_date"] == "2026-11-04", phrase

    def test_no_weekday_mentioned_returns_none(self):
        result = dr.weekday_within_span("end of the first week", date(2026, 11, 1), date(2026, 11, 7))
        assert result is None

    def test_case_insensitive(self):
        result = dr.weekday_within_span("coming WEDNESDAY", date(2026, 11, 1), date(2026, 11, 7))
        assert result["from_date"] == "2026-11-04"


class TestResolveRelativeDateRangePhrase:
    """Regression coverage for the live bug: 'upcoming Wednesday to next
    Sunday' resolved to 'next Sunday' alone (a higher fixed-priority
    pattern in _PATTERNS) because resolve_relative_date_phrase only ever
    returns its first match by pattern priority, not textual position."""

    def test_reported_bug_upcoming_wednesday_to_next_sunday(self):
        # From Fri 2026-08-21: "upcoming Wednesday" = 2026-08-26 (nearest
        # Wed on/after today). The second endpoint must resolve to the
        # Sunday following THAT Wednesday (2026-08-30), not the nearest
        # Sunday from today (2026-08-23, which would be BEFORE it).
        today = date(2026, 8, 21)
        result = dr.resolve_relative_date_range_phrase(
            "I want to apply casual leave for upcoming wednesday to next sunday "
            "for full day due to health issue", today,
        )
        assert result is not None
        first, second = result
        assert first["from_date"] == "2026-08-26"
        assert second is not None
        assert second["from_date"] == "2026-08-30"

    def test_first_endpoint_wins_over_higher_priority_pattern_appearing_later(self):
        today = date(2026, 8, 21)
        solo = dr.resolve_relative_date_phrase("upcoming wednesday to next sunday", today)
        # Sanity check on the pre-existing bug: the single-phrase resolver
        # really does pick the wrong (later-appearing, higher-priority)
        # phrase when used naively on a range query.
        assert solo["matched_phrase"] == "next sunday"

        first, second = dr.resolve_relative_date_range_phrase("upcoming wednesday to next sunday", today)
        assert first["matched_phrase"] == "upcoming wednesday"
        assert second["matched_phrase"] == "next sunday"

    def test_second_endpoint_resolves_relative_to_first_not_today(self):
        # "this Monday to this Friday" — both within the same week as seen
        # from the FIRST endpoint, not independently anchored to today.
        today = date(2026, 8, 19)  # Wednesday
        first, second = dr.resolve_relative_date_range_phrase("this monday to this friday", today)
        assert first["from_date"] == "2026-08-24"   # this coming Monday
        assert second["from_date"] == "2026-08-28"  # the Friday of THAT week

    def test_till_and_until_are_recognized_connectors(self):
        today = date(2026, 8, 21)
        for connector in ("till", "until", "through"):
            result = dr.resolve_relative_date_range_phrase(f"upcoming wednesday {connector} next sunday", today)
            assert result is not None, connector
            first, second = result
            assert (first["from_date"], second["from_date"]) == ("2026-08-26", "2026-08-30")

    def test_no_connector_returns_none(self):
        assert dr.resolve_relative_date_range_phrase("apply casual leave next monday", date(2026, 8, 21)) is None

    def test_unrecognized_second_side_means_no_connector_match_at_all(self):
        # The connector regex itself requires BOTH sides to already be a
        # valid _PATTERNS phrase, so "whenever works" on the right simply
        # never forms a match — this is a full None, not a single-endpoint
        # result (contrast with test_second_resolving_before_first_is_dropped,
        # where the connector DOES match both sides but the second endpoint
        # is dropped afterwards for resolving too early).
        today = date(2026, 8, 21)
        assert dr.resolve_relative_date_range_phrase("next monday to whenever works", today) is None

    def test_second_resolving_before_first_is_dropped(self):
        # Contrived but must not invert: if the second phrase's kind
        # resolves to the anchor date itself (no forward movement), drop it
        # rather than return a same-day/backwards "range".
        today = date(2026, 8, 21)
        result = dr.resolve_relative_date_range_phrase("tomorrow to today", today)
        assert result is not None
        first, second = result
        assert first["from_date"] == "2026-08-22"
        assert second is None


class TestMentionsDateExpression:
    """Promoted from hr_graph.py's former private _mentions_a_date so it's
    reusable outside the leave-status branch (see hr_graph.classify_node,
    which now computes this once per query for every intent)."""

    @pytest.mark.parametrize("query", [
        "show my leave details for 21th august",
        "what's my status on August 21",
        "leaves from today",
        "anything for tomorrow",
        "checked yesterday and nothing changed",
        "on 21/08/2026",
        "due 21-08",
        "created 2026-08-21",
    ])
    def test_recognizes_plausible_date_mentions(self, query):
        assert dr.mentions_date_expression(query) is True

    @pytest.mark.parametrize("query", [
        "what's my leave status",
        "is my leave approved",
        "how many leaves do I have",
        "vocation",
    ])
    def test_no_false_positive_on_dateless_queries(self, query):
        assert dr.mentions_date_expression(query) is False


class TestResolveStructuredDate:
    """resolve_structured_date — the tool-calling tier: an LLM extracts
    structured fields only (never a final date), this pure function does
    100% of the actual arithmetic by composing the SAME primitives the
    regex-matched functions above already use. No new date math anywhere
    here — only a new entry point into math that's already tested."""

    TODAY = date(2026, 8, 24)  # a Monday

    def test_day_offset_and_weekday_together_is_a_conflict_returns_none(self):
        # Live evidence (real-model diagnostic): the model populates BOTH
        # day_offset and weekday fields for compound phrases outside this
        # schema's vocabulary ("a week from next Tuesday", "two Fridays
        # from now") despite the prompt forbidding it — and picking one
        # arbitrarily produced a silently WRONG date in both observed
        # cases. Two populated shapes at once must defer, not guess.
        result = dr.resolve_structured_date(
            self.TODAY, day_offset=1, target_weekday="friday", ordinal="first", month_offset=1,
        )
        assert result is None

    def test_day_offset_alone_with_no_weekday_field_still_resolves(self):
        result = dr.resolve_structured_date(self.TODAY, day_offset=1)
        assert result == date(2026, 8, 25)

    def test_day_offset_and_weekday_that_agree_still_resolve(self):
        # Live evidence: the model populates BOTH shapes even for simple
        # cases like "this coming Friday" — day_offset=4 (2026-08-28) and
        # target_weekday=friday/weekday_relation=this land on the SAME
        # date, so this must resolve normally rather than being treated as
        # a conflict (only disagreement is a conflict, not co-occurrence).
        result = dr.resolve_structured_date(
            self.TODAY, day_offset=4, target_weekday="friday", weekday_relation="this",
        )
        assert result == date(2026, 8, 28)

    def test_day_offset_zero_is_today(self):
        assert dr.resolve_structured_date(self.TODAY, day_offset=0) == self.TODAY

    def test_day_offset_negative_is_rejected_by_default(self):
        # "yesterday" — a syntactically fine offset, but the past-date
        # contract still applies unless allow_past=True.
        assert dr.resolve_structured_date(self.TODAY, day_offset=-1) is None

    def test_day_offset_negative_allowed_when_allow_past_true(self):
        result = dr.resolve_structured_date(self.TODAY, day_offset=-1, allow_past=True)
        assert result == date(2026, 8, 23)

    def test_weekday_relation_this(self):
        # "this/coming Wednesday" — inclusive nearest occurrence.
        result = dr.resolve_structured_date(self.TODAY, target_weekday="wednesday", weekday_relation="this")
        assert result == date(2026, 8, 26)

    def test_weekday_relation_next_is_strict(self):
        result = dr.resolve_structured_date(self.TODAY, target_weekday="monday", weekday_relation="next")
        assert result == date(2026, 8, 31)  # strictly after today, even though today IS Monday

    def test_weekday_relation_next_to_next(self):
        result = dr.resolve_structured_date(self.TODAY, target_weekday="monday", weekday_relation="next_to_next")
        assert result == date(2026, 9, 7)

    def test_ordinal_weekday_this_month(self):
        # August 2026: last Monday is the 31st.
        result = dr.resolve_structured_date(
            self.TODAY, target_weekday="monday", ordinal="last", month_offset=0,
        )
        assert result == date(2026, 8, 31)

    def test_ordinal_weekday_next_month(self):
        # September 2026: 2nd Wednesday is the 9th.
        result = dr.resolve_structured_date(
            self.TODAY, target_weekday="wednesday", ordinal="second", month_offset=1,
        )
        assert result == date(2026, 9, 9)

    def test_ordinal_without_month_offset_is_ambiguous_returns_none(self):
        assert dr.resolve_structured_date(self.TODAY, target_weekday="friday", ordinal="first") is None

    def test_month_offset_two_months_ahead(self):
        # Live bug: "next 2 months first week Wednesday" — month_offset used
        # to only support "this"/"next" (0/1), so "2" had nowhere to go and
        # got silently dropped, answering as if the user had said "next
        # month". October 2026's first Wednesday is the 7th.
        result = dr.resolve_structured_date(
            self.TODAY, target_weekday="wednesday", ordinal="first", month_offset=2,
        )
        assert result == date(2026, 10, 7)

    def test_month_offset_crosses_a_year_boundary(self):
        # From November 2026, month_offset=2 lands in January 2027.
        result = dr.resolve_structured_date(
            date(2026, 11, 15), target_weekday="friday", ordinal="first", month_offset=2,
        )
        assert result == date(2027, 1, 1)

    def test_negative_month_offset_returns_none(self):
        assert dr.resolve_structured_date(
            self.TODAY, target_weekday="friday", ordinal="first", month_offset=-1,
        ) is None

    def test_fourth_occurrence_always_exists_every_month_has_at_least_28_days(self):
        # Every calendar month has >=28 days, so "fourth" always exists for
        # any weekday — only "fifth" could fail to exist, and "fifth" isn't
        # a valid ordinal in this schema at all (see
        # test_unrecognized_ordinal_returns_none). September 2026 Fridays:
        # 4, 11, 18, 25 — fourth is the 25th.
        result = dr.resolve_structured_date(
            self.TODAY, target_weekday="friday", ordinal="fourth", month_offset=1,
        )
        assert result == date(2026, 9, 25)

    def test_no_weekday_no_offset_returns_none(self):
        assert dr.resolve_structured_date(self.TODAY) is None

    def test_unrecognized_weekday_returns_none(self):
        assert dr.resolve_structured_date(self.TODAY, target_weekday="funday", weekday_relation="next") is None

    def test_unrecognized_ordinal_returns_none(self):
        assert dr.resolve_structured_date(
            self.TODAY, target_weekday="friday", ordinal="fifth", month_offset=1,
        ) is None

    def test_resolved_this_month_date_before_today_returns_none_by_default(self):
        # today is 2026-09-29; September's last Monday (28th) has passed.
        result = dr.resolve_structured_date(
            date(2026, 9, 29), target_weekday="monday", ordinal="last", month_offset=0,
        )
        assert result is None

    def test_resolved_this_month_date_before_today_allowed_with_flag(self):
        result = dr.resolve_structured_date(
            date(2026, 9, 29), target_weekday="monday", ordinal="last", month_offset=0, allow_past=True,
        )
        assert result == date(2026, 9, 28)
