"""
Regression guard for services/ai_service.py::_build_leave_slot_extraction_prompt.

Live bug: "apply for PL on 2026-08-20" got extracted with leave_type
mapped to "leave_without_pay" — the LLM guessed a slug for an abbreviation
("PL" / Privilege Leave) the prompt never defined, and happened to guess
the one slug where being wrong is financially significant (it silently
turns a paid leave request into an unpaid one). The fix is a prompt-level
instruction, which can't be asserted via a mocked-LLM unit test the way the
rest of this file's tests work — this instead pins down that the specific
safety instructions are present in the prompt, so a future edit can't
silently drop them. The actual behavior was verified against the real LLM
directly (not covered by CI).
"""

import datetime

from services.ai_service import (
    _build_leave_slot_extraction_prompt,
    _build_structured_date_extraction_prompt,
    _build_date_range_extraction_prompt,
)


class TestLeaveSlotExtractionPromptSafety:

    def test_prompt_forbids_guessing_unclear_leave_types(self):
        prompt = _build_leave_slot_extraction_prompt("apply for PL", {})
        assert "do not guess" in prompt.lower()

    def test_prompt_forbids_defaulting_unclear_types_to_leave_without_pay(self):
        prompt = _build_leave_slot_extraction_prompt("apply for PL", {})
        assert "never map" in prompt.lower() or "never guess" in prompt.lower() \
            or "only for when the user explicitly says" in prompt.lower()
        assert "leave_without_pay" in prompt

    def test_prompt_instructs_reason_field_not_to_absorb_unknown_leave_types(self):
        prompt = _build_leave_slot_extraction_prompt("apply for maternity leave", {})
        assert "not a reason" in prompt.lower() or "isn't in the known" in prompt.lower()

    def test_known_slugs_still_listed(self):
        prompt = _build_leave_slot_extraction_prompt("apply leave", {})
        for slug in ("casual_leave", "sick_leave", "earned_leave", "comp_off",
                     "leave_without_pay", "short_leave"):
            assert slug in prompt

    def test_prompt_warns_against_misparsing_apply_type_leave_with_no_for(self):
        """Live bug: 'apply sick leave reason is fever' (no 'for'/'want'/
        'need') consistently returned leave_type=null, unrecognized_leave_
        type='sick leave' — the model was misreading 'leave' as the verb
        'to depart' rather than the noun, even though the exact same type
        was recognized fine with 'apply FOR sick leave'. The prompt must
        explicitly warn against this exact misparse."""
        prompt = _build_leave_slot_extraction_prompt("apply sick leave reason is fever", {})
        assert "apply <type> leave" in prompt or "apply sick leave" in prompt.lower()
        assert "verb" in prompt.lower()

    def test_prompt_covers_bare_leave_type_root_word_without_the_word_leave(self):
        """Live bug: 'casual'/'earned'/'short' (typed bare, in reply to
        'what type of leave?') already mapped fine, but bare 'sick' alone
        consistently returned leave_type=null, unrecognized_leave_type=
        'sick' — 'sick' is also an ordinary English word for feeling
        unwell, so the model over-applied its own 'don't infer from a
        symptom' rule to a bare single-word reply where naming the type IS
        the message's entire content. Must explicitly carve out the
        exact-single-word case, and explicitly distinguish it from 'I am
        sick' (which must keep going to reason, unchanged)."""
        prompt = _build_leave_slot_extraction_prompt("sick", {})
        assert "sick_leave" in prompt
        assert '"i am sick"' in prompt.lower()  # explicit contrasting negative example present
        assert "one word" in prompt.lower() or "single word" in prompt.lower() or "single-word" in prompt.lower()


class TestStructuredDateExtractionPromptSafety:
    """Regression guard for _build_structured_date_extraction_prompt (the
    tier-2 structured-field extraction prompt). Audit finding (A3, no live
    bug reported yet): tier 2's schema requires weekday_relation to be set
    for ANY weekday it fills in, but for a bare two-weekday range with no
    modifier word on either side ('Wednesday to Friday'), which week is
    meant is genuinely ambiguous — the model has a documented tendency
    (see date_resolver.resolve_structured_date's own docstring) to
    over-infer a weekday_relation guess anyway rather than leaving it null,
    which would bypass tier 3's cross-check entirely since tier 2 would
    then report success. Can't be asserted via a mocked-LLM test the way
    the rest of this file's tests work — this pins down that the specific
    instruction is present in the prompt. The actual model behavior should
    be verified against the real LLM directly (not covered by CI)."""

    def test_prompt_instructs_null_weekday_relation_for_bare_modifierless_range(self):
        prompt = _build_structured_date_extraction_prompt("Wednesday to Friday", datetime.date(2026, 8, 24))
        assert "wednesday to friday" in prompt.lower()
        assert "null" in prompt.lower()
        assert "modifier" in prompt.lower() or "ambiguous" in prompt.lower()


class TestDateRangeExtractionPromptUsesInjectedToday:
    """Live bug: _build_date_range_extraction_prompt (the tier-2 LLM
    fallback used by hr_graph._resolve_date_range for leave-status/read-
    only date filtering) had NO today parameter at all — it always called
    naive datetime.date.today() internally, silently discarding the
    correctly-computed, timezone-aware `today` its only caller already had
    (used correctly for that same caller's own deterministic tier). If the
    server process's OS-local timezone ever differs from the app's
    configured QUOTA_TIMEZONE, or near a midnight boundary, this tier could
    reason from the wrong calendar date entirely. Must use the passed-in
    `today`, never the real wall-clock date."""

    def test_prompt_uses_the_injected_today_not_the_real_date(self):
        prompt = _build_date_range_extraction_prompt("last Monday", datetime.date(2026, 1, 1))
        assert "2026-01-01" in prompt

    def test_prompt_reflects_a_different_injected_today(self):
        prompt = _build_date_range_extraction_prompt("last Monday", datetime.date(2026, 12, 31))
        assert "2026-12-31" in prompt
        assert "2026-01-01" not in prompt

    def test_purpose_hint_still_included_when_given(self):
        prompt = _build_date_range_extraction_prompt(
            "last Monday", datetime.date(2026, 1, 1), purpose_hint="a leave status filter",
        )
        assert "a leave status filter" in prompt

    def test_purpose_hint_optional(self):
        prompt = _build_date_range_extraction_prompt("last Monday", datetime.date(2026, 1, 1))
        assert "2026-01-01" in prompt


class TestStructuredDateExtractionPromptWeekVsWeekday:
    """Live bug, found by mining real production queries: for 'next to next
    month first week sick leave' (no weekday named at all), the model set
    target_weekday='monday' anyway — hallucinating a specific day out of
    an ordinal + 'week' context alone, even though target_weekday's own
    rule already said 'if the message names a weekday'. tier1 has no
    coverage for month_offset>=2 combined with 'week' (only month_offset=1
    via resolve_week_of_next_month_phrase), so this reached tier 2, which
    then produced a specific, wrong-looking day nobody asked for.
    resolve_structured_date requires target_weekday to compute anything
    from the ordinal+month_offset shape, so a hallucinated weekday here
    silently produces a full, confident (but baseless) date."""

    def test_prompt_explicitly_excludes_week_from_meaning_weekday(self):
        prompt = _build_structured_date_extraction_prompt("first week of next month", datetime.date(2026, 8, 24))
        assert "is not a weekday" in prompt.lower() or "is not a weekday" in prompt
        assert "first week of next month" in prompt.lower()
        assert "first monday of next month" in prompt.lower()
