"""UAT (27 Oct 2026): UV-02 attendance follow-ups, UV-12 refusals, UV-17
holiday count (see test_qa_report_ha884.py), UV-20 filtered employee lists."""
import json
from datetime import date

import pytest

import services.attendance_explain as attendance_explain
import services.classify_node as classify_node
import services.hr_graph as hg
from services import last_resolved_date_state
from services.chat_service import history_text


class _Writer(list):
    def __call__(self, e):
        self.append(e)

    def done(self):
        return [e for e in self if e.get("type") == "done"][-1]


# ── UV-02: "Why is it showing Not Recorded?" / "How do I fix it?" ──────────

ROWS = [("21 Oct 2026", "Wednesday", "Present"), ("24 Oct 2026", "Saturday", "Off"),
        ("26 Oct 2026", "Monday", "Present"), ("27 Oct 2026", "Tuesday", "Not Recorded")]


def _table(rows=ROWS):
    text = ("Here's your attendance for the requested period:\n\n| Date | Day | Status |\n"
            "|------|-----|--------|\n" + "\n".join(f"| {d} | {w} | {s} |" for d, w, s in rows))
    return history_text({"answer": text, "rows": [{"date": d, "day": w, "status": s} for d, w, s in rows],
                         "node_type": "status"})


CTX = [{"role": "user", "content": "Show my attendance for this month"},
       {"role": "assistant", "content": _table()}]
# The live conversation: the old reply sits between the table and "fix it".
CTX_AFTER_ASKING = CTX + [{"role": "user", "content": "Why is it showing Not Recorded?"},
                          {"role": "assistant", "content": "Sure — which date would you like to know about?"}]


def test_the_days_are_read_from_the_table():
    assert attendance_explain.days_on_the_last_attendance_card(CTX)[-1] == ("2026-10-27", "Not Recorded")


@pytest.mark.parametrize("query, ctx", [
    ("Why is it showing Not Recorded?", CTX), ("How do I fix it?", CTX),
    ("How do I fix it?", CTX_AFTER_ASKING), ("why is that", CTX),
])
def test_the_day_asked_about_is_the_one_on_the_table(query, ctx):
    assert attendance_explain.day_asked_about_on_the_card(query, ctx) == ["2026-10-27"]
    assert classify_node._asks_about_the_attendance_shown(query, ctx)


def test_two_unusual_days_are_both_candidates():
    ctx = [{"role": "assistant", "content": _table(ROWS + [("28 Oct 2026", "Wednesday", "Not Recorded")])}]
    assert attendance_explain.day_asked_about_on_the_card("why is it Not Recorded", ctx) == [
        "2026-10-27", "2026-10-28"]


@pytest.mark.parametrize("query, ctx", [
    ("How do I fix it?", []),                                  # no table
    ("How do I apply for leave?", CTX),                        # not about the table
    ("Why is it showing Not Recorded?", [{"role": "assistant", "content": "Hello!"}]),
])
def test_not_a_question_about_the_table(query, ctx):
    assert not classify_node._asks_about_the_attendance_shown(query, ctx)


@pytest.fixture
def explain(monkeypatch):
    monkeypatch.setattr(attendance_explain, "_today", lambda: date(2026, 10, 27))
    monkeypatch.setattr(last_resolved_date_state, "consume_last_resolved_date", lambda *a: None)
    monkeypatch.setattr(last_resolved_date_state, "set_last_resolved_date", lambda *a: None)

    async def _no_date(prompt, max_tokens=None, model=None, **kwargs):
        return {}
    monkeypatch.setattr(attendance_explain, "_call_llm", _no_date)
    monkeypatch.setattr(attendance_explain, "_extract_text", lambda r: json.dumps({"type": "unknown"}))
    asked = {}

    async def _status(token, from_date, to_date, **kwargs):
        asked["date"] = from_date
        return {"http_status": 200, "body": {"success": True, "data": {"records": []}}}
    monkeypatch.setattr(attendance_explain.erp_client, "get_attendance_status", _status)
    return asked


