"""How the apply-leave card may be resolved. Three tiers, all load-bearing.

  1. A BUTTON the employee pressed. The card sends "yes submit it" for
     confirm and "cancel" for cancel; the cancellation card sends "confirm
     cancellation" and "keep request". A press is already an unambiguous
     answer -- act on it, never ask it to confirm itself.

  2. A TYPED whole-message yes or no and NOTHING ELSE ("yes", "ok", "no",
     "cancel", "discard"). Equally unambiguous -- act on it.

  3. ANYTHING ELSE. A yes or no with more attached is not agreement to the
     rest of the sentence, and this is where real damage happened: "yes but
     only half day" submitted a FULL day, and "yes i think so but let me
     check my balance first" submitted the request the employee had just
     asked to hold. Both reached the approver and cannot be taken back. These
     go to classify_confirmation_reply, and the card stays open until a tier
     1 or 2 reply resolves it.

Two ways to break this, both of which have shipped:

  * widening tier 2 into "contains a yes somewhere" -- that is the full-day
    bug above;
  * narrowing tiers 1-2 into asking anyway -- a button that asks you to
    confirm the button, and a plain "yes" that will not submit.
"""
import pytest
from unittest.mock import AsyncMock, MagicMock, patch

import services.leave_action_service as las

CARD = {
    "step": "awaiting_confirmation", "leave_type": "casual_leave",
    "from_date": "2026-09-25", "to_date": "2026-09-25",
    "session_type_slug": "full_day", "reason": "Personal work",
}

pytestmark = pytest.mark.asyncio


class _Writer:
    def __init__(self): self.events = []
    def __call__(self, ev): self.events.append(ev)
    def of_type(self, t): return [e for e in self.events if e.get("type") == t]


async def _at_card(reply, slots=None, allow_submit=False):
    """One turn at the card. _call_llm raises on purpose: the gate must hold
    when the model is unreachable, and must never fail OPEN into submitting."""
    ok = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "name": "T", "is_manager": False,
        "leave_quota": {"casual_leave": {"total": 12, "remaining": 8}},
        "leave_settings": {"leave_type": [{"slug": "casual_leave", "name": "Casual Leave",
                                           "session_type_required": False}]},
        "leaves": []}}})
    submitted = []

    async def _apply(*a, **k):
        if not allow_submit:
            raise AssertionError("SUBMITTED WITHOUT ASKING — see this file's docstring")
        submitted.append(1)
        return {"http_status": 200, "body": {"success": True, "data": [{"id": 1}]}}
    applied = _apply
    cleared, writer = [], _Writer()
    with patch.object(las.erp_client, "get_leave_context", ok), \
            patch.object(las.erp_client, "get_leave_balance", ok), \
            patch.object(las.erp_client, "get_applied_leaves", ok), \
            patch.object(las.erp_client, "apply_leave", applied), \
            patch.object(las, "_call_llm", AsyncMock(side_effect=RuntimeError("no LLM"))), \
            patch.object(las.leave_slot_service, "get_slots",
                         lambda *a, **k: dict(slots or CARD)), \
            patch.object(las.leave_slot_service, "set_slots", lambda *a, **k: None), \
            patch.object(las.leave_slot_service, "clear_slots",
                         lambda *a, **k: cleared.append(1)):
        out = await las.leave_action_node(
            {"query": reply, "intent": "apply_leave", "bearer_token": "t",
             "company_id": 1, "conversation_id": "gate", "usage_events": [],
             "is_manager": False}, writer)
    return out["response_text"], cleared, submitted


@pytest.mark.parametrize("reply", [
    "yes submit it",                             # tier 1 — the confirm button
    "yes", "ok", "sure", "submit", "go ahead",   # tier 2 — bare affirmatives
])
async def test_a_button_press_or_a_bare_yes_submits_on_sight(reply):
    """No extra confirmation step. Asking a button to confirm itself, or
    refusing to act on a plain "yes", is the bug this guards."""
    text, _, submitted = await _at_card(reply, allow_submit=True)
    assert submitted, f"{reply!r} did not submit"


@pytest.mark.parametrize("reply", [
    "cancel",                                          # tier 1 — cancel button
    "no", "nope", "discard", "never mind", "forget it",  # tier 2
])
async def test_a_button_press_or_a_bare_no_discards_on_sight(reply):
    text, cleared, submitted = await _at_card(reply)
    assert cleared, f"{reply!r} did not resolve the card"
    assert not submitted

@pytest.mark.parametrize("reply", [
    "yes but only half day",
    "yes, change the date to 5 october",
    "yes i think so but let me check my balance first",
])
async def test_a_qualified_yes_is_not_consent_to_what_follows(reply):
    """A leading "yes" is not agreement to the rest of the sentence. "yes but
    only half day" once submitted a FULL day. The mocked apply_leave raises if
    this ever submits, which is the assertion that matters; with no model
    reachable it cannot tell WHICH change was meant, and failing closed onto
    the card is the correct outcome."""
    text, _, submitted = await _at_card(reply)
    assert not submitted
    assert "last check" not in text.lower(), (
        "a qualified yes was treated as a plain go-ahead")


@pytest.mark.parametrize("reply", ["yes submit it", "yes", "cancel", "no", "discard"])
async def test_tiers_1_and_2_never_need_the_model(reply):
    """_call_llm raises throughout this file. Buttons and bare yes/no must
    still work: an outage cannot leave someone unable to submit or discard a
    request that is sitting on their screen."""
    text, cleared, submitted = await _at_card(reply, allow_submit=True)
    assert submitted or cleared, f"{reply!r} needed a model call to resolve"
