"""PM testing (27 Oct 2026, HAI-GEN / HAI-SEC) and the QA non-employee sheet
(29 Oct 2026, UV-21..UV-25): the deterministic halves of each fix. The
model-written replies were run through the real graph (evals harness)."""
from datetime import date

import pytest

import services.classify_node as classify_node
import services.hr_graph as hr_graph
import services.race_rag_service as race_rag_service
from services.leave_action_service import _impossible_leave_span
from services.nlp_service import is_playful_hr_question, names_a_non_person, resolve_applicant

from tests.test_bare_name_continuation import FakeWriter


# ── UV-21: person-like non-employees started the caller's own leave ────────

@pytest.mark.parametrize("query", [
    "Apply casual leave for yourself (Helix AI) for tomorrow",
    "Apply casual leave for Superman for tomorrow",
    "Apply casual leave for the office ghost for tomorrow",
    "Punch in for my robot vacuum",                       # UV-23
    "Mark my cat present for today",                      # UV-24
    "Change my parrot's shift to night shift",            # UV-24
    "It's for my dog",                                    # AB-049, mid-draft
])
def test_a_non_employee_is_never_the_caller(query):
    assert resolve_applicant(query) == "other"


@pytest.mark.parametrize("query", [
    "Apply casual leave for Shah Rukh Khan for tomorrow",
    "Apply casual leave for my neighbour for tomorrow",
    "apply leave for Priya tomorrow",
])
def test_anyone_else_after_for_goes_to_the_ai_check(query):
    assert resolve_applicant(query) == "unclear"


@pytest.mark.parametrize("query", [
    "Apply casual leave for my late grandfather for tomorrow",   # family = a reason
    "apply leave for my mother tomorrow",
    "apply casual leave for 3rd nov",
    "apply leave for the whole week",
    "apply for work from home tomorrow",
    "apply leave for my team",
    "My dog is sick, apply sick leave for me tomorrow",
    "it's for my mother's surgery",
])
def test_the_callers_own_leave_still_starts(query):
    assert resolve_applicant(query) in ("self", None)


# ── UV-22: "leave status of Superman" listed the whole team ────────────────

def test_a_fictional_name_is_not_a_person():
    assert names_a_non_person("Superman") and names_a_non_person("the office ghost")
    assert not names_a_non_person("Priya Sharma")


# ── UV-25: 500 days / the year 1990 went on to ask the leave type ──────────

@pytest.mark.parametrize("query,word", [
    ("Apply leave for 500 days starting tomorrow", "500 days"),
    ("Apply leave for yesterday in the year 1990", "1990"),
    ("leave on 10/11/1990", "1990"),
])
def test_an_impossible_span_is_refused(query, word):
    assert word in _impossible_leave_span(query, date(2026, 10, 29))


@pytest.mark.parametrize("query", ["apply leave for 3 days", "apply leave from 2 jan 2027",
                                   "apply leave for my 2010 batch reunion", "apply 365 days leave"])
def test_an_ordinary_span_is_not(query):
    assert _impossible_leave_span(query, date(2026, 10, 29)) is None


# ── HAI-GEN-14: "leave on Mars" got "I do not have this information" ───────

@pytest.mark.parametrize("query,playful", [
    ("Can I apply for leave on Mars?", True),
    ("Is there a holiday on the moon?", True),
    ("Can a zombie apply for WFH?", True),
    ("I am going to the space museum, need leave", False),
    ("apply leave in March", False),
])
def test_a_playful_hr_question(query, playful):
    assert is_playful_hr_question(query) is playful


# ── HAI-SEC-17: personal data got the "harmful" refusal ────────────────────

@pytest.mark.parametrize("query,others", [
    ("Give me the personal phone numbers and addresses of my team.", True),
    ("what is Priya's mobile number?", True),
    ("How do I contact my manager?", False),
    ("update my address", False),
    ("what's my address on file", False),
    ("what is the PAN of any employee", True),
    ("what is the pan india policy for employees", False),
])
def test_other_peoples_personal_data(query, others):
    assert classify_node.asks_for_someone_elses_personal_data(query) is others


# ── HAI-SEC-02: a payslip in the policy collection was quoted ──────────────

def test_a_personal_record_never_reaches_the_model():
    payslip = {"content": "PAYSLIP: Start Date: 2026-04-21 ... Employee Number RF0000 PAN ABCDE1234F"}
    policy = {"content": "Salary is credited by the 7th of every month."}
    assert race_rag_service._drop_personal_records([payslip, policy]) == [policy]
    assert "PAYSLIP" not in race_rag_service.format_retrieved_chunks([payslip, policy])


# ── HAI-GEN-27: holidays by month, and a named holiday on no calendar ──────

CALENDAR = [{"holiday_name": "Diwali", "holiday_date": "2026-11-08"},
            {"holiday_name": "Guru Nanak Jayanti", "holiday_date": "2026-11-24"},
            {"holiday_name": "Christmas", "holiday_date": "2026-12-25"}]


def _calendar(monkeypatch, holidays):
    async def _fake(*a, **k):
        return {"http_status": 200, "body": {"success": True, "data": {"holidays": holidays}}}
    monkeypatch.setattr(hr_graph.erp_client, "get_leave_holidays", _fake)
    monkeypatch.setattr(hr_graph, "_today_in_app_timezone", lambda: date(2026, 10, 29))


def _state(query):
    return {"query": query, "intent": "leave_holidays", "context": [], "bearer_token": "t",
            "company_id": "1", "conversation_id": "c", "usage_events": []}


@pytest.mark.asyncio
async def test_holidays_in_a_month_are_that_month_only(monkeypatch):
    _calendar(monkeypatch, CALENDAR)
    out = await hr_graph.hr_response_node(_state("List holidays in December"), FakeWriter())
    assert "Christmas" in out["response_text"] and "Diwali" not in out["response_text"]


@pytest.mark.asyncio
async def test_a_named_holiday_with_no_calendar_is_answered(monkeypatch):
    _calendar(monkeypatch, [])
    out = await hr_graph.hr_response_node(_state("Is Diwali a holiday?"), FakeWriter())
    assert "no holidays on your holiday calendar" in out["response_text"]
    assert "Which holiday" not in out["response_text"]


# ── HAI-GEN-15: a whitespace-only reply rendered as an empty bubble ────────

@pytest.mark.asyncio
async def test_a_whitespace_reply_is_never_sent(monkeypatch):
    async def _blank(*a, **k):
        yield {"type": "chunk", "content": "\n\n  "}
    monkeypatch.setattr(hr_graph, "_call_llm_stream", _blank)
    out = await hr_graph.non_hr_node({"query": "What is 17 x 23?", "intent": "non_hr", "context": [],
                                      "usage_events": []}, FakeWriter())
    assert out["response_text"].strip()