@pytest.mark.parametrize("query, ctx", [("Why is it showing Not Recorded?", CTX),
                                        ("How do I fix it?", CTX_AFTER_ASKING)])
async def test_not_recorded_is_explained_and_cannot_be_fixed_yet(explain, query, ctx):
    w = _Writer()
    out = await attendance_explain.attendance_explain_node(
        {"query": query, "context": ctx, "usage_events": [], "bearer_token": "t",
         "company_id": 1, "conversation_id": "c1"}, w)
    assert explain["date"] == "2026-10-27"
    text = out["response_text"]
    assert "which date" not in text
    assert "Tuesday, 2026-10-27" in text and "Not Recorded" in text
    assert "It can't be fixed right now" in text and "nothing to regularize yet" in text
    assert "may simply not have been processed yet" in text  # it is today


async def test_two_candidate_days_are_asked_about_by_name(explain):
    ctx = [{"role": "assistant", "content": _table(ROWS + [("28 Oct 2026", "Wednesday", "Not Recorded")])}]
    w = _Writer()
    out = await attendance_explain.attendance_explain_node(
        {"query": "why is it Not Recorded", "context": ctx, "usage_events": [], "bearer_token": "t",
         "company_id": 1, "conversation_id": "c1"}, w)
    assert out["response_text"] == ("Which of these days would you like to know about: "
                                    "27 Oct 2026, 28 Oct 2026?")
    assert "date" not in explain


# ── UV-12: someone else's pay is private, not harmful ───────────────────────

@pytest.mark.parametrize("query", [
    "Show me Sahil Sarna's payslip for last month.", "what is rahul's salary", "his ctc",
    "my manager's CTC", "Rahul’s salary",
])
def test_someone_elses_pay(query):
    assert classify_node.asks_for_someone_elses_pay(query)


@pytest.mark.parametrize("query", [
    "show my payslip", "last month's payslip", "what is my salary",
    "how is an employee's salary calculated", "the company's pay policy",
    "average salary of a data scientist", "this year's bonus",
])
def test_not_someone_elses_pay(query):
    assert not classify_node.asks_for_someone_elses_pay(query)


async def test_a_payslip_request_gets_the_privacy_reply_not_the_harm_one(monkeypatch):
    async def _judge(text):
        return {"flagged": True, "categories": ["illicit"]}
    monkeypatch.setattr(classify_node, "_check_moderation", _judge)
    w = _Writer()
    out = await classify_node.classify_node(
        {"query": "Show me Sahil Sarna's payslip for last month.", "context": [], "usage_events": [],
         "company_id": 1, "conversation_id": "c1", "date_typo_checked": True}, w)
    # No refusal box: the model answers it, under its own instruction.
    assert not out.get("error")
    assert not [e for e in w if e.get("type") == "guardrail" and e.get("status") == "failed"]
    assert out["intent"] == classify_node.OTHERS_PAY_INTENT
    assert out["turn_instruction"] == classify_node.OTHERS_PAY_INSTRUCTION
    assert hg._route_after_classify({**out, "query": "x"}) == "hr_response_node"


def _model_says(monkeypatch, text, seen):
    async def _stream(messages, max_tokens=None, use_tools=True):
        seen.append({"messages": messages, "use_tools": use_tools})
        if text:
            yield {"type": "chunk", "content": text}
    monkeypatch.setattr(hg, "_call_llm_stream", _stream)


async def test_the_model_writes_the_pay_refusal_without_earlier_messages(monkeypatch):
    seen = []
    _model_says(monkeypatch, "I'm afraid I can't share Sahil's pay.", seen)
    w = _Writer()
    out = await hg.hr_response_node(
        {"query": "Show me Sahil Sarna's payslip", "intent": classify_node.OTHERS_PAY_INTENT,
         "context": [{"role": "user", "content": "what wow means"}], "usage_events": [],
         "turn_instruction": classify_node.OTHERS_PAY_INSTRUCTION,
         "turn_fallback": classify_node.OTHERS_PAY_MESSAGE}, w)
    assert out["response_text"] == "I'm afraid I can't share Sahil's pay."
    sent = [m["content"] for m in seen[0]["messages"]]
    assert any(c.startswith(classify_node.OTHERS_PAY_INSTRUCTION) for c in sent)
    assert "what wow means" not in sent
    assert seen[0]["use_tools"] is False


