"""
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

import services.ai_service as ai_service

from services.ai_service import (
    _build_leave_slot_extraction_prompt,
    _build_structured_date_extraction_prompt,
    _build_date_range_extraction_prompt,
    _build_shift_target_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()


# -- Employee code vs bare id (FR-07.3) ---------------------------------------

class TestCodeTokenGuard:
    """Live regression: asked about "EMP-578", extraction returned
    employee_id 578. erp-api 403s that id ("not found in your team"), which
    this app correctly renders as AC4's denial - so a legitimate report
    looked out of scope. The whole token is recovered here rather than
    trusting the model to follow the instruction not to split it."""

    def test_hyphenated_code_is_recovered(self):
        assert ai_service._code_token_for(
            "why was EMP-578 marked half day on 27 july", 578) == "EMP-578"

    def test_lowercase_codes_are_recovered(self):
        assert ai_service._code_token_for("why was geo6 marked absent", 6) == "geo6"
        assert ai_service._code_token_for("why was em10 marked absent", 10) == "em10"
        assert ai_service._code_token_for("leave request of User1", 1) == "User1"

    def test_bare_id_is_left_alone(self):
        """An explicitly stated numeric id must keep working."""
        assert ai_service._code_token_for("show leave request of employee 3735", 3735) is None
        assert ai_service._code_token_for("show leave request of employee id 616", 616) is None

    def test_number_absent_from_the_query_yields_nothing(self):
        assert ai_service._code_token_for("why was he marked absent", 42) is None

    def test_date_digits_are_not_mistaken_for_a_code(self):
        """"27 july" must not be read as a code carrying the id 27."""
        assert ai_service._code_token_for("marked half day on 27 july", 27) is None


class TestPronounNameGuard:
    """Live regression: extraction returns employee_name "he" AND
    uses_pronoun true, inconsistently. Left through, the node searches
    erp-api for an employee called "he", matches nobody, and answers a
    pronoun follow-up with a roster prompt instead of the subject it
    already knows."""

    def test_pronouns_are_recognised(self):
        for word in ("he", "She", "THEY", "him", "her", "them", "their",
                     "this employee", "that person", "he?"):
            assert ai_service._is_pronoun_name(word) is True, word

    def test_real_identifiers_are_not_pronouns(self):
        for word in ("Ayush", "Ayush Jio", "geo3", "EMP-578", "Priya", "User1"):
            assert ai_service._is_pronoun_name(word) is False, word


class TestShiftTargetExtractionPromptSafety:
    """HA-192 (FR-06.4) leans on this extraction to decide whether a shift
    query is about the caller or a teammate. The one failure mode that
    matters: a message that only MENTIONS a colleague for context ("I'm
    covering for Sarah, what's my shift?") must not come back with that
    colleague as the target, or the caller is wrongly denied their own
    shift. That is a prompt-level instruction, asserted here so a future
    edit can't silently drop it (behavior verified against the real LLM
    separately, not in CI)."""

    def _prompt(self, query):
        return _build_shift_target_extraction_prompt(query, datetime.date(2026, 9, 3))

    def test_prompt_tells_the_model_to_ignore_a_context_only_mention(self):
        p = self._prompt("I'm covering for Sarah today, what's my shift?")
        assert "context" in p.lower()
        assert "covering for" in p.lower()

    def test_prompt_still_defines_own_shift_as_no_target(self):
        p = self._prompt("what shift am I on")
        assert "own shift" in p.lower()
