"""Weekly off (QA, 26 Oct): "when is my weekly off", "when is my off?" and
"tell me on which days i've off".

After a holiday answer the first two got the holiday message again (the
holiday follow-up check read any short "when ..." as "when is the next
holiday"); asked fresh, the third went to the policy documents and the
model put together "Wednesdays off, plus Saturdays and Sundays" from policy
text. The weekly off is part of the employee's shift assignment
(/shift-details: shift.week_off_day, work_calendar.week_off_days), so that is
where it is answered from - never the model.
"""
import pytest

import services.hr_graph as hr_graph
import services.shift_query as shift_query
from services.classify_node import _is_holiday_followup
from services.nlp_service import is_week_off_query

from tests.test_bare_name_continuation import _mocks, _state, FakeWriter
from tests.test_shift_query import base_state

pytestmark = pytest.mark.asyncio


@pytest.fixture(autouse=True)
def _own_shift(monkeypatch):
    """No target employee named (test_shift_query's default), without the model."""
    async def _fake(query, today=None):
        return {"employee_id": None, "employee_name": None, "requested_date": None}, None
    monkeypatch.setattr(shift_query.ai_service, "extract_shift_target_fields", _fake)

WEEK_OFF_QUESTIONS = [
    "when is my weekly off", "when is my off?", "tell me on which days i've off",
    "what are my week offs", "which days do I have off", "is saturday my off?",
    "what is my rest day", "my weekoff days", "when am i off", "what days off do I get",
]

NOT_WEEK_OFF = [
    # Leave, which also says "day off".
    "can I take a day off tomorrow", "apply for a day off on friday",
    "how many days off do I have left", "I need a day off",
    # Other subjects.
    "show the holiday list", "what is my shift", "is the office off on diwali?",
]


@pytest.mark.parametrize("query", WEEK_OFF_QUESTIONS)
def test_week_off_questions_are_recognised(query):
    assert is_week_off_query(query)


@pytest.mark.parametrize("query", NOT_WEEK_OFF)
def test_other_questions_are_not(query):
    assert not is_week_off_query(query)


@pytest.mark.parametrize("query", ["when is my weekly off", "when is my off?"])
def test_a_week_off_question_is_not_a_holiday_followup(query):
    assert not _is_holiday_followup(query, "leave_holidays")
    assert _is_holiday_followup("When is the next one?", "leave_holidays")


@pytest.mark.parametrize("last_intent", [None, "leave_holidays", "policy"])
@pytest.mark.parametrize("query", ["when is my weekly off", "tell me on which days i've off"])
async def test_routed_to_the_shift_assignment_without_the_llm(query, last_intent):
    with _mocks(detected="policy") as m:
        result = await hr_graph.classify_node(
            _state(query, last_intent=last_intent, is_manager=False), FakeWriter())

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


def _shift_response(monkeypatch, shift, work_calendar=None):
    async def _fake(token, **kwargs):
        data = {"shift": shift}
        if work_calendar is not None:
            data["work_calendar"] = work_calendar
        return {"http_status": 200, "body": {"success": True, "data": data}}
    monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)


async def test_the_answer_is_the_week_off_itself(monkeypatch):
    # The live /shift-details shape.
    _shift_response(monkeypatch, {
        "shift_id": 245, "shift_name": "Ayush Team Shift", "start_time": "09:00:00",
        "end_time": "19:00:00", "week_off_day": ["Friday", "Saturday", "Sunday"]})

    out = await shift_query.shift_query_node(base_state("when is my weekly off"), FakeWriter())

    assert out["response_text"] == (
        "Your weekly off is **Friday, Saturday and Sunday** (shift: Ayush Team Shift).")


async def test_falls_back_to_the_work_calendar(monkeypatch):
    _shift_response(monkeypatch, {"shift_id": 1, "shift_name": "Demo", "start_time": "09:00:00",
                                  "end_time": "18:00:00"},
                    work_calendar={"week_off_days": ["Sunday"]})

    out = await shift_query.shift_query_node(base_state("when is my off?"), FakeWriter())

    assert out["response_text"] == "Your weekly off is **Sunday** (shift: Demo)."


async def test_no_week_off_on_record_is_said_not_guessed(monkeypatch):
    _shift_response(monkeypatch, {"shift_id": 1, "shift_name": "Demo", "start_time": "09:00:00",
                                  "end_time": "18:00:00"})

    out = await shift_query.shift_query_node(base_state("what is my week off"), FakeWriter())

    assert "doesn't list a weekly off" in out["response_text"]


async def test_a_shift_question_still_gets_the_full_card(monkeypatch):
    _shift_response(monkeypatch, {"shift_id": 1, "shift_name": "Demo", "start_time": "09:00:00",
                                  "end_time": "18:00:00", "week_off_day": ["Sunday"]})

    out = await shift_query.shift_query_node(base_state("what is my shift"), FakeWriter())

    assert "You're currently assigned to **Demo**" in out["response_text"]
    assert "Week off: Sunday" in out["response_text"]