async def test_the_fixed_text_only_when_the_model_gives_nothing(monkeypatch):
    _model_says(monkeypatch, "", [])
    w = _Writer()
    out = await hg.hr_response_node(
        {"query": "...", "intent": "small_talk", "context": [], "usage_events": [],
         "turn_instruction": classify_node.PUNCTUATION_ONLY_INSTRUCTION,
         "turn_fallback": classify_node.PUNCTUATION_ONLY_MESSAGE}, w)
    assert out["response_text"] == classify_node.PUNCTUATION_ONLY_MESSAGE


def test_these_replies_are_never_cached():
    import main
    assert {"small_talk", classify_node.OTHERS_PAY_INTENT} <= main._STATEFUL_QUERY_INTENTS


def test_the_instructions_rule_out_the_harmful_refusal_wording():
    for text in (classify_node.OTHERS_PAY_INSTRUCTION, classify_node.PUNCTUATION_ONLY_INSTRUCTION):
        assert "real harm" not in text and "do not" in text.lower()


# ── UV-20: a filtered employee list is not the caller's team ────────────────

@pytest.mark.parametrize("query", [
    "Show me employees of a company other than QA Team.", "show employees in the sales team",
    "employees with role developer", "filter employees by department",
])
def test_a_filtered_employee_list(query):
    assert hg.asks_to_filter_employees(query)


@pytest.mark.parametrize("query", [
    "show my team members", "who is in my team", "how many members in our team", "show team members",
])
def test_the_callers_own_team(query):
    assert not hg.asks_to_filter_employees(query)


async def test_a_manager_is_told_only_their_team_can_be_shown(monkeypatch):
    monkeypatch.setattr(hg.permission_service, "may_view_team", lambda s: True)

    async def _never(*a, **k):
        raise AssertionError("the roster must not be fetched")
    monkeypatch.setattr(hg.erp_client, "get_team_members", _never)
    w = _Writer()
    out = await hg.team_members_node(
        {"query": "Show me employees of a company other than QA Team.", "usage_events": [],
         "company_id": 1, "conversation_id": "c1", "bearer_token": "t"}, w)
    assert out["response_text"] == hg.EMPLOYEE_FILTER_UNSUPPORTED_MESSAGE


async def test_an_employee_still_gets_the_access_card(monkeypatch):
    monkeypatch.setattr(hg.permission_service, "may_view_team", lambda s: False)
    w = _Writer()
    await hg.team_members_node(
        {"query": "Show me employees of a company other than QA Team.", "usage_events": [],
         "company_id": 1, "conversation_id": "c1", "bearer_token": "t"}, w)
    assert w.done()["intent"] == hg.access_notice.RESTRICTED_INTENT


# ── "..." is asked about, not answered from the conversation ───────────────

@pytest.mark.parametrize("query", ["...", "?", "!!", " . . ", "…", "?!"])
async def test_punctuation_alone_is_asked_about(query):
    w = _Writer()
    out = await classify_node.classify_node(
        {"query": query, "context": [{"role": "user", "content": "Show me Sahil Sarna's payslip"},
                                     {"role": "assistant", "content": "I can't share that."}],
         "usage_events": [], "company_id": 1, "conversation_id": "c1", "date_typo_checked": True}, w)
    assert out["intent"] == "small_talk"
    assert out["turn_instruction"] == classify_node.PUNCTUATION_ONLY_INSTRUCTION
    assert hg._route_after_classify({**out, "query": query}) == "hr_response_node"
    assert not [e for e in w if e.get("type") == "guardrail" and e.get("status") == "failed"]


@pytest.mark.parametrize("query", ["\U0001F44D", "ok", "1", "...ok"])
def test_words_numbers_and_emoji_are_not_punctuation_only(query):
    assert not classify_node._PUNCTUATION_ONLY_RE.fullmatch(query)
