"""QA QF-01 / QF-02 (26 Oct): follow-ups whose subject is only in the answer
before them.

QF-01  "Show the holiday list for 2026" -> "When is the next one?" invented
       a date each run ("Wednesday, 1 November 2026" - a Sunday). The
       follow-up has no holiday word, so it missed the holiday route and the
       model answered with no calendar.
QF-02  "Who is my reporting manager?" -> "How do I contact them?" showed the
       caller's own team roster ("Your Team - 18 members").
"""
from datetime import date

import pytest

import services.erp_client as erp_client
import services.hr_graph as hr_graph
import services.reporting_manager as rm
from services.classify_node import _is_holiday_followup

from tests.test_bare_name_continuation import _mocks, _state, FakeWriter

pytestmark = pytest.mark.asyncio


# ── QF-02: contact follow-up to the reporting-manager answer ─────────────────

@pytest.mark.parametrize("query", [
    "How do I contact them?", "how can I reach him?", "what's her email?",
    "can I call my manager?", "how do i get in touch with them", "give me their number",
])
def test_contact_followups_are_recognised(query):
    assert rm.is_contact_followup(query, rm.INTENT)
    assert rm.is_contact_followup(query, rm.CONTACT_INTENT)


@pytest.mark.parametrize("query,last_intent", [
    ("How do I contact them?", None),                      # nothing before it
    ("How do I contact them?", "HRMS_TEAM_MEMBERS_QUERY"),  # "them" = the team on screen
    ("how do I contact HR?", rm.INTENT),                   # not about the manager
    ("show my team members", rm.INTENT),
    ("thanks", rm.INTENT),
])
def test_everything_else_is_not(query, last_intent):
    assert not rm.is_contact_followup(query, last_intent)


@pytest.mark.parametrize("is_manager", [True, False])
async def test_contact_followup_is_not_the_team_roster(is_manager):
    with _mocks(detected="HRMS_TEAM_MEMBERS_QUERY") as m:
        result = await hr_graph.classify_node(
            _state("How do I contact them?", last_intent=rm.INTENT, is_manager=is_manager),
            FakeWriter())

    assert result["intent"] == rm.CONTACT_INTENT
    assert not m["classify"].called
    assert hr_graph._route_after_classify(result) == "reporting_manager_node"


def _leaves(*rows):
    return {"http_status": 200, "body": {"success": True, "data": {"leaves": list(rows)}}}


def _patch_leaves(monkeypatch, pending, applied=None):
    async def _pending(*a, **k):
        return pending

    async def _applied(*a, **k):
        return applied if applied is not None else _leaves()
    monkeypatch.setattr(erp_client, "get_pending_leaves", _pending)
    monkeypatch.setattr(erp_client, "get_applied_leaves", _applied)


def _contact_state():
    return {"query": "How do I contact them?", "intent": rm.CONTACT_INTENT, "company_id": 7,
            "conversation_id": "conv-1", "bearer_token": "t", "usage_events": []}


async def test_contact_names_the_manager_and_invents_no_details(monkeypatch):
    # The row shape the user shared from /leave/applied {"leave_status": "all"}.
    _patch_leaves(monkeypatch, _leaves(), _leaves({
        "id": 372, "leave_type": "Casual Leave", "status_name": "pending",
        "approver_name": "Ayush Chandra", "role": "manager", "applied_date": "2026-09-28"}))
    writer = FakeWriter()

    out = await rm.reporting_manager_node(_contact_state(), writer)

    assert out["response_text"] == rm.CONTACT_KNOWN_MESSAGE.format(manager="Ayush Chandra")
    assert "@" not in out["response_text"]
    assert writer.of_type("done")[0]["intent"] == rm.CONTACT_INTENT


async def test_contact_with_no_manager_found_points_to_hr(monkeypatch):
    # Approved leaves name the HR approver: never the reporting manager.
    _patch_leaves(monkeypatch, _leaves(), _leaves(
        {"approver_name": "Priya HR", "role": "hr", "status_name": "approved"}))

    out = await rm.reporting_manager_node(_contact_state(), FakeWriter())

    assert out["response_text"] == rm.CONTACT_NOT_FOUND_MESSAGE


async def test_contact_with_erp_down_still_points_to_hr(monkeypatch):
    async def _down(*a, **k):
        raise erp_client.ErpApiUnavailable("down")
    monkeypatch.setattr(erp_client, "get_pending_leaves", _down)

    out = await rm.reporting_manager_node(_contact_state(), FakeWriter())

    assert out["response_text"] == rm.CONTACT_UNREACHABLE_MESSAGE


# ── QF-01: follow-up to the holiday answer ───────────────────────────────────

@pytest.mark.parametrize("query", [
    "When is the next one?", "and after that?", "which day is it?",
    "how many are left?", "what's the next one", "show all",
])
def test_holiday_followups_are_recognised(query):
    assert _is_holiday_followup(query, "leave_holidays")


@pytest.mark.parametrize("query,last_intent", [
    ("When is the next one?", None),
    ("When is the next one?", "leave_balance"),
    ("what is my leave balance?", "leave_holidays"),     # a new question
    ("apply leave for the next one", "leave_holidays"),
    ("thanks", "leave_holidays"),
])
def test_other_messages_are_not_holiday_followups(query, last_intent):
    assert not _is_holiday_followup(query, last_intent)


async def test_holiday_followup_is_classified_without_the_llm():
    with _mocks(detected="policy") as m:
        result = await hr_graph.classify_node(
            _state("When is the next one?", last_intent="leave_holidays", is_manager=False),
            FakeWriter())

    assert result["intent"] == "leave_holidays"
    assert not m["classify"].called
    assert hr_graph._route_after_classify(result) == "hr_response_node"


def _hr_state(query):
    return {"query": query, "intent": "leave_holidays", "context": [], "bearer_token": "t",
            "company_id": "3735", "conversation_id": "conv-1", "usage_events": []}


@pytest.fixture
def no_model(monkeypatch):
    def _fail(*a, **k):
        raise AssertionError("the model must not answer a holiday question")
    monkeypatch.setattr(hr_graph, "_call_llm_stream", _fail)
    monkeypatch.setattr(hr_graph, "_today_in_app_timezone", lambda: date(2026, 10, 26))


async def test_no_calendar_gives_the_same_answer_not_a_date(monkeypatch, no_model):
    async def _none(*a, **k):
        return {"http_status": 200, "body": {
            "success": False, "message": "The holiday list is not available for your department."}}
    monkeypatch.setattr(hr_graph.erp_client, "get_leave_holidays", _none)

    out = await hr_graph.hr_response_node(_hr_state("When is the next one?"), FakeWriter())

    assert out["response_text"] == "The holiday list is not available for your department."


async def test_with_a_calendar_the_real_next_holiday_is_given(monkeypatch, no_model):
    async def _cal(*a, **k):
        return {"http_status": 200, "body": {"success": True, "data": {"holidays": [
            {"holiday_name": "Gandhi Jayanti", "holiday_date": "2026-10-02"},
            {"holiday_name": "Diwali", "holiday_date": "2026-11-08"},
            {"holiday_name": "Christmas", "holiday_date": "2026-12-25"},
        ]}}}
    monkeypatch.setattr(hr_graph.erp_client, "get_leave_holidays", _cal)

    out = await hr_graph.hr_response_node(_hr_state("When is the next one?"), FakeWriter())

    assert out["response_text"].startswith("Your next holiday is Diwali - Sun, 08 Nov 2026.")
    assert "Gandhi Jayanti" not in out["response_text"]
