"""A leave reason longer than erp-api accepts is caught when it is GIVEN.

QA: a reason over 200 characters went through every step - read-back,
confirmation card, "yes" - and only then was refused by erp-api ("can't
apply it, reduce your reason"). The limit is now checked before the
read-back and the card, on the exact text that would be submitted.
"""

import json
from datetime import date
from unittest.mock import AsyncMock, patch

import pytest

import services.leave_action_service as las

LIMIT = las.MAX_LEAVE_REASON_LENGTH

# "Today" for the leave flow in these tests. The leave date is fixed
# (2026-10-06), and the flow refuses a date before today — so on the real clock
# these would start failing once the calendar passed it ("You can't apply for
# leave on a past date"), for a reason unrelated to what they test.
TEST_TODAY = date(2026, 9, 28)

_ERP = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
    "name": "Abcd Test", "is_manager": False,
    "leave_quota": {"casual_leave": {"total": 12, "remaining": 10}},
    "leave_settings": {"leave_type": [{"slug": "casual_leave", "name": "Casual Leave",
                                       "session_type_required": False}]},
    "leaves": [], "holidays": [], "abbreviations": []}}})


@pytest.fixture
def turn(monkeypatch):
    monkeypatch.setattr(las, "_today", lambda: TEST_TODAY)
    monkeypatch.setattr(las, "_today_in_app_timezone", lambda: TEST_TODAY)
    store = {}
    monkeypatch.setattr(las.leave_slot_service, "get_slots",
                        lambda *a, **k: dict(store["s"]) if store.get("s") else None)
    monkeypatch.setattr(las.leave_slot_service, "set_slots",
                        lambda c, v, s: store.__setitem__("s", dict(s)) or True)
    monkeypatch.setattr(las.leave_slot_service, "clear_slots",
                        lambda *a, **k: store.pop("s", None) or True)

    async def _turn(query, extracted):
        writer_events = []
        llm = AsyncMock(return_value={"choices": [{"message": {"content": json.dumps(extracted)}}]})
        with patch.object(las.erp_client, "get_leave_context", _ERP), \
                patch.object(las.erp_client, "get_leave_balance", _ERP), \
                patch.object(las.erp_client, "get_applied_leaves", _ERP), \
                patch.object(las.erp_client, "get_leave_holidays", _ERP, create=True), \
                patch.object(las, "_call_llm", llm):
            out = await las.leave_action_node(
                {"query": query, "intent": "apply_leave", "bearer_token": "t", "company_id": 1,
                 "conversation_id": "r", "usage_events": [], "is_manager": False},
                writer_events.append)
        cards = [e for e in writer_events if e.get("type") == "leave_confirmation"]
        return out["response_text"], cards, store.get("s") or {}

    return _turn


def _request(reason):
    return {"leave_type": "casual_leave", "from_date": "2026-10-06", "to_date": "2026-10-06",
            "session_type_slug": "full_day", "reason": reason}


async def test_a_reason_over_the_limit_is_asked_for_again_before_any_card(turn):
    long_reason = "x" * (LIMIT + 1)

    # Typed exactly as stored, so no read-back would be asked either.
    text, cards, slots = await turn(long_reason, _request(long_reason))

    assert text == (f"Your reason is {LIMIT + 1} characters long, but it can be at most "
                    f"{LIMIT}. Please share a shorter reason for your leave.")
    assert cards == []
    assert slots["reason"] is None
    assert slots["leave_type"] == "casual_leave"   # the rest of the request is kept


async def test_a_reason_exactly_at_the_limit_is_accepted(turn):
    reason = "y" * LIMIT

    text, cards, slots = await turn(reason, _request(reason))

    assert "at most" not in text
    assert len(cards) == 1
    assert slots["reason"] == reason


async def test_a_shorter_reason_after_a_long_one_reaches_the_card(turn):
    long_reason = "z" * (LIMIT + 50)
    await turn(long_reason, _request(long_reason))

    text, cards, slots = await turn("Family function", {"reason": "Family function"})

    assert len(cards) == 1
    assert cards[0]["data"]["reason"] == "Family function"
