"""A question about ONE dated leave is answered about that leave (negative
run, 28 Oct 2026, #56).

"my leave on 2 nov got approved right?" - the 2 Nov leave is PENDING - was
answered "Your approved leave requests — Earned Leave (2026-11-23 ...)
approved; Casual Leave (2026-10-16 ...) approved; ..." and the leave asked
about was never mentioned. Two gaps: "got approved right?" was not read as a
status question (so it became a LIST of approved leaves), and "2 nov" was
left to an LLM fallback that only runs when classify_node flagged a date.
"""
from datetime import date
from unittest.mock import AsyncMock, patch

import pytest

import services.leave_action_service as las


def _leave(id_, slug, name, frm, to, status):
    return {"id": id_, "leave_type": name, "leave_type_slug": slug, "from_date": frm, "to_date": to,
            "status_name": status, "status": {"pending": 0, "approved": 1}[status],
            "leave_count": "1", "total_days": 1, "session_type": "Full Day",
            "applied_date": "2026-10-26", "approver_name": "Anita Desai", "reason": "x"}


LEAVES = [
    _leave(9101, "casual_leave", "Casual Leave", "2026-11-02", "2026-11-03", "pending"),
    _leave(9105, "earned_leave", "Earned Leave", "2026-11-23", "2026-11-24", "approved"),
    _leave(9085, "casual_leave", "Casual Leave", "2026-10-16", "2026-10-16", "approved"),
]


async def _ask(query):
    asked = []

    async def _applied(token, leave_status=None, **k):
        asked.append(leave_status)
        rows = LEAVES if leave_status in (None, "all") else [l for l in LEAVES if l["status_name"] == leave_status]
        return {"http_status": 200, "body": {"success": True, "data": {"leaves": rows}}}

    context = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "leave_quota": {}, "leave_settings": {"leave_type": [
            {"slug": "casual_leave", "name": "Casual Leave"},
            {"slug": "earned_leave", "name": "Earned Leave"}]}}}})
    with patch.object(las.erp_client, "get_applied_leaves", _applied), \
            patch.object(las.erp_client, "get_leave_context", context), \
            patch.object(las.erp_client, "get_leave_balance", context), \
            patch.object(las, "_today_in_app_timezone", lambda: date(2026, 10, 28)), \
            patch.object(las, "_call_llm", AsyncMock(side_effect=RuntimeError("no LLM"))):
        out = await las.leave_action_node(
            {"query": query, "intent": "leave_status", "bearer_token": "t", "company_id": 1,
             "conversation_id": "tag", "usage_events": [], "is_manager": False,
             "has_date_expression": False}, lambda ev: None)
    return out["response_text"], asked


@pytest.mark.parametrize("query", [
    "my leave on 2 nov got approved right?",
    "my leave on 2 nov is approved, correct?",
    "is my leave on 2 nov approved",
])
async def test_the_dated_leave_is_answered_with_its_real_status(query):
    text, asked = await _ask(query)
    assert asked == ["all"], "searched one status instead of every leave"
    assert "pending" in text.lower(), text
    assert "2026-11-23" not in text and "23 Nov" not in text, "answered about other leaves"


async def test_a_list_request_for_a_status_is_still_a_list():
    text, asked = await _ask("show my approved leaves")
    assert asked == ["approved"]
    assert "pending" not in text.lower()


class TestTheDateIsReadWithoutTheModel:
    @pytest.mark.parametrize("query", ["between 1st oct and 5th oct", "from 2 nov to 5 nov"])
    async def test_a_range_is_not_collapsed_to_one_day(self, query):
        """Left to the model fallback (unreachable here), never shortened."""
        text, asked = await _ask(f"show my leaves {query}")
        assert "2026-10-01" not in text or "2026-10-05" in text
