"""QA report HA-884 (07 Oct 2026, QA as test06): the failed cases."""
import pytest
from unittest.mock import AsyncMock, patch

import services.ai_service as ai
import services.classify_node as cn
import services.erp_client as erp_client
import services.hr_graph as hg


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]


class TestTC007Translation:
    @pytest.mark.parametrize("query", [
        'Translate "Good morning, how are you?" into Hindi.', "translate good morning into hindi",
        "How do you say thank you in French", "say hello in tamil",
    ])
    def test_a_translation(self, query):
        assert cn._is_translation_request(query) is True

    @pytest.mark.parametrize("query", ["good morning", "what is the leave policy in hindi company"])
    def test_not_a_translation(self, query):
        assert cn._is_translation_request(query) is False


def test_tc010_the_general_prompt_forbids_latex():
    p = ai.GENERAL_CHAT_SYSTEM_PROMPT
    assert "does NOT render LaTeX" in p and "\\frac" in p and "\f" not in p


class TestTC031GeneralHrThemedQuestions:
    def _state(self, query, enabled=True):
        return {"query": query, "intent": "policy", "context": [], "usage_events": [],
                "policy_lookup_failed": True, "policy_context": None,
                "general_chat_enabled": enabled}

    async def test_answered_by_the_general_lane(self):
        w = _Writer()
        with patch.object(hg, "general_chat_node", AsyncMock(return_value={"response_text": "x"})) as gc:
            await hg.hr_response_node(self._state("Summarise the benefits of remote work."), w)
        gc.assert_awaited_once()

    @pytest.mark.parametrize("query", ["What is our notice period?", "what is the company leave policy",
                                       "am I eligible for work from home"])
    async def test_a_company_question_keeps_the_honest_fallback(self, query):
        w = _Writer()
        with patch.object(hg, "general_chat_node", AsyncMock()) as gc:
            await hg.hr_response_node(self._state(query), w)
        gc.assert_not_awaited()
        assert w.done()["data"]["answer"] == hg.NO_INFO_FALLBACK

    async def test_with_general_chat_off_non_hr_node_answers(self):
        """UAT 27 Oct: with the lane off this went to the fallback ("I do not
        have this information"). non_hr_node answers it, as it does every
        other general question."""
        w = _Writer()
        with patch.object(hg, "general_chat_node", AsyncMock()) as gc, \
                patch.object(hg, "non_hr_node", AsyncMock(return_value={"response_text": "x"})) as nh:
            await hg.hr_response_node(self._state("Summarise the benefits of remote work.",
                                                  enabled=False), w)
        gc.assert_not_awaited()
        nh.assert_awaited_once()

    async def test_with_general_chat_off_a_company_question_keeps_the_fallback(self):
        w = _Writer()
        with patch.object(hg, "non_hr_node", AsyncMock()) as nh:
            await hg.hr_response_node(self._state("What is our notice period?", enabled=False), w)
        nh.assert_not_awaited()
        assert w.done()["data"]["answer"] == hg.NO_INFO_FALLBACK


class TestTC018Holidays:
    @pytest.fixture
    def holidays(self, monkeypatch):
        def _install(result=None, exc=None):
            async def _get(*a, **k):
                if exc:
                    raise exc
                return result
            monkeypatch.setattr(erp_client, "get_leave_holidays", _get)
        monkeypatch.setattr(hg, "_today_in_app_timezone",
                            lambda: __import__("datetime").date(2026, 10, 7))
        return _install

    CAL = {"http_status": 200, "body": {"success": True, "data": {"holidays": [
        {"holiday_name": "Gandhi Jayanti", "holiday_date": "2026-10-02"},
        {"holiday_name": "Dussehra", "holiday_date": "2026-10-20"},
        {"holiday_name": "Diwali", "holiday_date": "2026-11-08"}]}}}

    async def test_the_next_holiday_comes_from_the_calendar(self, holidays):
        holidays(self.CAL)
        w = _Writer()
        await hg.hr_response_node({"query": "When is the next holiday?", "intent": "policy",
                                   "context": [], "usage_events": []}, w)
        assert w.done()["data"]["answer"].startswith("Your next holiday is Dussehra - Tue, 20 Oct 2026.")
        assert w.done()["intent"] == "leave_holidays"

    async def test_no_calendar_says_erp_apis_words(self, holidays):
        holidays(exc=erp_client.ErpApiUnavailable(
            "erp-api returned 403", status_code=403,
            body={"success": False, "message": "The holiday list is not available for your department."}))
        w = _Writer()
        await hg.hr_response_node({"query": "When is the next holiday?", "intent": "policy",
                                   "context": [], "usage_events": []}, w)
        assert w.done()["data"]["answer"] == "The holiday list is not available for your department."

    # UV-17 (27 Oct): the count question got "I do not have this information".
    @pytest.mark.parametrize("query", [
        "How many holidays are there in my company this year?", "total holidays this year",
        "number of public holidays in 2026", "how many holidays do we get",
    ])
    async def test_the_holiday_count_comes_from_the_calendar(self, holidays, query):
        holidays({"http_status": 200, "body": {"success": True, "data": {
            "year": 2026, "total_holidays": 3, "holidays": self.CAL["body"]["data"]["holidays"]}}})
        w = _Writer()
        await hg.hr_response_node({"query": query, "intent": "policy",
                                   "context": [], "usage_events": []}, w)
        answer = w.done()["data"]["answer"]
        assert answer.startswith("There are 3 holidays on your holiday calendar for 2026. 2 are still to come:")
        assert "Dussehra - Tue, 20 Oct 2026" in answer and "Gandhi Jayanti" not in answer
        assert w.done()["intent"] == "leave_holidays"

    @pytest.mark.parametrize("query", ["How many holidays are there in my company this year?",
                                       "how many holidays left"])
    def test_a_holiday_count_is_routed_to_the_calendar(self, query):
        assert cn._HOLIDAY_COUNT_RE.search(query)

    @pytest.mark.parametrize("query", ["I want to apply leave on a holiday"])
    def test_not_a_holiday_list_question(self, query):
        assert not hg._HOLIDAY_QUESTION_RE.search(query)

    def test_is_x_a_holiday_is_answered_from_the_calendar(self):
        """Was excluded while the calendar answer could only give "your next
        holiday"; it now answers yes/no for the named day (QA LT-06 T7 - see
        test_is_it_a_holiday.py), instead of the policy documents guessing."""
        assert hg._HOLIDAY_QUESTION_RE.search("is diwali a holiday")
        assert hg._IS_IT_A_HOLIDAY_RE.search("is diwali a holiday")


