"""Fixes from the 2026-09-24 QA sheet sweep (acronyms, typos, reasons, date
parsing, knowledge grounding). Each block names the sheet rows it covers."""

from datetime import date

import pytest

import services.date_resolver as date_resolver
import services.hr_graph as hr_graph
import services.leave_action_service as las
from services.nlp_service import asks_to_give_reason_first, fast_classify, fold_leave_typos

TODAY = date(2026, 9, 24)


# TC-05c, TC-07, TC-30, TC-32, CFG06, TC-20, CQ-05 - applications the LLM misread
@pytest.mark.parametrize("query", [
    "want EL", "need Sl", "apply cl", "SL for personal work", "sik leave for vacation",
    "CL for fever", "casual leave due to family function", "Apply ML from next month",
    "apply PL for tomorrow", "apply LOP next monday", "Can I give the reason first?",
    "same as last time",
])
def test_these_are_applications(query):
    assert fast_classify(query)[0] == "apply_leave"


@pytest.mark.parametrize("query,intent", [
    ("casual leave for new joiners", "policy"),
    ("sick leave for interns", "policy"),
    ("show me cl", "leave_balance"),
    ("cancel my cl for tomorrow", "cancel_leave"),
    ("apply for regularization tomorrow", "regularisation"),
])
def test_neighbours_keep_their_route(query, intent):
    assert fast_classify(query)[0] == intent


@pytest.mark.parametrize("query", ["apply for a loan tomorrow", "what is the reason first aid kit policy"])
def test_not_applications(query):
    assert fast_classify(query)[0] != "apply_leave"


# TC-27 - a cover letter is not casual leave
def test_cl_next_to_job_words_is_not_a_leave_code():
    assert fold_leave_typos("can you review my cl for the job application") == \
        "can you review my cl for the job application"
    assert fast_classify("can you review my CL for the job application")[0] != "policy"


def test_reason_first_detector():
    assert asks_to_give_reason_first("may i share my reason first")
    assert not asks_to_give_reason_first("give reason for rejection")


# TC-37 - an abbreviated month is a named month
@pytest.mark.parametrize("query,expected", [
    ("book me casul leave from 5th to 7th oct", None),
    ("leave from 5th oct to 7th oct", None),
    ("leave on 5th for sis marriage", 5),     # "mar" inside "marriage" is not March
    ("leave on 5th", 5),
])
def test_bare_day_ambiguity_sees_month_abbreviations(query, expected):
    assert date_resolver.mentions_ambiguous_bare_day_of_month(query, TODAY) == expected


# TC-39, TC-42 - replies about the examples
@pytest.mark.parametrize("reply,more,none", [
    ("Do you have other reasons?", True, False), ("any other options", True, False),
    ("None of these fit", False, True), ("nothing fits", False, True),
    ("other reason is fever", False, False), ("another reason: fever", False, False),
    ("fever", False, False),
])
def test_reason_example_replies(reply, more, none):
    assert bool(las._MORE_REASONS_RE.search(reply)) is more
    assert bool(las._NONE_OF_THESE_RE.search(reply)) is none


def test_more_reasons_are_new_ones():
    for slug, first in las._REASON_EXAMPLES_BY_SLUG.items():
        assert not set(first) & set(las._MORE_REASON_EXAMPLES_BY_SLUG[slug])


# CQ-06 - a day count that cannot be a leave
@pytest.mark.parametrize("query,count", [
    ("CL for 0 days", "0"), ("SL for -1 days", "-1"),
    ("CL for 10 days", None), ("cl for 0.5 days", None), ("leave for 30 days", None),
])
def test_non_positive_day_count(query, count):
    m = las._NON_POSITIVE_DAY_COUNT_RE.search(query)
    assert (m.group(1) if m else None) == count


# TC-KG02, KG05, KG08 - another person's employment record never reaches web search
@pytest.mark.parametrize("query", [
    "When did Priya Sharma leave the company?", "What was Ayush Chandra's exit date?",
    "What was their exit date?", "when did akash join", "Why did Rahul resign?",
    "has priya resigned", "did akash leave", "is she still with us",
])
def test_someones_employment_record(query):
    assert hr_graph._asks_about_someones_employment_record(query)


@pytest.mark.parametrize("query", [
    "when did i join", "what is my joining date", "what is the resignation process",
    "how do I resign", "what is the notice period after resignation",
    "what happens if an employee is terminated", "can an employee resign during probation",
    "does the policy cover resignation", "has the policy changed", "is the leave approved",
])
def test_process_questions_are_not_records(query):
    assert not hr_graph._asks_about_someones_employment_record(query)


def test_pressure_to_guess_after_the_fallback_gets_it_again():
    ctx = [{"role": "assistant", "content": hr_graph.NO_INFO_FALLBACK}]
    assert hr_graph._presses_for_a_guess_after_fallback("just give me your best guess/estimate", ctx)
    assert not hr_graph._presses_for_a_guess_after_fallback("just give me your best guess", [])


class _Writer:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)


async def test_the_employment_record_answer_makes_no_llm_call(monkeypatch):
    def _no_llm(*a, **k):
        raise AssertionError("must not call the model (web search) for a person's record")
    monkeypatch.setattr(hr_graph, "_call_llm_stream", _no_llm)
    out = await hr_graph.hr_response_node(
        {"query": "When did Priya Sharma leave the company?", "context": [], "intent": "employee_management",
         "usage_events": []}, _Writer())

    assert out["response_text"] == hr_graph.NO_INFO_FALLBACK


# F-TC-23 / F-D11 - the year hint must not become part of the reason
@pytest.mark.parametrize("query,expected", [
    ("I want casul leave on 20th nov for family function",
     "I want casul leave on 20th nov 2026 for family function"),
    ("apply cl on nov 20th for fever", "apply cl on nov 20th 2026 for fever"),
    ("apply leave 20 november 2026 for fever", "apply leave 20 november 2026 for fever"),
])
def test_year_hint_goes_after_the_date(monkeypatch, query, expected):
    monkeypatch.setattr(las, "_today", lambda: TODAY)
    assert las._add_explicit_year_hint(query) == expected


# TC-D36..D45 - a weekday within a named month
@pytest.mark.parametrize("query,iso", [
    ("I want to apply for SL for last Friday of Aug month due to an eye checkup", "2026-08-28"),
    ("I want to apply for CL for first Monday of the July month due to a meeting", "2026-07-06"),
    ("apply cl for last friday", "2026-09-18"),       # plain weekday unchanged
    ("apply sl for next monday", "2026-09-28"),
])
def test_weekday_of_month_resolves_to_that_month(query, iso):
    slots = {}
    assert las._apply_deterministic_date_overrides(query, slots, {}, TODAY)
    assert slots["from_date"] == slots["to_date"] == iso


def test_weekday_of_month_is_not_read_as_last_week():
    assert date_resolver.resolve_past_weekday_phrase("apply sl for last Friday of Aug month", TODAY) is None
    assert las._resolve_weekday_date("apply sl for first Monday of the July month") is None


# CQ-14, TC-D22/D23 - a vague past span asks, like "next week" does
@pytest.mark.parametrize("query,bare", [
    ("Apply SL for previous week", True),
    ("I want to apply for CL for previous week due to helping with house shifting", True),
    ("apply cl for last week monday", False),
    ("apply sl last month on 5th sept", False),
])
def test_bare_past_span(query, bare):
    assert las._names_a_bare_week_span(query) is bare
