""""Is it a holiday in our company?" (QA LT-06 T7, about Diwali) and "Summary
de do" (LT-06 T10).

T7 went to the policy documents: "Yes, Diwali is listed as a company holiday"
in one run, "not a company holiday ... only Wednesdays and Sat/Sun" in QA's
other. Whether a day is a holiday is answered from the caller's holiday
calendar (/leave/holidays) or not at all.

T10 reached the whole-chat node and still summarised only the last answer.
"""
from datetime import date

import pytest

import services.hr_graph as hr_graph

from tests.test_bare_name_continuation import FakeWriter

pytestmark = pytest.mark.asyncio

CALENDAR = [
    {"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"},
]
DIWALI_CHAT = [
    {"role": "user", "content": "Diwali kya hai?"},
    {"role": "assistant", "content": "Diwali is the festival of lights."},
    {"role": "user", "content": "When is it in 2026?"},
    {"role": "assistant", "content": "Sunday, 8 November 2026."},
]


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


def _calendar(monkeypatch, holidays=None, unavailable=None):
    async def _fake(*a, **k):
        if unavailable:
            return {"http_status": 200, "body": {"success": False, "message": unavailable}}
        return {"http_status": 200, "body": {"success": True, "data": {"holidays": holidays}}}
    monkeypatch.setattr(hr_graph.erp_client, "get_leave_holidays", _fake)


def _state(query, context=None, intent="policy"):
    return {"query": query, "intent": intent, "context": context or [], "bearer_token": "t",
            "company_id": "3735", "conversation_id": "conv-1", "usage_events": []}


async def test_the_holiday_from_the_conversation_is_checked(monkeypatch, no_model):
    _calendar(monkeypatch, CALENDAR)

    out = await hr_graph.hr_response_node(_state("Is it a holiday in our company?", DIWALI_CHAT),
                                          FakeWriter())

    assert out["response_text"] == "Yes - Diwali - Sun, 08 Nov 2026 is on your holiday calendar."


async def test_a_day_not_on_the_calendar_is_said_so(monkeypatch, no_model):
    _calendar(monkeypatch, [h for h in CALENDAR if h["holiday_name"] != "Diwali"])

    out = await hr_graph.hr_response_node(_state("Is it a holiday in our company?", DIWALI_CHAT),
                                          FakeWriter())

    assert out["response_text"].startswith("I can't see that on your holiday calendar.")
    assert "Christmas" in out["response_text"]


async def test_a_date_is_checked_against_the_calendar(monkeypatch, no_model):
    _calendar(monkeypatch, CALENDAR)

    yes = await hr_graph.hr_response_node(_state("is 25 Dec a holiday"), FakeWriter())
    no = await hr_graph.hr_response_node(_state("is 26 Dec a holiday"), FakeWriter())

    assert yes["response_text"] == "Yes - Christmas - Fri, 25 Dec 2026 is on your holiday calendar."
    assert no["response_text"] == "Sat, 26 Dec 2026 isn't on your holiday calendar."


async def test_no_calendar_gives_erps_message(monkeypatch, no_model):
    msg = "The holiday list is not available for your department. Please contact HR for more information."
    _calendar(monkeypatch, unavailable=msg)

    out = await hr_graph.hr_response_node(_state("Is it a holiday in our company?", DIWALI_CHAT),
                                          FakeWriter())

    assert out["response_text"] == msg


async def test_summary_de_do_is_told_to_cover_the_whole_chat(monkeypatch):
    seen = {}

    async def _capture(messages, **kwargs):
        seen["messages"] = messages
        yield {"type": "chunk", "content": "summary"}
    monkeypatch.setattr(hr_graph, "_call_llm_stream", _capture)

    await hr_graph.hr_response_node(_state("Summary de do", DIWALI_CHAT, intent="conversation_meta"),
                                    FakeWriter())

    systems = [m["content"] for m in seen["messages"] if m["role"] == "system"]
    assert hr_graph.CHAT_SUMMARY_INSTRUCTION in systems
    assert [m["content"] for m in seen["messages"] if m["role"] == "user"][0] == "Diwali kya hai?"