def test_tc020_an_impossible_leave_date_is_named():
    from datetime import date
    from services.regularisation_node import _invalid_date_mention, _invalid_date_message
    bad = _invalid_date_mention("Apply leave for 31 February.", date(2026, 10, 7))
    assert bad
    msg = _invalid_date_message(bad, date(2026, 10, 7),
                                question="Which date would you like to take leave?",
                                example="08 Oct 2026")
    assert "isn't a valid date" in msg and "February" in msg and "take leave" in msg


class TestTC029NoWebSearchInHrAnswers:
    """"What is a salary slip?" was answered "per Zoho Payroll, Salesforce India
    and RazorpayX" - the HR answer node searched the web when the company
    documents had nothing. Browsing is out of scope (HA-884)."""

    async def _use_tools(self, monkeypatch):
        seen = {}

        async def _stream(messages, max_tokens=None, use_tools=True):
            seen["use_tools"] = use_tools
            yield {"type": "chunk", "content": "A salary slip lists earnings and deductions."}

        monkeypatch.setattr(hg, "_call_llm_stream", _stream)
        await hg.hr_response_node({"query": "What is a salary slip?", "intent": "payroll",
                                   "context": [], "usage_events": []}, _Writer())
        return seen["use_tools"]

    async def test_off_by_default(self, monkeypatch):
        monkeypatch.delenv("HR_WEB_SEARCH_ENABLED", raising=False)
        assert await self._use_tools(monkeypatch) is False

    async def test_only_when_switched_on(self, monkeypatch):
        monkeypatch.setenv("HR_WEB_SEARCH_ENABLED", "true")
        assert await self._use_tools(monkeypatch) is True


class TestTC016LeavePolicyFromConfiguration:
    SETTINGS = {"leave_type": [
        {"name": "Casual Leave", "slug": "casual_leave", "quota": 100, "max_apply_in_month": 2,
         "benefit_start": "confirmation", "is_carry_forward": False},
        {"name": "Sick Leave", "slug": "sick_leave", "quota": 100, "max_apply_in_month": 20},
        {"name": "Regularization", "slug": "regularization", "max_apply_in_month": 4}],
        "is_leave_monthy_credit": "true"}

    @pytest.fixture
    def balance(self, monkeypatch):
        def _install(result=None, exc=None):
            async def _get(*a, **k):
                if exc:
                    raise exc
                return result
            monkeypatch.setattr(erp_client, "get_leave_balance", _get)
        return _install

    async def test_the_configured_policy(self, balance):
        balance({"http_status": 200, "body": {"success": True, "data": {"leave_settings": self.SETTINGS}}})
        w = _Writer()
        await hg.hr_response_node({"query": "What is the company leave policy?", "intent": "policy",
                                   "context": [], "usage_events": []}, w)
        answer = w.done()["data"]["answer"]
        assert "**Casual Leave**: 100 days a year; up to 2 applications a month" in answer
        assert "Regularization" not in answer and "[X]" not in answer
        assert w.done()["intent"] == "leave_policy"

    async def test_one_type_asked_for(self, balance):
        balance({"http_status": 200, "body": {"success": True, "data": {"leave_settings": self.SETTINGS}}})
        msg = await hg._configured_leave_policy_answer({}, "what is the sick leave policy")
        assert msg.startswith("Your company's Sick Leave policy:") and "Casual" not in msg

    async def test_unreachable_configuration_falls_back(self, balance):
        balance(exc=erp_client.ErpApiUnavailable("down"))
        assert await hg._configured_leave_policy_answer({}, "what is the leave policy") is None
