"""
Tests for the apply-leave / leave-balance conversation feature:
  - services/leave_slot_service.py (Redis slot store)
  - services/erp_client.py's leave functions (context/balance/apply)
  - services/hr_graph.py::leave_action_node (role gate, balance branch,
    multi-turn apply branch, confirmation, submission)

leave_action_node is exercised directly (not through the HTTP layer) with a
fake StreamWriter and an in-memory fake for leave_slot_service, so these
tests pin down the actual conversation logic without needing Redis, erp-api,
or a real LLM call.
"""

import json
from datetime import date
import pytest
from unittest.mock import patch, MagicMock

import services.hr_graph as hr_graph
import services.classify_node as classify_node_mod
import services.leave_action_service as leave_action_service
import services.leave_slot_service as leave_slot_service
import services.erp_client as erp_client
from services.erp_client import ErpApiTimeout, ErpApiUnavailable, ErpApiUnauthorized


class FakeWriter:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)

    def of_type(self, etype):
        return [e for e in self.events if e.get("type") == etype]


class FakeSlotStore:
    """In-memory stand-in for leave_slot_service, keyed like the real one."""

    def __init__(self):
        self._store = {}

    def _key(self, company_id, conversation_id):
        return f"{company_id}:{conversation_id}"

    def get_slots(self, company_id, conversation_id):
        return self._store.get(self._key(company_id, conversation_id))

    def set_slots(self, company_id, conversation_id, slots):
        self._store[self._key(company_id, conversation_id)] = dict(slots)
        return True

    def clear_slots(self, company_id, conversation_id):
        self._store.pop(self._key(company_id, conversation_id), None)
        return True


def base_state(query: str, intent: str = "apply_leave", has_date_expression: bool = False) -> dict:
    return {
        "query": query, "intent": intent, "usage_events": [],
        "bearer_token": "caller-token", "company_id": 1, "conversation_id": "conv-1",
        "has_date_expression": has_date_expression,
    }


def fake_llm_response(usage=None):
    return {"choices": [{"message": {"content": ""}}], "usage": usage or {}}


def mock_extraction(monkeypatch, extracted: dict):
    """Patches hr_graph._call_llm + _extract_text/_safe_json_parse pipeline to
    return exactly `extracted` for the leave-slot-extraction call."""
    async def _fake_call_llm(prompt, max_tokens=None, model=None):
        return {"__extracted__": extracted}

    def _fake_extract_text(response):
        return json.dumps(response.get("__extracted__", {}))

    monkeypatch.setattr(hr_graph, "_call_llm", _fake_call_llm)
    monkeypatch.setattr(hr_graph, "_extract_text", _fake_extract_text)
    # leave_action_node's slot-extraction call lives in leave_action_service now.
    monkeypatch.setattr(leave_action_service, "_call_llm", _fake_call_llm)
    monkeypatch.setattr(leave_action_service, "_extract_text", _fake_extract_text)


# ═════════════════════════════════════════════════════════════════════════════
# leave_slot_service — direct unit tests (real module, Redis mocked out)
# ═════════════════════════════════════════════════════════════════════════════

class TestLeaveSlotService:

    def test_set_then_get_roundtrips(self):
        mock_client = MagicMock()
        store = {}
        mock_client.set.side_effect = lambda key, val, ex=None: store.__setitem__(key, val)
        mock_client.get.side_effect = lambda key: store.get(key)

        with patch.object(leave_slot_service, "_get_redis", return_value=mock_client):
            wrote_ok = leave_slot_service.set_slots(1, "conv-1", {"leave_type": "casual_leave"})
            result = leave_slot_service.get_slots(1, "conv-1")

        assert wrote_ok is True
        assert result == {"leave_type": "casual_leave"}
        mock_client.set.assert_called_once()
        assert mock_client.set.call_args.kwargs.get("ex") == leave_slot_service.SLOT_TTL

    def test_get_returns_none_when_nothing_stored(self):
        mock_client = MagicMock()
        mock_client.get.return_value = None
        with patch.object(leave_slot_service, "_get_redis", return_value=mock_client):
            assert leave_slot_service.get_slots(1, "conv-1") is None

    def test_get_returns_none_when_redis_unavailable(self):
        with patch.object(leave_slot_service, "_get_redis", return_value=None):
            assert leave_slot_service.get_slots(1, "conv-1") is None

    def test_clear_deletes_the_key(self):
        mock_client = MagicMock()
        with patch.object(leave_slot_service, "_get_redis", return_value=mock_client):
            cleared_ok = leave_slot_service.clear_slots(1, "conv-1")
        mock_client.delete.assert_called_once_with("leave_slots:1:conv-1")
        assert cleared_ok is True

    def test_write_failure_does_not_raise_and_returns_false(self):
        mock_client = MagicMock()
        mock_client.set.side_effect = Exception("connection reset")
        with patch.object(leave_slot_service, "_get_redis", return_value=mock_client):
            result = leave_slot_service.set_slots(1, "conv-1", {"leave_type": "casual_leave"})  # must not raise
        assert result is False

    def test_clear_failure_does_not_raise_and_returns_false(self):
        mock_client = MagicMock()
        mock_client.delete.side_effect = Exception("connection reset")
        with patch.object(leave_slot_service, "_get_redis", return_value=mock_client):
            result = leave_slot_service.clear_slots(1, "conv-1")  # must not raise
        assert result is False

    def test_clear_returns_false_when_redis_unavailable(self):
        with patch.object(leave_slot_service, "_get_redis", return_value=None):
            assert leave_slot_service.clear_slots(1, "conv-1") is False


# ═════════════════════════════════════════════════════════════════════════════
# erp_client — leave functions
# ═════════════════════════════════════════════════════════════════════════════

class TestErpClientLeaveFunctions:

    async def test_get_leave_context_forwards_token_and_url(self):
        captured = {}

        async def _request(method, url, headers=None, **kwargs):
            captured.update(method=method, url=url, headers=headers)
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {"is_manager": False}}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            result = await erp_client.get_leave_context("caller-token-abc")

        assert captured["method"] == "GET"
        assert captured["url"] == "http://erp.test/api/v1/ai/leave/context"
        assert captured["headers"]["Authorization"] == "Bearer caller-token-abc"
        assert result["body"]["data"]["is_manager"] is False

    async def test_no_timeout_override_omits_the_kwarg_entirely(self):
        """httpx treats an explicit timeout=None as 'no timeout at all', not
        'use the client default' — so a call with no override must not pass
        the kwarg through as None, or every such call would hang forever on
        a wedged connection instead of using the client's real default."""
        captured = {}

        async def _request(method, url, headers=None, **kwargs):
            captured.update(kwargs)
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {}}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            await erp_client.get_leave_context("caller-token-abc")

        assert "timeout" not in captured

    async def test_timeout_override_is_forwarded_to_httpx(self):
        captured = {}

        async def _request(method, url, headers=None, **kwargs):
            captured.update(kwargs)
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {}}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            await erp_client.get_leave_context("caller-token-abc", timeout_seconds=3.0)
            await erp_client.get_leave_balance("caller-token-abc", timeout_seconds=3.0)

        assert captured["timeout"] == 3.0

    async def test_successful_call_is_logged_without_leaking_the_token(self, caplog):
        async def _request(method, url, headers=None, **kwargs):
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {}}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http, \
             caplog.at_level("INFO", logger="services.erp_client"):
            mock_http.request = _request
            await erp_client.get_leave_context("super-secret-token-value")

        log_text = caplog.text
        assert "GET http://erp.test/api/v1/ai/leave/context" in log_text
        assert "200" in log_text
        assert "super-secret-token-value" not in log_text

    def test_log_call_to_db_persists_expected_fields(self):
        mock_session = MagicMock()
        mock_session_local = MagicMock(return_value=mock_session)

        with patch.object(erp_client, "SessionLocal", mock_session_local):
            erp_client._log_call_to_db(
                method="GET", endpoint="/api/v1/ai/leave/balance", http_status=200,
                latency_ms=42.5, success=True, error_code=None,
                company_id=99, conversation_id="conv-1",
            )

        mock_session.add.assert_called_once()
        logged_row = mock_session.add.call_args.args[0]
        assert logged_row.method == "GET"
        assert logged_row.endpoint == "/api/v1/ai/leave/balance"
        assert logged_row.http_status == 200
        assert logged_row.latency_ms == 42.5
        assert logged_row.success is True
        assert logged_row.error_code is None
        assert logged_row.company_id == 99
        assert logged_row.conversation_id == "conv-1"
        mock_session.commit.assert_called_once()
        mock_session.close.assert_called_once()

    def test_log_call_to_db_records_failures_too(self):
        mock_session = MagicMock()
        mock_session_local = MagicMock(return_value=mock_session)

        with patch.object(erp_client, "SessionLocal", mock_session_local):
            erp_client._log_call_to_db(
                method="POST", endpoint="/api/v1/ai/leave/apply", http_status=None,
                latency_ms=None, success=False, error_code="TIMEOUT",
                company_id=99, conversation_id="conv-1",
            )

        logged_row = mock_session.add.call_args.args[0]
        assert logged_row.success is False
        assert logged_row.error_code == "TIMEOUT"
        assert logged_row.http_status is None

    def test_log_call_to_db_write_failure_does_not_raise(self):
        mock_session = MagicMock()
        mock_session.commit.side_effect = Exception("db down")
        mock_session_local = MagicMock(return_value=mock_session)

        with patch.object(erp_client, "SessionLocal", mock_session_local):
            erp_client._log_call_to_db(
                method="GET", endpoint="/x", http_status=None, latency_ms=None,
                success=False, error_code="TIMEOUT", company_id=None, conversation_id=None,
            )  # must not raise

        mock_session.rollback.assert_called_once()
        mock_session.close.assert_called_once()

    async def test_persist_call_log_dispatch_failure_does_not_raise(self, monkeypatch):
        async def _boom(*a, **kw):
            raise RuntimeError("threadpool broken")
        monkeypatch.setattr(erp_client, "run_in_threadpool", _boom)
        await erp_client._persist_call_log(
            method="GET", endpoint="/x", http_status=200, latency_ms=1.0,
            success=True, error_code=None, company_id=None, conversation_id=None,
        )  # must not raise

    async def test_get_leave_balance_timeout_raises(self):
        import httpx

        async def _request(*a, **kw):
            raise httpx.TimeoutException("timed out")

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiTimeout):
                await erp_client.get_leave_balance("tok")

    async def test_apply_leave_sends_only_provided_optional_fields(self):
        captured = {}

        async def _request(method, url, headers=None, json=None, **kwargs):
            captured["json"] = json
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": [{"id": 42}]}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            result = await erp_client.apply_leave(
                "tok", leave_type_slug="casual_leave", from_date="2026-09-01", to_date="2026-09-01",
            )

        assert captured["json"] == {
            "leave_type_slug": "casual_leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
        }
        assert result["body"]["data"][0]["id"] == 42

    async def test_apply_leave_401_raises_unauthorized(self):
        """401 gets its own exception rather than ErpApiUnavailable: a
        rejected caller token means "log in again", which is a different
        message (and a different user action) from "the HR system is down".
        See leave_eligibility_node, which relies on telling them apart."""
        async def _request(*a, **kw):
            resp = MagicMock()
            resp.status_code = 401
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnauthorized):
                await erp_client.apply_leave("tok", "casual_leave", "2026-09-01", "2026-09-01")

    async def test_apply_leave_404_still_raises_unavailable(self):
        """404 on a fixed no-ID route means the route isn't reachable, which
        stays an availability problem — only 401 was split out."""
        async def _request(*a, **kw):
            resp = MagicMock()
            resp.status_code = 404
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnavailable):
                await erp_client.apply_leave("tok", "casual_leave", "2026-09-01", "2026-09-01")

    async def test_get_leave_status_forwards_token_and_url(self):
        captured = {}

        async def _request(method, url, headers=None, **kwargs):
            captured.update(method=method, url=url, headers=headers)
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {"leaves": [{"id": 30}]}}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            result = await erp_client.get_leave_status("caller-token-abc")

        assert captured["method"] == "GET"
        assert captured["url"] == "http://erp.test/api/v1/ai/leave/pending"
        assert captured["headers"]["Authorization"] == "Bearer caller-token-abc"
        assert result["body"]["data"]["leaves"][0]["id"] == 30

    async def test_cancel_leave_sends_leave_id_and_reason(self):
        captured = {}

        async def _request(method, url, headers=None, json=None, **kwargs):
            captured.update(method=method, url=url, headers=headers, json=json)
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {
                "leave_id": 15510, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "sick_leave", "leave_count": "1",
                "cancel_reason": "My plans have changed.",
            }, "message": "Leave request cancelled successfully."}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            result = await erp_client.cancel_leave("caller-token-abc", 15510, "My plans have changed.")

        assert captured["method"] == "POST"
        assert captured["url"] == "http://erp.test/api/v1/ai/leave/cancel"
        assert captured["headers"]["Authorization"] == "Bearer caller-token-abc"
        assert captured["json"] == {"leave_id": 15510, "cancel_reason": "My plans have changed."}
        assert result["body"]["data"]["status_name"] == "Cancelled"

    async def test_cancel_leave_business_rejection_comes_back_as_data_not_an_exception(self):
        """erp-api's sendInfo()/400 convention — an ineligible cancellation
        (already cancelled, locked, etc) must be readable by the caller, not
        raised as ErpApiUnavailable."""
        async def _request(method, url, headers=None, json=None, **kwargs):
            resp = MagicMock()
            resp.status_code = 400
            resp.json.return_value = {"success": False, "message": "Leave request is already cancelled."}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            result = await erp_client.cancel_leave("tok", 1, "reason")

        assert result["body"]["success"] is False
        assert result["body"]["message"] == "Leave request is already cancelled."


# ═════════════════════════════════════════════════════════════════════════════
# leave_action_node — role gate, balance branch, apply branch
# ═════════════════════════════════════════════════════════════════════════════

@pytest.fixture(autouse=True)
def _flush_real_redis_leave_state():
    """Test-isolation safety net, not a feature test of its own.

    Every test in this file that DOESN'T request fake_slots/fake_cancel_
    state/etc. (i.e. doesn't monkeypatch the module-level store) exercises
    the REAL, Redis-backed store instead — using this suite's universally-
    reused company_id=1, conversation_id="conv-1" key, since that's what
    base_state() always returns. If a local Redis happens to be reachable
    and ANY test anywhere leaves data behind under that key (a genuine bug
    in this file, or just ad-hoc manual debugging against the real module),
    a later, completely unrelated test reading the real store picks up
    stale leftover state and fails nondeterministically depending on run
    order and whether Redis happens to be up — confirmed live: a leftover
    "collecting" apply-leave slot made classify_node's mid-flow fast-path
    silently reroute an unrelated cancel_leave test to leave_action_node
    instead. Flushes every key this file's state stores use for that one
    conversation, both before AND after each test (before, in case a
    previous run already left something behind; after, so this test's own
    real-store writes, if any, don't leak into the next one). Silently a
    no-op when Redis is unreachable — the common case in CI — since this is
    a best-effort cleanup, not a requirement for the test to run at all.

    Also covers services.slot_store's "regularization" namespace
    ("regularization_slots:1:conv-1") — classify_node checks that store
    BEFORE either leave slot store (see classify_node.py's mid-flow
    regularisation block, which runs first), so a leftover regularization
    entry silently hijacks classify_node's routing for ANY test in this
    file, not just leave-slot ones — confirmed live: it misrouted a bare
    "Confirm Cancellation" cancel-flow reply into the regularisation
    free-text-answer branch. slot_store.py uses the same Redis connection
    details as leave_slot_service.py, so its client can delete this key
    too without a separate import.
    """
    keys = (
        "leave_slots:1:conv-1",
        "leave_cancel_state:1:conv-1",
        "leave_history_clarify_state:1:conv-1",
        "leave_disambiguation_state:1:conv-1",
        "leave_type_clarify_state:1:conv-1",
        "regularization_slots:1:conv-1",
    )

    def _flush():
        try:
            client = leave_slot_service._get_redis()
            if client:
                client.delete(*keys)
        except Exception:
            pass

    _flush()
    yield
    _flush()


@pytest.fixture
def fake_slots(monkeypatch):
    store = FakeSlotStore()
    # leave_action_node's own calls live in leave_action_service; classify_node's
    # fast-path 0.5 check lives in services.classify_node — both names need the fake.
    monkeypatch.setattr(classify_node_mod, "leave_slot_service", store)
    monkeypatch.setattr(leave_action_service, "leave_slot_service", store)
    return store


class FakeHistoryClarifyStateStore:
    """In-memory stand-in for leave_history_clarify_state, same shape as
    FakeCancelStateStore."""

    def __init__(self):
        self._store = {}

    def _key(self, company_id, conversation_id):
        return f"{company_id}:{conversation_id}"

    def get_state(self, company_id, conversation_id):
        return self._store.get(self._key(company_id, conversation_id))

    def set_state(self, company_id, conversation_id, state):
        self._store[self._key(company_id, conversation_id)] = dict(state)
        return True

    def clear_state(self, company_id, conversation_id):
        self._store.pop(self._key(company_id, conversation_id), None)
        return True


@pytest.fixture
def fake_history_clarify_state(monkeypatch):
    store = FakeHistoryClarifyStateStore()
    # classify_node's fast-path 0.3 lives in services.classify_node;
    # leave_action_service's own leave_status branch sets/reads the same state.
    monkeypatch.setattr(classify_node_mod, "leave_history_clarify_state", store)
    monkeypatch.setattr(leave_action_service, "leave_history_clarify_state", store)
    return store


class FakeDisambiguationStateStore:
    """In-memory stand-in for leave_disambiguation_state."""

    def __init__(self):
        self._store = {}

    def _key(self, company_id, conversation_id):
        return f"{company_id}:{conversation_id}"

    def get_candidates(self, company_id, conversation_id):
        return self._store.get(self._key(company_id, conversation_id))

    def set_candidates(self, company_id, conversation_id, cards):
        self._store[self._key(company_id, conversation_id)] = list(cards)

    def clear_candidates(self, company_id, conversation_id):
        self._store.pop(self._key(company_id, conversation_id), None)


@pytest.fixture
def fake_disambiguation_state(monkeypatch):
    store = FakeDisambiguationStateStore()
    # Same split as fake_slots: classify_node's fast-path lives in
    # services.classify_node, the actual resolution logic lives in leave_action_service.
    monkeypatch.setattr(classify_node_mod, "leave_disambiguation_state", store)
    monkeypatch.setattr(leave_action_service, "leave_disambiguation_state", store)
    return store


class FakeCancelStateStore:
    """In-memory stand-in for leave_cancel_state, same shape as FakeSlotStore."""

    def __init__(self):
        self._store = {}

    def _key(self, company_id, conversation_id):
        return f"{company_id}:{conversation_id}"

    def get_state(self, company_id, conversation_id):
        return self._store.get(self._key(company_id, conversation_id))

    def set_state(self, company_id, conversation_id, state):
        self._store[self._key(company_id, conversation_id)] = dict(state)
        return True

    def clear_state(self, company_id, conversation_id):
        self._store.pop(self._key(company_id, conversation_id), None)
        return True


@pytest.fixture
def fake_cancel_state(monkeypatch):
    store = FakeCancelStateStore()
    # Same split as fake_slots: classify_node's fast-path 0.6 check lives in
    # services.classify_node, leave_action_node's own usage lives in leave_action_service.
    monkeypatch.setattr(classify_node_mod, "leave_cancel_state", store)
    monkeypatch.setattr(leave_action_service, "leave_cancel_state", store)
    return store


async def _no_conflicting_leaves(token, **kwargs):
    """leave_action_node's pre-confirmation date-conflict check (see
    _find_conflicting_leave) calls erp_client.get_leave_status on every
    all-slots-filled turn. Any apply-branch test reaching that point must
    mock this — without it, the call falls through to a REAL, unmocked
    network hit (this is exactly how one test was quietly hitting the live
    local erp-api dev server and passing only because a 401 got swallowed as
    ErpApiUnavailable). Not wired up as an autouse fixture: hr_graph.erp_client
    IS services.erp_client (same module object), so an autouse patch here
    would also hijack TestErpClientLeaveFunctions' tests of the real
    get_leave_status implementation."""
    return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}


@pytest.fixture(autouse=True)
def _stub_failure_enrichment(request, monkeypatch):
    """Safety net for the HEL-283 failure path specifically.

    After an erp-api rejection, leave_action_node calls
    _collect_additional_failures, which fetches holidays, balance and existing
    applications to explain the failure (AC4). A test that mocks only
    apply_leave therefore still reaches three unmocked calls and hits the
    network — which is the live-erp-api problem _no_conflicting_leaves warns
    about above, and it made test_apply_failure_from_erp_api_surfaces_its_message
    pass alone and fail in-suite.

    The objection recorded above — that an autouse patch would hijack
    TestErpClientLeaveFunctions, which exercises the real client — is real, so
    that class is explicitly skipped rather than the idea being abandoned.
    Everything here is a benign default; any test that cares sets its own
    afterwards, which wins.
    """
    if request.cls is not None and request.cls.__name__ == "TestErpClientLeaveFunctions":
        return

    async def _no_holidays(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {
            "year": 2026, "department": "Shopfloor Team",
            "total_holidays": 0, "holidays": [],
        }}}

    async def _ample_balance(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {
            "leave_quota": {"casual_leave": {"total": "24", "remaining": "24"},
                            "sick_leave": {"total": "12", "remaining": "12"}},
        }}}

    async def _no_leaves(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}

    monkeypatch.setattr(hr_graph.erp_client, "get_leave_holidays", _no_holidays, raising=False)
    monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _ample_balance)
    monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_leaves)


def not_manager_context():
    async def _f(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {"is_manager": False}}}
    return _f


def manager_context():
    async def _f(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {"is_manager": True}}}
    return _f


# ═════════════════════════════════════════════════════════════════════════════
# classify_node — is_database_related / has_date_expression signals
# ═════════════════════════════════════════════════════════════════════════════

class TestClassifyNodeClassificationFlags:

    @pytest.mark.parametrize("label,expected", [
        ("leave_balance", True),   # wired — leave_action_node calls erp_client today
        ("apply_leave", True),
        ("leave_status", True),
        ("attendance", True),      # erp-api endpoint exists, not yet wired — still True
        ("payroll", True),
        ("salary", True),
        ("performance", True),
        ("leave_policy", False),   # general knowledge, no backend lookup
        ("benefits", False),       # no matching erp-api module exists
        ("non_hr", False),
    ])
    async def test_is_database_related_matches_intent(self, monkeypatch, fake_slots, label, expected):
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return label, None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        writer = FakeWriter()
        result = await hr_graph.classify_node(base_state("some ambiguous query", "general"), writer)

        assert result["intent"] == label
        assert result["is_database_related"] is expected

    async def test_has_date_expression_true_for_dated_query(self, monkeypatch, fake_slots):
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "leave_status", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        writer = FakeWriter()
        result = await hr_graph.classify_node(
            base_state("show my leave details for 21th august", "general"), writer
        )

        assert result["has_date_expression"] is True

    async def test_has_date_expression_false_for_dateless_query(self, monkeypatch, fake_slots):
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "leave_status", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        writer = FakeWriter()
        result = await hr_graph.classify_node(base_state("what's my leave status", "general"), writer)

        assert result["has_date_expression"] is False


# ═════════════════════════════════════════════════════════════════════════════
# classify_node — mid-flow interruption detection (Fast-path 0.5)
# ═════════════════════════════════════════════════════════════════════════════

class TestClassifyNodeMidFlowInterruption:

    async def test_balance_question_interrupts_apply_flow_classification(self, fake_slots):
        fake_slots.set_slots(1, "conv-1", {"step": "collecting", "leave_type": None})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("how many types of leave do I have"), writer)

        assert result["intent"] == "leave_balance"

    async def test_status_question_interrupts_apply_flow_classification(self, fake_slots):
        fake_slots.set_slots(1, "conv-1", {"step": "collecting", "leave_type": "casual_leave"})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("what's the status of my leave"), writer)

        assert result["intent"] == "leave_status"

    @pytest.mark.parametrize("query", ["cancel my leave", "cancel this application", "cancel my pending request"])
    async def test_bare_cancel_during_apply_flow_stays_in_apply_leave_not_cancel_leave(
        self, fake_slots, query,
    ):
        """Live bug report: mid-application 'cancel my leave'/'cancel this
        application' got treated as a confident interruption into the
        cancel_leave flow (asking to pick a PENDING submitted leave to
        cancel) instead of being recognized as a request to discard the
        in-progress draft. fast_classify confidently returns cancel_leave
        for phrasing like this (see _CANCEL_LEAVE_PATTERNS in
        nlp_service.py), but without an explicit reference number it must
        stay in the apply flow, where leave_action_service.py's own
        discard check handles it."""
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "casual_leave",
            "from_date": None, "to_date": None, "reason": None,
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state(query), writer)

        assert result["intent"] == "apply_leave"

    async def test_bare_cancel_at_confirmation_step_stays_in_apply_leave_not_cancel_leave(
        self, fake_slots,
    ):
        """Live bug report: a bare 'cancel' reply to the apply-flow's own
        awaiting_confirmation prompt ('Shall I submit this request?') never
        matches fast_classify's _CANCEL_LEAVE_PATTERNS — those require an
        object word ('leave'/'request'/'application') near 'cancel', which a
        bare one-word reply doesn't have — so interrupt_intent comes back
        None and the turn fell through to the LLM fallback classifier, which
        guessed cancel_leave. That routed into the cancel SEARCH flow (fetch
        existing requests, ask which one to cancel) instead of ever reaching
        leave_action_service.py's deterministic discard check, which does
        correctly match a bare \\bcancel\\b."""
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "sick_leave",
            "from_date": "2026-09-22", "to_date": "2026-09-22",
            "session_type_slug": "full_day", "reason": "going out",
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("cancel"), writer)

        assert result["intent"] == "apply_leave"

    async def test_cancel_with_explicit_reference_during_apply_flow_still_interrupts(self, fake_slots):
        """Contrast with the bare-cancel test above: an EXPLICIT reference
        number is trusted to mean a genuinely different, already-submitted
        request, so it's still treated as a real interruption into
        cancel_leave — the apply-leave draft is left untouched to resume
        afterward, same as any other interruption."""
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "casual_leave",
            "from_date": None, "to_date": None, "reason": None,
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("cancel LR-2041"), writer)

        assert result["intent"] == "cancel_leave"

    async def test_ambiguous_reply_still_defaults_to_apply_leave(self, monkeypatch, fake_slots):
        """Regression guard: a genuine slot-filling reply ('full day', a date
        range) must still route to apply_leave, not get accidentally caught
        by the interruption check. 'full day' has zero fast_classify keyword
        hits (same as any bare date/confirmation reply), so it now goes
        through the fallback LLM classifier (see the ambiguous-reply fix
        below) — mocked here to return what a context-aware real classifier
        would say for a slot-filling continuation."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "apply_leave", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        fake_slots.set_slots(1, "conv-1", {"step": "collecting", "leave_type": "casual_leave"})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("full day"), writer)

        assert result["intent"] == "apply_leave"

    async def test_unrelated_query_with_no_keyword_hits_interrupts_apply_flow(self, monkeypatch, fake_slots):
        """Bug repro (live transcript): after an insufficient-balance
        re-prompt for alternate dates, the user asked 'generate a jd for ai
        engineer' — completely unrelated, but fast_classify only weakly
        matches 'jd' (1 hit; job_description needs 2), so it returns
        (None, True, 0.0). The old code treated ANY fast_classify miss as
        'still filling slots' and looped 'What dates would you like to take
        off?' forever. It must now fall back to the real classifier and
        honor a genuine topic switch even when fast_classify has no opinion
        at all, not just when it confidently disagrees."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "job_description", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave",
            "from_date": None, "to_date": None, "reason": "Fever",
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(
            base_state("generate a jd for ai engineer"), writer
        )

        assert result["intent"] == "job_description"
        assert result["is_hr"] is True

    async def test_unrelated_topic_interrupts_apply_flow_classification(self, fake_slots):
        """Live bug repro: a completely unrelated question asked mid-flow was
        silently swallowed as slot-filling input — the user got a leave
        confirmation prompt ('Shall I submit this request?') instead of an
        answer to their actual question, because only leave_balance/
        leave_status were treated as valid interruptions. fast_classify
        already correctly identifies this as 'salary' with full confidence;
        classify_node just wasn't listening to it."""
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "short_leave",
            "from_date": "2026-08-18", "to_date": "2026-08-18",
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(
            base_state("i want to know the salary range for ai engineer"), writer
        )

        assert result["intent"] == "salary"
        assert result["is_hr"] is True

    async def test_bare_leave_type_reply_does_not_falsely_interrupt(self, fake_slots):
        """Regression guard for the fix above: "casual leave" / "sick leave"
        — the single most common, correct reply during slot collection —
        classifies as 'leave_policy' at full confidence (bare leave-type
        names are also leave_policy keywords). A naive 'anything but
        apply_leave is an interruption' rule would break the mainline apply
        flow on nearly every turn; leave_policy must be excluded."""
        fake_slots.set_slots(1, "conv-1", {"step": "collecting", "leave_type": None})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("casual leave on 2026-09-01"), writer)

        assert result["intent"] == "apply_leave"

    async def test_genuine_policy_question_interrupts_apply_flow(self, fake_slots):
        """Live bug repro: 'what is the sick leave policy' asked mid-flow
        also classifies as 'leave_policy' via fast_classify's keyword list —
        same as a bare 'casual leave' slot reply — so blanket-excluding
        leave_policy from interruption detection (the previous fix for the
        test above) silently absorbed genuine questions into slot extraction
        too: extraction finds no leave type in it, and the user's actual
        question was never answered, just re-prompted for the missing slot
        forever. A real question must still interrupt and get answered."""
        fake_slots.set_slots(1, "conv-1", {"step": "collecting", "leave_type": None})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("what is the sick leave policy"), writer)

        assert result["intent"] == "leave_policy"
        assert result["is_hr"] is True

    async def test_no_existing_slots_uses_normal_classification(self, monkeypatch, fake_slots):
        """When there's no apply-leave draft at all, the mid-flow check must
        not fire — the query goes through the real structured classifier."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "leave_balance", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        writer = FakeWriter()
        result = await hr_graph.classify_node(
            {**base_state("what is my leave balance?"), "intent": "leave_balance"}, writer
        )

        assert result["intent"] == "leave_balance"

    async def test_llm_classification_wins_over_fast_classify_disagreement(self, monkeypatch, fake_slots):
        """Core architectural regression guard: fast_classify's ≥0.5-confidence
        guess (pre_intent, set as state['intent'] by main.py) must NEVER be
        trusted outright anymore — the real structured classifier's result
        wins even when the two disagree. This is the fix for the live
        misrouting bug class (e.g. 'check my leave quota' → apply_leave):
        fast_classify's keyword lists are closed by construction and will
        always miss some real paraphrase; the architecture must not let that
        alone decide the outcome."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "leave_balance", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        writer = FakeWriter()
        # state["intent"] simulates fast_classify confidently (wrongly) having
        # said apply_leave — the LLM mock says leave_balance instead.
        result = await hr_graph.classify_node(
            {**base_state("check my leave quota"), "intent": "apply_leave"}, writer
        )

        assert result["intent"] == "leave_balance"

    async def test_awaiting_reason_reply_never_hits_llm_fallback_classifier(self, monkeypatch, fake_slots):
        """Live bug repro: replying 'vocation' to 'What's the reason for
        this leave request?' (leave_type/dates already set, only reason
        missing) got sent to the LLM fallback classifier — which, with no
        signal that a reason was specifically being asked for, read the
        bare word as off-topic and returned non_hr, silently discarding the
        whole in-progress application ('That's outside my area...'). The
        reason field is free text with no closed vocabulary — fast_classify
        can never confidently match it (confirmed: fast_classify('vocation')
        == (None, True, 0.0)) — so the fallback classifier must be skipped
        entirely for this slot, never even called."""
        def _must_not_be_called(prompt, valid_labels, fallback_label="general_hr"):
            raise AssertionError("LLM fallback classifier must not be called while awaiting reason only")
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _must_not_be_called)

        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave",
            "from_date": "2026-08-23", "to_date": "2026-08-23",
            "session_type_slug": "full_day", "reason": None,
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("vocation"), writer)

        assert result["intent"] == "apply_leave"
        assert result["is_hr"] is True

    async def test_genuine_interruption_still_caught_while_awaiting_reason(self, fake_slots):
        """Regression guard for the fix above: is_awaiting_reason_only must
        only skip the AMBIGUOUS-case LLM fallback, never fast_classify's own
        deterministic, confident interruption detection — a real question
        asked instead of supplying a reason must still interrupt and get
        answered, not be swallowed as reason text."""
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave",
            "from_date": "2026-08-23", "to_date": "2026-08-23",
            "session_type_slug": "full_day", "reason": None,
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("what is the maternity leave policy"), writer)

        assert result["intent"] == "leave_policy"
        assert result["is_hr"] is True

    async def test_fallback_prompt_describes_awaited_dates_slot(self, monkeypatch, fake_slots):
        """The 'vocation' bug's root cause was the fallback classifier having
        no idea a specific question was pending. Prove the fix actually wires
        that context through for a step OTHER than reason (dates), which
        still must go through the fallback (see the 'generate a jd' test
        above — dates can't use the reason slot's full bypass)."""
        captured = {}

        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            captured["prompt"] = prompt
            return "apply_leave", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave",
            "from_date": None, "to_date": None, "reason": None,
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("tomorrow"), writer)

        assert result["intent"] == "apply_leave"
        assert "the DATES for their leave" in captured["prompt"]

    async def test_fallback_prompt_describes_awaited_confirmation(self, monkeypatch, fake_slots):
        """Same wiring, for the confirmation step — the most consequential
        gap, since a misfire here silently drops a fully-collected, ready-to-
        submit request instead of just re-asking a question."""
        captured = {}

        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            captured["prompt"] = prompt
            return "apply_leave", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "sick_leave",
            "from_date": "2026-08-23", "to_date": "2026-08-23",
            "session_type_slug": "full_day", "reason": "fever",
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("yah go for it"), writer)

        assert result["intent"] == "apply_leave"
        assert "CONFIRM submitting their leave request" in captured["prompt"]

    async def test_genuine_interruption_still_caught_at_confirmation_step(self, fake_slots):
        """Regression guard for the fix above: the new awaited-slot context
        must only help the classifier resolve a genuinely ambiguous reply —
        it must never suppress a confidently-detected real interruption.
        'what's my leave balance' hits fast_classify's own keyword patterns
        directly, so this must be caught before the fallback classifier (and
        its new context) is even consulted."""
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "sick_leave",
            "from_date": "2026-08-23", "to_date": "2026-08-23",
            "session_type_slug": "full_day", "reason": "fever",
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("what's my leave balance"), writer)

        assert result["intent"] == "leave_balance"
        assert result["is_hr"] is True

    async def test_unrecognized_llm_label_falls_back_safely(self, monkeypatch, fake_slots):
        """A GENUINE classification failure (classify_intent_structured's own
        fallback path — the LLM call broke, or returned something off the
        enum) must not silently pass through as though 'general_hr' were a
        real, confident answer — that used to let hr_response_node answer a
        genuinely unclear message as if it were a normal broad HR question.
        It now short-circuits with an honest 'not sure what you mean' reply
        instead (classify_intent_structured's own contract of always
        returning an enum-valid label is unchanged and still covered by its
        own unit tests in test_intent_classification.py)."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return fallback_label, None, True  # simulates classify_intent_structured's own fallback path
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        writer = FakeWriter()
        result = await hr_graph.classify_node(base_state("some ambiguous query"), writer)

        # services/classify_node.py's classification_failed branch — the
        # actual, shipped values (not "unclear"; that string appears
        # nowhere in classify_node.py, which uses "unknown"/"flagged"
        # consistently across every one of its own failure paths).
        assert result["intent"] == "unknown"
        assert result["is_hr"] is False
        assert result["error"] == "flagged"
        assert "not sure what you're asking" in writer.of_type("error")[0]["message"].lower()


# classify_node's old Fast-path 2 (short-fragment -> generic 'follow_up'
# before either classifier ran) was removed entirely — see
# tests/test_classify_short_fragments.py for its full replacement coverage,
# including the negative control for genuine short follow-ups.


class TestClassifyNodeValidIntentLabels:

    def test_cancel_leave_is_a_valid_llm_label(self):
        """Regression: cancel_leave was added to hr_graph's intent prompt but
        dropped from _VALID_INTENT_LABELS during the classify_node refactor —
        classify_intent_structured's enum validation would silently reject
        any real 'cancel_leave' the LLM returned, since a label missing from
        this set can never survive server-side validation."""
        assert "cancel_leave" in hr_graph._VALID_INTENT_LABELS

    async def test_cancel_leave_from_the_llm_survives_classify_node_unchanged(self, monkeypatch):
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            assert "cancel_leave" in valid_labels
            return "cancel_leave", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        writer = FakeWriter()
        result = await hr_graph.classify_node(base_state("please cancel my leave request"), writer)

        assert result["intent"] == "cancel_leave"
        assert result["is_hr"] is True


# ═════════════════════════════════════════════════════════════════════════════
# classify_node — balance-vs-status disagreement asks a clarifying question
# instead of silently picking one (narrow, confidence-gated safety net —
# only this specific pair, not every fast_classify/LLM disagreement)
# ═════════════════════════════════════════════════════════════════════════════

class TestClassifyNodeLeaveHistoryClarification:

    @pytest.mark.parametrize("reply,expected_intent,expected_query_contains", [
        ("my balance please", "leave_balance", "leave balance"),
        ("how many days do I have left", "leave_balance", "leave balance"),
        ("pending please", "leave_status", "pending"),
        ("approved", "leave_status", "approved"),
        ("cancelled ones", "leave_status", "cancelled"),
        ("rejected", "leave_status", "rejected"),
        ("all of them", "leave_status", "all"),
        ("applied leaves", "leave_status", "all"),
    ])
    async def test_reply_resolves_to_the_right_intent_and_rewritten_query(
        self, fake_history_clarify_state, reply, expected_intent, expected_query_contains,
    ):
        fake_history_clarify_state.set_state(1, "conv-1", {"leave_type_slug": None})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state(reply), writer)

        assert result["intent"] == expected_intent
        assert expected_query_contains in result["query"].lower()
        assert fake_history_clarify_state.get_state(1, "conv-1") is None

    async def test_leave_type_mentioned_on_the_original_turn_is_preserved_through_resolution(
        self, fake_history_clarify_state,
    ):
        """'show my sick leaves' -> clarify asked, 'sick_leave' stored -> a
        bare 'approved' reply must still resolve to SICK approved leaves,
        not approved leaves of every type."""
        fake_history_clarify_state.set_state(1, "conv-1", {"leave_type_slug": "sick_leave"})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("approved"), writer)

        assert result["intent"] == "leave_status"
        assert "sick" in result["query"].lower()
        assert "approved" in result["query"].lower()

    async def test_unrecognized_reply_clears_state_and_falls_through_to_normal_classification(
        self, monkeypatch, fake_history_clarify_state,
    ):
        fake_history_clarify_state.set_state(1, "conv-1", {"leave_type_slug": None})

        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "general_hr", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        writer = FakeWriter()
        result = await hr_graph.classify_node(base_state("actually never mind, different question"), writer)

        assert result["intent"] == "general_hr"
        assert fake_history_clarify_state.get_state(1, "conv-1") is None

    async def test_reply_answering_type_category_and_date_range_all_at_once(
        self, fake_history_clarify_state,
    ):
        """The combined clarify message asks for type, category, and date
        range in one go — a reply answering all three ('sick leave,
        approved, last week') must resolve all three, none stored yet."""
        fake_history_clarify_state.set_state(1, "conv-1", {"leave_type_slug": None})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("sick leave, approved, last week"), writer)

        assert result["intent"] == "leave_status"
        q = result["query"].lower()
        assert "sick" in q
        assert "approved" in q
        assert "from " in q and " to " in q  # a resolved date range was spliced in

    async def test_date_range_given_on_the_original_turn_is_preserved_through_resolution(
        self, fake_history_clarify_state,
    ):
        """'show my leaves last month' -> clarify asked (category still
        unknown) -> a bare 'approved' reply must still carry the ORIGINAL
        date range through, not drop it."""
        fake_history_clarify_state.set_state(1, "conv-1", {
            "leave_type_slug": None, "date_from": "2026-07-01", "date_to": "2026-07-31",
        })
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("approved"), writer)

        assert result["intent"] == "leave_status"
        assert "from 2026-07-01 to 2026-07-31" in result["query"].lower()


class TestResolveDateRangePhrase:

    def test_explicit_iso_range(self):
        assert leave_action_service._resolve_date_range_phrase(
            "leaves from 2026-06-01 to 2026-08-01"
        ) == ("2026-06-01", "2026-08-01")

    def test_no_range_phrase_returns_none_none(self):
        assert leave_action_service._resolve_date_range_phrase("show me my leaves") == (None, None)

    def test_explicit_all_time_returns_none_none(self):
        assert leave_action_service._resolve_date_range_phrase("show me all time") == (None, None)

    def test_last_n_days(self):
        import datetime as _dt
        today = leave_action_service._today()
        expected_from = (today - _dt.timedelta(days=10)).isoformat()
        assert leave_action_service._resolve_date_range_phrase("last 10 days") == (expected_from, today.isoformat())

    def test_this_month(self):
        today = leave_action_service._today()
        date_from, date_to = leave_action_service._resolve_date_range_phrase("this month")
        assert date_from == today.replace(day=1).isoformat()
        assert date_to == today.isoformat()


class TestLeaveActionNodeRoleGate:

    async def test_manager_gets_own_balance_same_as_an_employee(self, monkeypatch, fake_slots):
        """Managers get full self-service — leave_balance/apply_leave/
        leave_status are never role-restricted. Every erp_client call is
        scoped to the caller's own token, so this can't leak a team view;
        there's no separate manager-vs-employee behavior left to gate."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("what's my leave balance", "leave_balance"), writer)

        done = writer.of_type("done")
        assert len(done) == 1
        assert done[0]["intent"] == "leave_balance"
        balance_events = writer.of_type("leave_balance")
        assert len(balance_events) == 1
        assert balance_events[0]["data"]["leave_quota"]["casual_leave"]["remaining"] == "5"

    async def test_context_timeout_gives_clean_message_not_a_crash(self, monkeypatch, fake_slots):
        async def _timeout(token, **kwargs):
            raise ErpApiTimeout("timed out")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _timeout)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("what's my leave balance", "leave_balance"), writer)

        assert "try again" in result["response_text"].lower()
        assert writer.of_type("leave_balance") == []


class TestLeaveActionNodeBalanceBranch:

    async def test_balance_branch_happy_path(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("what's my leave balance", "leave_balance"), writer)

        balance_events = writer.of_type("leave_balance")
        assert len(balance_events) == 1
        assert balance_events[0]["data"]["leave_quota"]["casual_leave"]["remaining"] == "5"
        assert writer.of_type("fetching_balance")

    async def test_balance_branch_attaches_followup_suggestions(self, monkeypatch, fake_slots):
        """AC6-style follow-ups shouldn't be exclusive to the pending-status
        view — balance responses should offer relevant next actions too."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("what's my leave balance", "leave_balance"), writer)

        suggestions = writer.of_type("leave_balance")[0]["data"]["suggestions"]
        assert "Would you like to check your pending leave requests?" in suggestions
        assert "Would you like to apply for leave?" in suggestions

    async def test_balance_branch_erp_api_failure_surfaces_real_message_not_a_false_success(
        self, monkeypatch, fake_slots,
    ):
        """Live bug repro: erp-api's sendInfo() returns success:false with a
        400 for business-rule failures — _request() passes that through as a
        normal result, not an exception. Previously nothing checked
        'success', so this silently fell through to an empty {} data
        payload while still saying 'Here's your current leave balance.' —
        looked successful, showed nothing."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 400, "body": {
                "success": False, "message": "No leave settings configured for your account.",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("what's my leave balance", "leave_balance"), writer)

        assert writer.of_type("leave_balance") == []
        assert "No leave settings configured for your account." in result["response_text"]
        assert "Here's your current leave balance" not in result["response_text"]

    async def test_balance_branch_parses_the_real_erp_api_payload_shape(self, monkeypatch, fake_slots):
        """Pinned against an actual live /api/v1/ai/leave/balance response
        (2026-08-18) — confirms erp-api itself was healthy (success:true,
        populated leave_quota) for the account that saw the empty-data bug,
        so that was a genuine transient/failure response, not a permanent
        account-config issue. Also guards real-world quirks this shape has
        that the earlier hand-written mocks didn't: int (not string) totals
        for some types, and extra top-level keys (notify, pendings) that
        must be ignored rather than tripping anything up."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {
                "success": True,
                "data": {
                    "leave_quota": {
                        "casual_leave": {"total": 24, "remaining": "14"},
                        "sick_leave": {"total": 12, "remaining": "7"},
                        "short_leave": {"total": 24, "remaining": "14"},
                        "comp_off": {"total": 0, "remaining": 0},
                        "leave_without_pay": {"total": 0, "remaining": 0},
                    },
                    "leave_settings": {
                        "leave_type": [
                            {"name": "Casual Leave", "slug": "casual_leave", "quota": 24,
                             "max_apply_in_month": 1, "oneTypeMax": "2"},
                        ],
                        "regularization_limit": "10",
                    },
                },
                "message": "success",
                "notify": [{"id": 276, "notification": "A New announcement from HR"}],
                "pendings": {"leaves": "", "regularizations": "", "comp_offs": "", "work_from_home": ""},
            }}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("whats my pending leave balance", "leave_balance"), writer
        )

        balance_events = writer.of_type("leave_balance")
        assert len(balance_events) == 1
        quota = balance_events[0]["data"]["leave_quota"]
        assert quota["casual_leave"] == {"total": 24, "remaining": "14"}
        assert quota["comp_off"] == {"total": 0, "remaining": 0}
        assert "Here's your current leave balance." in result["response_text"]

    async def test_balance_branch_success_but_empty_quota_gives_honest_message(self, monkeypatch, fake_slots):
        """Same failure mode, different cause: success:true but no
        leave_quota at all (e.g. nothing configured) must not claim success
        with an empty card either."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("what's my leave balance", "leave_balance"), writer)

        assert writer.of_type("leave_balance") == []
        assert "couldn't find any leave balance information" in result["response_text"]

    async def test_balance_branch_filters_to_the_named_leave_type(self, monkeypatch, fake_slots):
        """Regression: 'How many SICK leaves do I have left' previously got
        the exact same full-breakdown answer (every type, casual included)
        as a bare 'what's my leave balance' — the response never actually
        reflected which type was asked about."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {
                    "casual_leave": {"total": "7", "remaining": "5"},
                    "sick_leave": {"total": "7", "remaining": "4.7"},
                    "earned_leave": {"total": "0", "remaining": "0"},
                },
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("How many sick leaves do I have left?", "leave_balance"), writer
        )

        balance_events = writer.of_type("leave_balance")
        assert len(balance_events) == 1
        returned_quota = balance_events[0]["data"]["leave_quota"]
        assert returned_quota == {"sick_leave": {"total": "7", "remaining": "4.7"}}
        assert "4.7" in result["response_text"]
        assert "Sick Leave" in result["response_text"]

    async def test_balance_branch_names_the_leave_type_instead_of_generic_days(self, monkeypatch, fake_slots):
        """'You have 14 Casual Leaves remaining out of 24' — not the
        grammatically-off 'You have 14 Casual Leave day(s) remaining'."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "24", "remaining": "14"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("how many casual leaves do I have left", "leave_balance"), writer
        )
        assert result["response_text"] == "You have 14 Casual Leaves remaining out of 24."

    async def test_balance_branch_multiple_named_types_shows_all_of_them(self, monkeypatch, fake_slots):
        """Live bug repro: 'how many casual AND sick leaves do I have'
        previously only answered casual — the type filter only ever
        returned its first match, silently dropping the rest of a
        multi-type question."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {
                    "casual_leave": {"total": "7", "remaining": "5"},
                    "sick_leave": {"total": "7", "remaining": "6"},
                    "earned_leave": {"total": "15", "remaining": "10"},
                },
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("how many casual and sick leaves do I have", "leave_balance"), writer
        )

        returned_quota = writer.of_type("leave_balance")[0]["data"]["leave_quota"]
        assert set(returned_quota.keys()) == {"casual_leave", "sick_leave"}
        assert "earned_leave" not in returned_quota
        assert "Casual Leave" in result["response_text"]
        assert "Sick Leave" in result["response_text"]

    async def test_balance_branch_no_type_named_returns_full_breakdown(self, monkeypatch, fake_slots):
        """Negative control: a generic balance question must still return
        every leave type, not just whichever one happens to match first."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {
                    "casual_leave": {"total": "7", "remaining": "5"},
                    "sick_leave": {"total": "7", "remaining": "4.7"},
                },
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("what's my leave balance", "leave_balance"), writer)

        returned_quota = writer.of_type("leave_balance")[0]["data"]["leave_quota"]
        assert set(returned_quota.keys()) == {"casual_leave", "sick_leave"}
        assert "current leave balance" in result["response_text"]

    async def test_balance_branch_named_type_absent_from_quota_falls_back_to_full(self, monkeypatch, fake_slots):
        """A leave type word appearing in the query but not present in this
        employee's quota (e.g. no comp_off entitlement configured) must not
        silently return an empty filtered result — fall back to the full
        breakdown instead."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("how many comp off do I have", "leave_balance"), writer)

        returned_quota = writer.of_type("leave_balance")[0]["data"]["leave_quota"]
        assert set(returned_quota.keys()) == {"casual_leave"}
        assert "current leave balance" in result["response_text"]

    async def test_balance_question_answered_mid_apply_flow_without_clearing_slots(self, monkeypatch, fake_slots):
        """Regression: 'how many types of leave do I have' asked WHILE an
        apply-leave draft is in progress must actually answer the balance
        question (previously it was swallowed and just re-asked the same
        slot-filling question forever), and must not disturb the draft."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        in_progress_slots = {
            "step": "collecting", "leave_type": None, "from_date": None,
            "to_date": None, "session_type_slug": None, "reason": None,
        }
        fake_slots.set_slots(1, "conv-1", dict(in_progress_slots))

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "7"},
                                "sick_leave": {"total": "7", "remaining": "7"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("how many types of leave do I have", "leave_balance"), writer
        )

        assert writer.of_type("leave_balance")
        assert "in progress" in result["response_text"]
        # The draft must survive — untouched — so the user can resume it.
        assert fake_slots.get_slots(1, "conv-1") == in_progress_slots

    async def test_status_question_answered_mid_apply_flow_without_clearing_slots(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        in_progress_slots = {
            "step": "collecting", "leave_type": "casual_leave", "from_date": None,
            "to_date": None, "session_type_slug": None, "reason": None,
        }
        fake_slots.set_slots(1, "conv-1", dict(in_progress_slots))

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("what's the status of my leave", "leave_status"), writer
        )

        assert "You currently have no pending leave requests." in result["response_text"]
        assert "in progress" in result["response_text"]
        assert fake_slots.get_slots(1, "conv-1") == in_progress_slots


class TestLeaveActionNodeApplyBranch:

    async def test_cancel_while_still_collecting_discards_the_draft(self, monkeypatch, fake_slots):
        """Live bug report: saying 'cancel this' while still collecting the
        leave type/dates/reason (not yet at the final awaiting_confirmation
        step) used to fall through to slot extraction, find nothing new,
        and silently re-ask for whatever was still missing — never
        recognizing the discard request at all. Must discard the draft
        immediately, at any step, and never even reach the (expensive) slot
        extraction call."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "casual_leave",
            "from_date": None, "to_date": None, "session_type_slug": None, "reason": None,
        })
        never_called = MagicMock(side_effect=AssertionError("slot extraction must not run for a discard reply"))
        monkeypatch.setattr(leave_action_service, "_call_llm", never_called)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel this application"), writer)

        assert "cancelled" in result["response_text"].lower()
        assert fake_slots.get_slots(1, "conv-1") is None
        never_called.assert_not_called()

    async def test_bare_half_day_reply_asks_which_half_instead_of_guessing(self, monkeypatch, fake_slots):
        """Live bug repro: user replies 'half day' (no "first"/"second")
        to 'full day or half day?'. Previously the LLM had no way to signal
        that ambiguity — the extraction prompt only listed first_half_day/
        second_half_day as options — so it silently guessed first_half_day
        and went straight to a confirmation prompt without ever telling the
        user it had guessed."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        from datetime import timedelta
        single_day = (leave_action_service._today_in_app_timezone() + timedelta(days=7)).isoformat()
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "earned_leave",
            "from_date": single_day, "to_date": single_day,
            "session_type_slug": None, "reason": None,
        })

        # The (now-updated) extraction prompt returns the generic "half_day"
        # slug for a bare "half day" reply rather than guessing which half.
        mock_extraction(monkeypatch, {"session_type_slug": "half_day"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("half day"), writer)

        assert writer.of_type("leave_confirmation") == []
        assert "first half or second half" in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["session_type_slug"] is None  # cleared, not silently accepted

    async def test_explicit_half_reply_after_ambiguity_prompt_completes_normally(self, monkeypatch, fake_slots):
        """The follow-up ('first half'/'second half') must resolve normally
        once the user actually answers which half — this isn't a dead end."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"earned_leave": {"total": "15", "remaining": "15"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        from datetime import timedelta
        single_day = (leave_action_service._today_in_app_timezone() + timedelta(days=7)).isoformat()
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "earned_leave",
            "from_date": single_day, "to_date": single_day,
            "session_type_slug": None, "reason": "personal work",
        })

        mock_extraction(monkeypatch, {"session_type_slug": "second_half_day"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("second half"), writer)

        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert confirmation[0]["data"]["session_type_slug"] == "second_half_day"
        assert confirmation[0]["data"]["total_days"] == 0.5
        assert "shall i submit" in result["response_text"].lower()

    async def test_unrecognized_leave_type_gets_an_explicit_denial(self, monkeypatch, fake_slots):
        """'I want to apply maternity leave' — maternity isn't a slug this
        codebase (or this company) knows. Extraction correctly leaves
        leave_type null for it (existing behavior — never guess), but that
        used to just re-ask 'what type of leave?' with no acknowledgement
        of what the user actually said, reading as the bot ignoring them.
        Must explicitly say the named type isn't available, listing the
        real options."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {
                    "casual_leave": {"total": 12, "remaining": 12},
                    "sick_leave": {"total": 10, "remaining": 10},
                },
                "leave_settings": {"leave_type": [
                    {"slug": "casual_leave", "name": "Casual Leave"},
                    {"slug": "sick_leave", "name": "Sick Leave"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {"unrecognized_leave_type": "maternity"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("I want to apply maternity leave"), writer)

        message = result["response_text"]
        assert "maternity" in message.lower()
        assert "Casual Leave" in message
        assert "Sick Leave" in message
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["leave_type"] is None  # never guessed

    @pytest.mark.parametrize("reply", ["Short Leave", "short leave", "SHORT LEAVE", "Short_Leave", "short"])
    async def test_capitalized_known_leave_type_is_recovered_not_denied(
        self, monkeypatch, fake_slots, reply,
    ):
        """Live bug: replying "Short Leave" — capitalized exactly as the bot
        itself had just printed it — came back from extraction as
        unrecognized_leave_type, so the bot answered 'We don't have a "short
        leave" leave type — the leave types you can apply for are: Casual
        Leave, Sick Leave, Earned Leave, or Short Leave.', denying a type it
        listed as available in the same breath. Extraction flagging
        something unrecognized is not authoritative — the company's real
        configured list is, and it must be consulted before any denial,
        under any capitalization or separator style."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {
                    "casual_leave": {"total": 12, "remaining": 12},
                    "short_leave": {"total": 10, "remaining": 10},
                },
                "leave_settings": {"leave_type": [
                    {"slug": "casual_leave", "name": "Casual Leave"},
                    {"slug": "short_leave", "name": "Short Leave"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {"unrecognized_leave_type": reply})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state(reply), writer)

        assert "don't have" not in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["leave_type"] == "short_leave"

    async def test_leave_type_returned_as_display_name_is_canonicalized_to_slug(
        self, monkeypatch, fake_slots,
    ):
        """The other half of the same bug: when extraction returns
        leave_type as the DISPLAY NAME ("Short Leave") rather than the slug,
        it used to be stored verbatim, pass every local check, and only fail
        at erp-api's own apply() call — after the user had already
        confirmed. Must be canonicalized to the real slug up front."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"short_leave": {"total": 10, "remaining": 10}},
                "leave_settings": {"leave_type": [
                    {"slug": "short_leave", "name": "Short Leave"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {"leave_type": "Short Leave"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("Short Leave"), writer)

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["leave_type"] == "short_leave"

    async def test_genuinely_unknown_type_is_still_denied(self, monkeypatch, fake_slots):
        """Guard: the recovery above must not turn the denial path into a
        rubber stamp — a type this company really doesn't have is still
        rejected, by name, exactly as before."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": 12, "remaining": 12}},
                "leave_settings": {"leave_type": [
                    {"slug": "casual_leave", "name": "Casual Leave"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {"unrecognized_leave_type": "Maternity Leave"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Maternity Leave"), writer)

        assert "don't have" in result["response_text"].lower()
        assert fake_slots.get_slots(1, "conv-1")["leave_type"] is None

    async def test_ask_leave_type_lists_the_companys_real_configured_types(self, monkeypatch, fake_slots):
        """Live bug repro: the 'what type of leave?' question used to always
        say 'casual, sick, earned, or something else?' — a fixed, hardcoded
        set — so a company that also has short_leave/comp_off configured
        (as this fake company does) never had those mentioned anywhere, and
        a user had no way to know they were valid answers. The question must
        list this company's REAL configured types, fetched live from
        erp-api, not a hardcoded guess. leave_without_pay here is present in
        leave_quota (with a zero balance, exactly like the live repro) but
        deliberately absent from leave_settings.leave_type's name list — the
        type list must still include it (sourced from leave_quota, the
        complete list — see _fetch_known_leave_types), deriving its display
        name from the slug since no explicit name was given."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {
                    "casual_leave": {"total": 24, "remaining": "13"},
                    "sick_leave": {"total": 12, "remaining": "7"},
                    "short_leave": {"total": 24, "remaining": "14"},
                    "comp_off": {"total": 0, "remaining": 0},
                    "leave_without_pay": {"total": 0, "remaining": 0},
                },
                "leave_settings": {"leave_type": [
                    {"slug": "casual_leave", "name": "Casual Leave (CL)"},
                    {"slug": "sick_leave", "name": "Sick Leave (SL)"},
                    {"slug": "short_leave", "name": "Short Leave"},
                    {"slug": "comp_off", "name": "Comp Off"},
                    # leave_without_pay intentionally has no entry here.
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("I want to apply for leave"), writer)

        message = result["response_text"]
        assert "Casual Leave (CL)" in message
        assert "Sick Leave (SL)" in message
        assert "Short Leave" in message
        assert "Comp Off" in message
        assert "Leave Without Pay" in message  # zero-balance, no explicit name — still included

    async def test_ask_leave_type_falls_back_to_generic_wording_if_erp_api_unavailable(
        self, monkeypatch, fake_slots,
    ):
        """If the company's real type list can't be fetched (erp-api down),
        the question must still be askable — falls back to the old generic
        wording rather than erroring out or asking with an empty list."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance_down(token, **kwargs):
            raise hr_graph.erp_client.ErpApiUnavailable("connection refused")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance_down)

        mock_extraction(monkeypatch, {})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("I want to apply for leave"), writer)

        assert "type of leave" in result["response_text"].lower()

    async def test_full_multi_turn_apply_flow(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        applied = {}
        async def _apply(token, leave_type_slug, from_date, to_date, session_type_slug=None, reason=None, **kwargs):
            applied.update(leave_type_slug=leave_type_slug, from_date=from_date, to_date=to_date,
                           session_type_slug=session_type_slug, reason=reason)
            return {"http_status": 200, "body": {"success": True, "data": [{"id": 4821}]}}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _apply)

        # Turn 1: "I want to apply for leave" — nothing extracted yet, asks for leave type.
        mock_extraction(monkeypatch, {})
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("I want to apply for leave"), writer)
        assert "type of leave" in writer.of_type("done")[0]["message"].lower()

        # Turn 2: provides leave type + dates.
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("casual leave on 2026-09-01"), writer)
        assert "full day or half day" in writer.of_type("done")[0]["message"].lower()

        # Turn 3: provides session type — asks for reason next (all other slots filled).
        mock_extraction(monkeypatch, {"session_type_slug": "full_day"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("full day"), writer)
        assert "reason" in writer.of_type("done")[0]["message"].lower()

        # Turn 4: provides reason — all slots filled, moves to confirmation.
        mock_extraction(monkeypatch, {"reason": "doctor's appointment"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("doctor's appointment"), writer)
        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert confirmation[0]["data"]["total_days"] == 1.0
        assert "shall i submit" in writer.of_type("done")[0]["message"].lower()

        # Turn 5: confirms — submits via erp_client.apply_leave.
        mock_extraction(monkeypatch, {"is_affirmative": True})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("yes, submit it"), writer)
        success_events = writer.of_type("leave_success")
        assert len(success_events) == 1
        assert success_events[0]["data"]["application_id"] == 4821
        assert "4821" in result["response_text"]
        assert "Would you like to check its status?" in success_events[0]["data"]["suggestions"]
        assert applied == {
            "leave_type_slug": "casual_leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day", "reason": "doctor's appointment",
        }
        # Slots cleared after successful submission — next turn starts fresh.
        assert fake_slots.get_slots(1, "conv-1") is None

    async def test_multi_day_range_skips_half_day_question_and_computes_full_span(
        self, monkeypatch, fake_slots,
    ):
        """Live bug repro: 'casual leave from 2026-08-24 to 2026-08-28' (5
        days) still asked 'full day or half day?' — a question that only
        makes sense for a single day. Worse, _compute_requested_days applied
        the 0.5-day override purely from session_type_slug, with no regard
        for the actual date span, so answering 'half day' would have
        silently confirmed a 5-day request as 0.5 days. Multi-day ranges
        must skip straight to confirmation with the correct full-span total."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "20", "remaining": "20"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        from datetime import timedelta
        range_from = leave_action_service._today_in_app_timezone() + timedelta(days=7)
        range_to = range_from + timedelta(days=4)  # 5-day span inclusive
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": range_from.isoformat(), "to_date": range_to.isoformat(),
            "reason": "family event",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state(f"apply casual leave from {range_from.isoformat()} to {range_to.isoformat()}"), writer
        )

        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert confirmation[0]["data"]["total_days"] == 5.0
        assert "5.0 day" in result["response_text"]
        assert "full day or half day" not in result["response_text"].lower()

    async def test_multi_day_session_type_required_leave_defaults_to_full_day(
        self, monkeypatch, fake_slots,
    ):
        """Live bug: a multi-day sick_leave request skipped the 'full day or
        half day?' question (correctly, per the test above — half-day makes
        no sense across a range) but then left session_type_slug at None
        all the way to the actual apply_leave() call, which erp-api rejects
        with 'The session type slug field is required when leave type slug
        is sick_leave' — discovered only AFTER the user had already
        confirmed. session_type_slug must default to 'full_day' for a
        multi-day request instead of being left unset."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        from datetime import timedelta
        range_from = leave_action_service._today_in_app_timezone() + timedelta(days=7)
        range_to = range_from + timedelta(days=1)  # 2-day span
        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": range_from.isoformat(), "to_date": range_to.isoformat(),
            "reason": "fever",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state(f"apply sick leave from {range_from.isoformat()} to {range_to.isoformat()}"), writer
        )

        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["session_type_slug"] == "full_day"

    async def test_multi_day_short_leave_rejected_before_confirmation(self, monkeypatch, fake_slots):
        """Live bug: erp-api treats short_leave as an inherently single-unit
        type (its apply()/update() logic force-sets leave_count="1"
        regardless of the date range given, the same way half_day forces
        0.5) and rejects a multi-day short_leave range outright ("The from
        date and to date must be the same for this leave request") — but
        only at actual submission time. A real live repro: a 15-day
        short_leave range ("1 Sept to 15 Sept") sailed all the way through
        confirmation and only failed after the user said "Yes, please
        submit it." Must be caught before confirmation instead."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"short_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)
        apply_mock = MagicMock(side_effect=AssertionError("must never be called"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        mock_extraction(monkeypatch, {
            "leave_type": "short_leave", "from_date": "2026-09-01", "to_date": "2026-09-15",
            "reason": "personal",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("I want to take leave from 1 Sept to 15 Sept short leave"), writer,
        )

        apply_mock.assert_not_called()
        assert writer.of_type("leave_confirmation") == []
        assert "single day" in result["response_text"].lower()
        assert writer.of_type("done")[0]["data"]["requires_date_input"] is True
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None
        assert saved["to_date"] is None
        assert saved["leave_type"] == "short_leave"  # type preserved, only dates cleared

    async def test_single_day_short_leave_proceeds_normally(self, monkeypatch, fake_slots):
        """Contrast case: a single-day short_leave request must NOT be
        caught by the new multi-day guard above."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"short_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {
            "leave_type": "short_leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
            "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("short leave on 1 Sept reason personal"), writer)

        assert len(writer.of_type("leave_confirmation")) == 1
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-09-01"
        assert saved["to_date"] == "2026-09-01"

    async def test_reason_is_asked_for_when_every_other_slot_is_filled(self, monkeypatch, fake_slots):
        """Regression: erp-api's standard (non-AI) leave application flow
        requires a reason; the AI-assist route's own validator marks it
        nullable, so this was never asked for and could reach confirmation
        without one — only to have erp-api reject the actual submission,
        discovered by the user only after they'd already said yes. Reason
        must be collected up front like leave_type/dates/session_type_slug."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        # Both slots are already filled, so leave_action_node's conflict
        # check (_find_conflicting_leave) runs before reaching the reason
        # prompt this test is actually about — must be mocked like every
        # other test that reaches this point, or it falls through to a
        # real, unmocked erp-api call.
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "casual_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day", "reason": None,
        })

        mock_extraction(monkeypatch, {})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("2026-09-01"), writer)

        assert writer.of_type("leave_confirmation") == []
        assert "reason" in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] == "collecting"
        assert saved["leave_type"] == "casual_leave"  # kept

    async def test_reason_supplied_in_same_turn_as_other_slots_skips_the_ask(self, monkeypatch, fake_slots):
        """If the user volunteers a reason in the same message that fills the
        last other slot (e.g. 'full day, doctor's appointment'), extraction
        already captures it — the explicit ask must not fire redundantly."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "casual_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": None, "reason": None,
        })

        mock_extraction(monkeypatch, {"session_type_slug": "full_day", "reason": "doctor's appointment"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("full day, doctor's appointment"), writer)

        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert confirmation[0]["data"]["reason"] == "doctor's appointment"
        assert "shall i submit" in result["response_text"].lower()

    async def test_reason_still_missing_after_one_retry_falls_back_to_raw_text(self, monkeypatch, fake_slots):
        """Live bug repro: extraction correctly refuses to let a leave-type
        mention leak into 'reason' (its own documented rule), but replies
        like 'sick leave' / 'I want to apply for sick leave' just restate
        the type, not an actual reason — so extraction keeps returning null
        and the bot re-asked the SAME question forever with no way out.
        First failed attempt still asks again (extraction might just need a
        clearer answer) — but the SECOND consecutive failure must accept
        the raw reply verbatim rather than loop a third time."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "7", "remaining": "5"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day", "reason": None,
        })

        # First reply: "sick leave" — extraction correctly refuses to treat
        # a leave-type mention as a reason, still asks.
        mock_extraction(monkeypatch, {})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("sick leave"), writer)
        assert "reason" in result["response_text"].lower()
        assert writer.of_type("leave_confirmation") == []
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["reason"] is None
        assert saved["reason_attempts"] == 1

        # Second reply, still not a real reason by extraction's own rule —
        # must now accept it verbatim instead of asking a third time.
        mock_extraction(monkeypatch, {})
        writer2 = FakeWriter()
        result2 = await hr_graph.leave_action_node(base_state("I want to apply for sick leave"), writer2)

        confirmation = writer2.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert confirmation[0]["data"]["reason"] == "I want to apply for sick leave"
        assert "shall i submit" in result2["response_text"].lower()
        saved2 = fake_slots.get_slots(1, "conv-1")
        assert "reason_attempts" not in saved2  # cleaned up once accepted

    async def test_reason_reply_flagged_as_unrecognized_leave_type_is_not_rejected_when_type_already_known(
        self, monkeypatch, fake_slots,
    ):
        """Live bug: with leave_type ALREADY confirmed as sick_leave, a
        garbled reply to the reason prompt ('fever009') got extraction's
        general 'unfamiliar short word' heuristic flagging it as
        unrecognized_leave_type — and the bot rejected with 'We don't have
        a "fever009" leave type here', even though leave type was never in
        question at this point in the conversation. The unrecognized_leave_
        type short-circuit must only apply while leave_type is genuinely
        still being collected, not retroactively once it's already locked
        in — otherwise it should fall through to the normal reason-fallback
        handling (same raw-text-acceptance safety net as the test above)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "7", "remaining": "5"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day", "reason": None,
            "reason_attempts": 1,  # already asked once, matching the reported transcript
        })

        mock_extraction(monkeypatch, {"unrecognized_leave_type": "fever009"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("fever009"), writer)

        assert "don't have" not in result["response_text"].lower()
        assert "fever009" not in result["response_text"].lower() or "reason" in result["response_text"].lower()
        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert confirmation[0]["data"]["reason"] == "fever009"
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["leave_type"] == "sick_leave"  # untouched throughout

    async def test_reason_related_apply_rejection_reprompts_for_reason_not_dates(self, monkeypatch, fake_slots):
        """If erp-api still rejects the submission over the reason field
        despite the proactive ask (e.g. a company-specific rule, or an
        erp-api change), the generic failure handler must not derail into
        asking for new dates — reason was never the problem's dates."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "casual_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day", "reason": "x",
        })

        async def _apply_fails(token, *a, **kw):
            return {"http_status": 400, "body": {"success": False, "message": "The reason field must be at least 3 characters."}}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _apply_fails)

        mock_extraction(monkeypatch, {"is_affirmative": True})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("yes"), writer)

        assert "reason" in result["response_text"].lower()
        assert writer.of_type("leave_success") == []
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] == "collecting"
        assert saved["reason"] is None
        # Dates must be preserved — the rejection was never about them.
        assert saved["from_date"] == "2026-09-01"
        assert saved["to_date"] == "2026-09-01"

    async def test_session_type_related_apply_rejection_reprompts_for_session_type_not_dates(
        self, monkeypatch, fake_slots,
    ):
        """Live bug: erp-api rejects a sick_leave submission with 'The
        session type slug field is required when leave type slug is
        sick_leave' — some leave types require an explicit full/half day
        even on what looked like a plain single-day request. The generic
        failure handler was clearing dates and asking 'What dates would you
        like to try instead?', which is nonsensical here — the dates were
        never the problem, session_type_slug was. Must re-collect the
        session type instead, same treatment as the reason field above."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "sick_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": None, "reason": "fever",
        })

        async def _apply_fails(token, *a, **kw):
            return {"http_status": 400, "body": {
                "success": False,
                "message": "The session type slug field is required when leave type slug is sick_leave.",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _apply_fails)

        mock_extraction(monkeypatch, {"is_affirmative": True})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("yes"), writer)

        assert "full day or half day" in result["response_text"].lower()
        assert writer.of_type("leave_success") == []
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] == "collecting"
        assert saved["session_type_slug"] is None
        # Dates must be preserved — the rejection was never about them.
        assert saved["from_date"] == "2026-09-01"
        assert saved["to_date"] == "2026-09-01"

    async def test_multi_day_range_with_stray_half_day_value_still_computes_full_span(self):
        """Defensive guard on _compute_requested_days directly: even if a
        half-day session_type_slug somehow ends up set on a multi-day range
        (e.g. carried over from an earlier single-day turn before the range
        was widened), the day count must reflect the actual date span, not
        silently collapse to 0.5."""
        slots = {
            "from_date": "2026-08-24", "to_date": "2026-08-28",
            "session_type_slug": "first_half_day",
        }
        assert leave_action_service._compute_requested_days(slots) == 5.0

    @pytest.mark.parametrize("query", [
        "give me another dates options which slot available",
        "give me options of dates",
        "which dates are available",
    ])
    async def test_asking_for_date_suggestions_gets_a_helpful_answer_not_a_repeat(
        self, monkeypatch, fake_slots, query,
    ):
        """Regression: there's no concept of a fixed 'available dates' slot
        list — asking for one previously got the exact same bare 'What dates
        would you like to take off?' prompt as any other unrecognized reply,
        which reads as the bot ignoring the question rather than answering
        it."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave", "from_date": None,
            "to_date": None, "session_type_slug": None, "reason": None,
        })

        mock_extraction(monkeypatch, {})  # no date recognized, as expected
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state(query), writer)

        message = result["response_text"].lower()
        assert "what dates would you like to take off?" not in message
        assert "available" in message or "date or date range" in message

    @pytest.mark.parametrize("query", [
        "what is my limit",
        "what's my limit",
        "how many can i apply",
        # Found via live multi-turn probing: "limit" rephrased as "maximum"/
        # "max" wasn't covered by any of the above and fell through to the
        # bare date prompt instead of answering.
        "what's the maximum days I can take at once",
        "what is the max days allowed",
    ])
    async def test_asking_about_limit_after_rejection_gets_the_real_figure(
        self, monkeypatch, fake_slots, query,
    ):
        """Regression: after erp-api rejects a submission with a limit-related
        message ('Monthly sick leave limit reached'), asking 'what is my
        limit' is a completely natural follow-up — it must be answered with
        the real per-type limit from erp-api's leave_settings, not the bare
        'What dates would you like to take off?' prompt."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave", "from_date": None,
            "to_date": None, "session_type_slug": None, "reason": None,
        })

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "7", "remaining": "4.7"}},
                "leave_settings": {"leave_type": [
                    {"name": "Sick Leave", "slug": "sick_leave", "quota": "7",
                     "max_apply_in_month": "3", "oneTypeMax": "2"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {})  # no date recognized, as expected
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state(query), writer)

        message = result["response_text"]
        assert "what dates would you like to take off?" not in message.lower()
        assert "3 request(s) per month" in message
        assert "Sick Leave" in message

    async def test_limit_question_when_erp_api_unavailable_falls_back_gracefully(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave", "from_date": None,
            "to_date": None, "session_type_slug": None, "reason": None,
        })

        async def _balance_down(token, **kwargs):
            raise hr_graph.erp_client.ErpApiUnavailable("connection refused")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance_down)

        mock_extraction(monkeypatch, {})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("what is my limit"), writer)

        # Must not crash, and must not silently repeat the generic prompt either.
        assert "couldn't fetch" in result["response_text"].lower()

    async def test_back_dated_leave_rejected_immediately_when_company_disallows_it(
        self, monkeypatch, fake_slots,
    ):
        """Live bug repro: 'i want to apply leave for yesterday' asked 'what
        type of leave?' first, even for a company with
        leave_settings.back_date_leave_allow == "0" — the date alone was
        already enough to know the request could never succeed. Must reject
        immediately, before ever asking about type/session/reason, and
        without needing leave_type known at all."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {}, "leave_settings": {"back_date_leave_allow": "0"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        status_mock = MagicMock(side_effect=AssertionError("conflict check must not run — back-date check blocks first"))
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", status_mock)
        apply_mock = MagicMock(side_effect=AssertionError("must never be called"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        mock_extraction(monkeypatch, {"from_date": "2026-08-19", "to_date": "2026-08-19"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("i want to apply leave for yesterday"), writer)

        apply_mock.assert_not_called()
        status_mock.assert_not_called()
        message = result["response_text"].lower()
        assert "past date" in message
        assert "type of leave" not in message
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None  # cleared so the next reply is read as a new date
        assert saved["leave_type"] is None  # never even asked for it

    async def test_back_dated_leave_allowed_when_company_setting_permits_it(self, monkeypatch, fake_slots):
        """Confirmed live: back_date_leave_allow is a genuine per-company
        toggle, not a universal rule — some companies set it to "1". Must
        NOT block in that case, proceeding to the normal conflict/slot flow."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {"leave_type": "casual_leave", "from_date": "2026-08-19", "to_date": "2026-08-19"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("apply casual leave for yesterday"), writer)

        assert "past date" not in result["response_text"].lower()

    async def test_future_dated_leave_never_triggers_back_date_check(self, monkeypatch, fake_slots):
        """The check must only ever fire for a genuinely past from_date —
        confirmed by NOT mocking get_leave_balance's back_date_leave_allow
        path at all here and instead asserting the flow proceeds to ask for
        session type normally for a clearly future date."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {}, "leave_settings": {"back_date_leave_allow": "0"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {"leave_type": "casual_leave", "from_date": "2027-06-01", "to_date": "2027-06-01"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("apply casual leave for 2027-06-01"), writer)

        assert "past date" not in result["response_text"].lower()

    async def test_conflict_check_runs_immediately_after_dates_not_after_session_and_reason(
        self, monkeypatch, fake_slots,
    ):
        """Live UX complaint: the conflict check used to run only after EVERY
        other slot (session type, reason) was also collected, so a duplicate
        date only surfaced after the user had already answered 'full day or
        half day?' and 'what's the reason?' — two wasted turns on a request
        that was never going to succeed. It only needs from_date/to_date, so
        it must fire as soon as those are known — here leave_type + dates
        are the ONLY slots filled (session_type_slug and reason are still
        None) and the conflict message must come back immediately, not the
        session-type question."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 50, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": "2026-08-18", "to_date": "2026-08-18", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        apply_mock = MagicMock(side_effect=AssertionError("must never be called — conflict should block first"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        # get_leave_balance is legitimately called once up front now — to
        # fetch this company's real configured leave types before extraction
        # runs (see _fetch_known_leave_types) — that's unrelated to the
        # invariant this test actually guards: the SEPARATE balance
        # *validation* call the flow makes later, right before showing a
        # confirmation, must never happen if the conflict check blocks first.
        balance_calls = {"count": 0}
        async def _balance(token, **kwargs):
            balance_calls["count"] += 1
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "7", "remaining": "5"}},
                "leave_settings": {
                    "leave_type": [{"slug": "sick_leave", "name": "Sick Leave"}],
                    "back_date_leave_allow": "1",
                },
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-18", "to_date": "2026-08-18",
        })
        writer = FakeWriter()
        # An explicit literal date, not "today" — this test is about
        # conflict-check ordering, not date resolution (see
        # test_date_resolver.py / TestDeterministicDateOverride for that);
        # using "today" here would now correctly trigger the deterministic
        # override and resolve to the real current date, not this test's
        # fixed 2026-08-18 mock.
        result = await hr_graph.leave_action_node(base_state("apply sick leave for 2026-08-18"), writer)

        apply_mock.assert_not_called()
        # Type-fetch + the back-date-allowed check both legitimately read
        # get_leave_balance before the conflict check runs — never the
        # later balance *validation* call, which would make this 3.
        assert balance_calls["count"] <= 2
        message = result["response_text"].lower()
        assert "already applied" in message
        assert "full day or half day" not in message
        assert "reason" not in message
        assert writer.of_type("leave_confirmation") == []

    async def test_conflict_check_runs_even_before_leave_type_is_known(self, monkeypatch, fake_slots):
        """Live UX complaint, one step further than the test above: 'I want
        to apply leave for today' gives a date but no leave type — the old
        code asked 'what type of leave?' FIRST since that's checked before
        dates, so the date conflict (which doesn't depend on type at all —
        erp-api's apply() rejects an overlapping date regardless of leave
        TYPE) only surfaced after the user answered that question too. The
        conflict must be caught the moment the date is known, whether or not
        leave_type has been given yet."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 51, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": "2026-08-18", "to_date": "2026-08-18", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {}, "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        apply_mock = MagicMock(side_effect=AssertionError("must never be called — conflict should block first"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        # Only a date is extracted — leave_type stays None, exactly like
        # "I want to apply leave for a given date" with no type mentioned.
        # An explicit literal date, not "today" — this test is about
        # conflict-check ordering, not date resolution; using "today" would
        # now correctly trigger the deterministic override and resolve to
        # the real current date, not this test's fixed 2026-08-18 mock.
        mock_extraction(monkeypatch, {"from_date": "2026-08-18", "to_date": "2026-08-18"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("I want to apply leave for 2026-08-18"), writer)

        apply_mock.assert_not_called()
        message = result["response_text"].lower()
        assert "already applied" in message
        assert "type of leave" not in message
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["leave_type"] is None  # never even asked for it

    async def test_proactive_duplicate_date_check_emits_a_leave_failure_card(
        self, monkeypatch, fake_slots,
    ):
        """Live UX request (2026-08-24): this proactive pre-submission
        conflict check used to return a bare chat message with no
        leave_failure card at all — unlike the balance pre-check right next
        to it in the code, which already went through leave_failure.
        build_card(). Must emit the same card shape (title, reason_code,
        badge, is_failure) as every other apply/cancel failure."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 51, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": "2026-08-18", "to_date": "2026-08-18", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)
        # The query says "today" — the deterministic tier-1 override always
        # resolves that word against the REAL current date, regardless of
        # what the (mocked) extraction guessed; anchor it here so it
        # resolves to the same 2026-08-18 the mocked conflicting leave and
        # extraction both use, independent of the real wall clock.
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 18))

        mock_extraction(monkeypatch, {"from_date": "2026-08-18", "to_date": "2026-08-18"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("I want to apply leave for today"), writer)

        failure_events = writer.of_type("leave_failure")
        assert len(failure_events) == 1
        card = failure_events[0]["data"]
        assert card["is_failure"] is True
        assert card["failure"]["title"] == "Leave Request Not Completed"
        assert card["failure"]["reason_code"] == ["DUPLICATE_APPLICATION"]
        assert card["failure"]["badge"] == ["duplicate_request"]
        assert card["failure"]["badge_label"] == ["Duplicate Request"]
        assert card["failure"]["sub_title"] == "Requested date is a duplicate"
        assert "already applied" in card["failure"]["display_message"][0].lower()
        done_data = writer.of_type("done")[0]["data"]
        assert done_data["is_failure"] is True

    async def test_duplicate_conflict_message_uses_the_shared_date_format(
        self, monkeypatch, fake_slots,
    ):
        """The conflict message previously showed the raw ISO pair
        ('2030-06-04 to 2030-06-04') instead of this file's shared design
        date format. A single-day conflict collapses to one formatted date;
        a genuine two-day conflict still shows both ends as a range."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status_single_day(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 51, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": "2030-06-04", "to_date": "2030-06-04", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status_single_day)

        mock_extraction(monkeypatch, {"from_date": "2030-06-04", "to_date": "2030-06-04"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("apply leave for 2030-06-04"), writer)

        message = writer.of_type("leave_failure")[0]["data"]["failure"]["display_message"][0]
        assert message == "You've already applied for Sick Leave on Tue, 04 Jun 2030 (pending)."
        assert "2030-06-04 to 2030-06-04" not in message

    async def test_duplicate_conflict_message_shows_a_real_range_for_two_dates(
        self, monkeypatch, fake_slots,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status_range(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 52, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": "2030-06-04", "to_date": "2030-06-05", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status_range)

        mock_extraction(monkeypatch, {"from_date": "2030-06-04", "to_date": "2030-06-05"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("apply leave for 2030-06-04 to 2030-06-05"), writer)

        message = writer.of_type("leave_failure")[0]["data"]["failure"]["display_message"][0]
        assert message == "You've already applied for Sick Leave on Tue, 04 Jun - Wed, 05 Jun 2030 (pending)."

    async def test_proactive_holiday_check_emits_a_leave_failure_card(
        self, monkeypatch, fake_slots,
    ):
        """Live bug report (2026-08-24): the holiday-blocked check used to
        live ONLY inside _collect_additional_failures, which runs 'ONLY
        after erp-api has already refused' — so a fully-holiday request
        that erp-api's own apply() doesn't itself reject went through
        uncaught. Must be caught proactively, before ever calling apply(),
        same as the duplicate-date and balance pre-checks."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _holidays(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "year": 2026, "holidays": [
                    {"holiday_date": "2026-12-20", "holiday_name": "Quarter-End Freeze"},
                ],
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_holidays", _holidays, raising=False)

        apply_mock = MagicMock(side_effect=AssertionError("must never be called — holiday should block first"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        # A future date (today in these tests is 2026-08-24) — a PAST date
        # here would collide with _roll_apply_dates_forward_if_past, which
        # is correct behavior for a real bare month/day mention but not what
        # this test is exercising.
        mock_extraction(monkeypatch, {"from_date": "2026-12-20", "to_date": "2026-12-20"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("apply leave for 20 dec", "apply_leave"), writer)

        apply_mock.assert_not_called()
        failure_events = writer.of_type("leave_failure")
        assert len(failure_events) == 1
        card = failure_events[0]["data"]
        assert card["is_failure"] is True
        assert card["failure"]["title"] == "Leave Request Not Completed"
        assert card["failure"]["reason_code"] == ["BLOCKED_DATE"]
        assert card["failure"]["badge"] == ["blocked_date"]
        assert card["failure"]["sub_title"] == "Requested date is blocked"
        assert "company holiday" in card["failure"]["display_message"][0].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None  # cleared so the next reply is read as a new date

    async def test_insufficient_balance_gets_a_dynamic_sub_title(
        self, monkeypatch, fake_slots,
    ):
        """Confirmed mockup example: 'Not enough Sick Leave balance' names
        the specific leave type — a plain reason_code lookup can't produce
        that on its own, so the card's sub_title is built dynamically by
        the caller instead (LeaveFailure.heading override)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "3", "remaining": "3"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        apply_mock = MagicMock(side_effect=AssertionError("must never be called — balance should block first"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-20", "to_date": "2026-08-24",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("apply sick leave from 20 to 24 aug, personal"), writer)

        apply_mock.assert_not_called()
        card = writer.of_type("leave_failure")[0]["data"]
        assert card["failure"]["reason_code"] == ["INSUFFICIENT_BALANCE"]
        assert card["failure"]["badge"] == ["balance"]
        assert card["failure"]["sub_title"] == "Not enough Sick Leave balance"

    async def test_insufficient_balance_message_and_chips_match_ha163_scenario_a(
        self, monkeypatch, fake_slots,
    ):
        """HA-163 Sprint 2 spec, Scenario A verbatim: 'You have 3 days of
        Sick Leave (SL) available, but this request needs 4 days. Reduce the
        duration or use another type.' plus two chips — Check Available
        Balance and Apply for the actual remaining balance (not a fixed
        suggestion). Also verifies the done-event carries this card, which
        the balance pre-check previously omitted (extra_data was never
        passed to _finish)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "12", "remaining": "3"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-10", "to_date": "2026-08-13",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("apply for 4 days of sick leave from 10 aug"), writer)

        card = writer.of_type("leave_failure")[0]["data"]
        assert card["failure"]["display_message"] == [
            "You have 3 days of Sick Leave (SL) available, but this request needs "
            "4 days. Reduce the duration or use another type."
        ]
        assert card["failure"]["next_actions"] == [
            {"label": "Check Available Balance", "action": "check_leave_balance"},
            {"label": "Apply for 3 Days", "action": "apply_reduced_days"},
        ]
        done = writer.of_type("done")[0]["data"]
        assert done["failure"] == card["failure"]

    async def test_insufficient_balance_check_runs_before_the_reason_question(
        self, monkeypatch, fake_slots,
    ):
        """Live bug report (2026-08-26): 'i want to aplyt sick leave or 15
        day' — leave_type and dates known, reason not yet given — used to
        ask "What's the reason for this leave request?" first, even though
        the request (15 days against a 3-day balance) was always going to be
        rejected. Balance now runs the moment leave_type + dates are known,
        the same reasoning that moved the holiday/conflict checks earlier on
        2026-08-24 — asking a question that can't change the outcome is a
        wasted round-trip erp-api's own apply() never even needs to see."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "12", "remaining": "3"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        # Anchor "today" on/before the requested range — this test is about
        # balance-check ordering, not date resolution; the bare "15 day"
        # phrasing names no month/year the roll-forward or explicit-date
        # recognition could anchor to, so an unfrozen real wall clock moving
        # past 10 Aug 2026 would otherwise trip the (unrelated) past-date
        # safety net first.
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 1))

        apply_mock = MagicMock(side_effect=AssertionError("must never be called — balance should block first"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        # reason is deliberately absent — the exact live repro.
        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-10", "to_date": "2026-08-24",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("i want to aplyt sick leave or 15 day"), writer)

        apply_mock.assert_not_called()
        assert "what's the reason" not in result["response_text"].lower()
        card = writer.of_type("leave_failure")[0]["data"]
        assert card["failure"]["reason_code"] == ["INSUFFICIENT_BALANCE"]
        assert card["failure"]["display_message"] == [
            "You have 3 days of Sick Leave (SL) available, but this request needs "
            "15 days. Reduce the duration or use another type."
        ]

    async def test_insufficient_balance_with_zero_remaining_suggests_another_type(
        self, monkeypatch, fake_slots,
    ):
        """A zero balance can't offer "Apply for 0 Days" — that chip is
        replaced with a different, still-actionable suggestion."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"comp_off": {"total": "0", "remaining": "0"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {
            "leave_type": "comp_off", "from_date": "2026-08-10", "to_date": "2026-08-10",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("apply comp off for 10 aug"), writer)

        card = writer.of_type("leave_failure")[0]["data"]
        assert card["failure"]["next_actions"] == [
            {"label": "Check Available Balance", "action": "check_leave_balance"},
            {"label": "Use Another Leave Type", "action": "change_leave_type"},
        ]

    async def test_blocked_date_message_expands_to_the_full_named_range(
        self, monkeypatch, fake_slots,
    ):
        """HA-163 Sprint 2 spec, Scenario B verbatim wording: a single-day
        request (15 Aug) falling inside a multi-day named freeze the holiday
        calendar lists one entry per day for (10-18 Aug) is described by its
        FULL range, not just the one requested day — derived entirely from
        the real calendar data, not fabricated (see _named_holiday_span)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _holidays(token, **kwargs):
            days = [f"2026-08-{d:02d}" for d in range(10, 19)]  # 10..18 Aug inclusive
            return {"http_status": 200, "body": {"success": True, "data": {
                "year": 2026, "holidays": [
                    {"holiday_date": d, "holiday_name": "Quarter-End Freeze"} for d in days
                ],
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_holidays", _holidays, raising=False)
        # Anchor "today" on/before the requested date — this test is about
        # holiday-blocking, not back-dating; without this, the (unrelated,
        # default-disallowed) back-date check would intercept the request
        # first as the real wall clock moves past 15 Aug 2026.
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 1))

        apply_mock = MagicMock(side_effect=AssertionError("must never be called — holiday should block first"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        mock_extraction(monkeypatch, {"from_date": "2026-08-15", "to_date": "2026-08-15"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply casual leave for 15 aug 2026", "apply_leave"), writer)

        apply_mock.assert_not_called()
        card = writer.of_type("leave_failure")[0]["data"]
        assert card["failure"]["display_message"] == [
            "15 Aug 2026 falls in a company blackout period (Quarter-End Freeze, "
            "10 Aug - 18 Aug 2026). Leave cannot be applied for blocked dates."
        ]
        assert card["failure"]["next_actions"] == [
            {"label": "Select Another Date", "action": "select_another_date"}]

    async def test_blocked_date_message_stays_single_day_when_calendar_has_no_range(
        self, monkeypatch, fake_slots,
    ):
        """An isolated single-day holiday must NOT be widened into a range
        it isn't part of — only real, contiguous same-named calendar entries
        justify the range wording."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _holidays(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "year": 2026, "holidays": [
                    {"holiday_date": "2026-07-14", "holiday_name": "Good Wednesday"},
                ],
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_holidays", _holidays, raising=False)
        # See the sibling test above — anchor "today" on/before the
        # requested date so the unrelated back-date-disallowed check can't
        # intercept this holiday-blocking scenario as the real wall clock
        # moves forward.
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 7, 1))

        apply_mock = MagicMock(side_effect=AssertionError("must never be called — holiday should block first"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        mock_extraction(monkeypatch, {"from_date": "2026-07-14", "to_date": "2026-07-14"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply casual leave for 14 july 2026", "apply_leave"), writer)

        apply_mock.assert_not_called()
        card = writer.of_type("leave_failure")[0]["data"]
        assert card["failure"]["display_message"] == [
            "14 Jul 2026 is a company holiday (Good Wednesday). "
            "Leave cannot be applied for blocked dates."
        ]

    async def test_erp_rejection_chips_vary_by_which_slot_was_invalidated(
        self, monkeypatch, fake_slots,
    ):
        """The chip echoes whichever slot the next_action text already
        targets — a date-shaped rejection offers Select Another Date, a
        fallback offers Contact HR Help Desk, never the wrong chip for the
        branch actually taken."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "casual_leave",
            "from_date": "2026-08-20", "to_date": "2026-08-20",
            "session_type_slug": "full_day", "reason": "personal",
        })

        async def _opaque(token, *a, **kw):
            return {"http_status": 400, "body": {"success": False, "message": "ERR_5521"}}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _opaque)
        mock_extraction(monkeypatch, {"is_affirmative": True})

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("yes"), writer)

        card = writer.of_type("leave_failure")[0]["data"]
        assert card["failure"]["is_fallback"] is True
        assert card["failure"]["next_actions"] == [
            {"label": "Contact HR Help Desk", "action": "contact_hr"}]

    async def test_is_failure_defaults_false_on_an_ordinary_apply_response(
        self, monkeypatch, fake_slots,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        mock_extraction(monkeypatch, {"from_date": "2026-08-18", "to_date": "2026-08-18"})

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("apply leave for 18 aug"), writer)

        assert writer.of_type("done")[0]["data"]["is_failure"] is False

    async def test_bare_month_mention_gets_an_explicit_year_hint_in_the_prompt(
        self, monkeypatch, fake_slots,
    ):
        """Fixes the root cause at the source rather than only patching the
        LLM's output afterward: a bare month/day mention with no year gets
        the correct year appended to the TEXT sent for extraction, so the
        model sees the exact same kind of unambiguous input as the
        '...15th november 2026' case that already worked reliably. The year
        itself is computed dynamically from date.today() each call, never
        hardcoded."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        captured_prompts = []

        async def _capture_call_llm(prompt, max_tokens=None, model=None):
            captured_prompts.append(prompt)
            return {"__extracted__": {}}

        def _fake_extract_text(response):
            return json.dumps(response.get("__extracted__", {}))

        monkeypatch.setattr(leave_action_service, "_call_llm", _capture_call_llm)
        monkeypatch.setattr(leave_action_service, "_extract_text", _fake_extract_text)

        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply for leave for 15th november", "apply_leave"), writer,
        )

        assert len(captured_prompts) == 1
        # "today" in these tests is 2026-08-24 — 15th November hasn't
        # happened yet this year, so the current year is the correct hint.
        assert "15th november 2026" in captured_prompts[0].lower()

    async def test_bare_month_mention_rolls_forward_past_the_year_the_llm_got_wrong(
        self, monkeypatch, fake_slots,
    ):
        """Live bug report (2026-08-24): 'apply for leave for 15th november'
        (no year given) got extracted by the LLM as a PAST date and rejected
        as such, while '...15th november 2026' worked fine. Simulates the
        exact failure mode — the LLM defaulting to the wrong (past) year —
        and confirms the correction rolls it forward to a real future date
        before it ever reaches erp-api, rather than trusting the LLM's year.
        (Belt-and-suspenders: this covers the case where the prompt's own
        year hint, tested above, somehow still isn't followed.)"""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        # Simulates the LLM's own reported bug: no year in the query, but it
        # resolved "15th november" to a year already in the past relative to
        # "today" (2026-08-24 in these tests).
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2025-11-15", "to_date": "2025-11-15",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("apply for leave for 15th november", "apply_leave"), writer,
        )

        assert "shall i submit" in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-11-15"
        assert saved["to_date"] == "2026-11-15"

    async def test_explicit_year_is_never_overridden_even_if_it_reads_as_past(
        self, monkeypatch, fake_slots,
    ):
        """The correction only ever fires for an AMBIGUOUS no-year mention —
        an employee who typed a specific year gets exactly that year back,
        never silently shifted."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        # This test's whole point is a genuinely, deliberately past date
        # (2025, from an explicit year) — back_date_leave_allow must be
        # explicitly permissive here, or the (unrelated) back-date-
        # disallowed check would clear from_date before this test ever gets
        # to observe whether the year itself was preserved.
        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2025-11-15", "to_date": "2025-11-15",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply for leave for 15th november 2025", "apply_leave"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2025-11-15"
        assert saved["to_date"] == "2025-11-15"

    async def test_conflicting_date_blocks_before_confirmation_not_after(self, monkeypatch, fake_slots):
        """Live bug repro: requesting Sick Leave for 2026-08-14 when Earned
        Leave was already applied for that same date used to sail straight
        past the confirmation card ('To confirm: 1.0 day(s) of sick leave
        ... Shall I submit this request?') and only fail AFTER the user said
        yes — erp-api's own apply() rejects overlapping dates regardless of
        leave TYPE. The conflict must be caught before showing a
        confirmation at all, not after."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "7", "remaining": "5"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 40, "leave_type": "Earned Leave", "leave_type_slug": "earned_leave",
                 "from_date": "2026-08-14", "to_date": "2026-08-14", "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        apply_mock = MagicMock(side_effect=AssertionError("must never be called — conflict should block first"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-14", "to_date": "2026-08-14",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        # An explicit literal date, not "today" — this test is about
        # conflict-check ordering, not date resolution; using "today" would
        # now correctly trigger the deterministic override and resolve to
        # the real current date, not this test's fixed 2026-08-14 mock.
        result = await hr_graph.leave_action_node(base_state("2026-08-14"), writer)

        apply_mock.assert_not_called()
        assert writer.of_type("leave_confirmation") == []  # never shown — blocked before that point
        assert "already applied" in result["response_text"].lower()
        assert "Earned Leave" in result["response_text"]
        # Same-date design format, matching every other date-bearing message
        # in this file — not the raw ISO pair.
        assert "Fri, 14 Aug 2026" in result["response_text"]
        # Dates cleared so the very next reply is treated as a new date, not
        # another attempt at the same rejected one.
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None
        assert saved["to_date"] is None
        assert saved["leave_type"] == "sick_leave"  # kept
        assert writer.of_type("done")[0]["data"]["requires_date_input"] is True

    async def test_conflict_check_ignores_rejected_and_cancelled_leaves(self, monkeypatch, fake_slots):
        """A rejected or cancelled leave on the same date isn't a real
        conflict — only pending/approved requests actually occupy the date."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "7", "remaining": "5"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 41, "leave_type": "Casual Leave", "leave_type_slug": "casual_leave",
                 "from_date": "2026-08-14", "to_date": "2026-08-14", "status_name": "rejected"},
                {"id": 42, "leave_type": "Comp Off", "leave_type_slug": "comp_off",
                 "from_date": "2026-08-14", "to_date": "2026-08-14", "status_name": "cancelled"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-14", "to_date": "2026-08-14",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("today"), writer)

        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert "shall i submit" in result["response_text"].lower()

    async def test_conflict_check_scopes_query_by_date_to_avoid_pagination_gap(self, monkeypatch, fake_slots):
        """Live bug repro: erp-api's leave/status endpoint (unfiltered) is
        capped to the 20 most recently CREATED rows — unrelated to the
        leave's actual date. On an account with enough history, an older
        pending leave for today's date fell off that window, the conflict
        check saw an empty/irrelevant list, confirmation was shown, and the
        user only found out it was a duplicate AFTER saying yes. Fixed by
        passing applied_leave_date so erp-api filters server-side instead of
        relying on the recency window. This test's fake only returns the
        conflicting leave when asked for the matching date — exactly
        modeling the pagination gap an unscoped query would fall into."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "7", "remaining": "5"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        apply_mock = MagicMock(side_effect=AssertionError("must never be called — conflict should block first"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        async def _status(token, applied_leave_date=None, **kwargs):
            if applied_leave_date != "2026-08-18":
                # Simulates the unscoped/wrong-date call seeing nothing —
                # the old, unfiltered query's exact failure mode.
                return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 99, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": "2026-08-18", "to_date": "2026-08-18", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-18", "to_date": "2026-08-18",
            "session_type_slug": "full_day", "reason": "not feeling well",
        })
        writer = FakeWriter()
        # An explicit literal date, not "today" — this test is about the
        # applied_leave_date scoping, not date resolution; using "today"
        # would now correctly trigger the deterministic override and
        # resolve to the real current date, not this test's fixed
        # 2026-08-18 mock.
        result = await hr_graph.leave_action_node(base_state("2026-08-18"), writer)

        apply_mock.assert_not_called()
        assert writer.of_type("leave_confirmation") == []
        assert "already applied" in result["response_text"].lower()

    async def test_conflict_check_erp_api_unavailable_falls_back_to_confirmation(self, monkeypatch, fake_slots):
        """Advisory, like the balance check beside it — if the conflict check
        itself can't reach erp-api, don't block the whole flow on that
        uncertainty; erp-api's own apply() call remains the authoritative
        gate at actual submission time."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "7", "remaining": "5"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _status_down(token, **kwargs):
            raise hr_graph.erp_client.ErpApiUnavailable("connection refused")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status_down)

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-14", "to_date": "2026-08-14",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("today"), writer)

        assert len(writer.of_type("leave_confirmation")) == 1
        assert "shall i submit" in result["response_text"].lower()

    async def test_partial_insufficient_balance_clears_dates_so_retry_doesnt_loop_forever(
        self, monkeypatch, fake_slots,
    ):
        """Live bug repro: after 'You only have N day(s)... What dates would
        you like to try instead?', a reply that ISN'T actually a new date
        ('personal reasons', 'fever' — anything, since extraction correctly
        finds no date in them) used to leave from_date/to_date untouched, so
        the exact same insufficient-balance combination got silently
        re-validated and the identical rejection repeated forever with no
        way out. Dates must be cleared on this rejection (same as the
        conflict-check and back-date-check rejections beside it), so the
        very next turn falls through to the normal 'what dates would you
        like to take off?' ask instead of looping. Uses a POSITIVE-but-
        insufficient balance (4 remaining, 5 needed) — a shorter date range
        genuinely could fix this, unlike the zero-balance case below."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _low_balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "4"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _low_balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        # Turn 1: a 5-day request against 4 remaining days.
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2027-10-01", "to_date": "2027-10-05",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("casual leave 2027-10-01 to 2027-10-05"), writer)
        # HA-163 Sprint 2 Scenario A wording (see _insufficient_balance_
        # message) — "you have 4 days... but this request needs 5 days".
        assert "you have 4 days" in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None
        assert saved["to_date"] is None
        assert saved["leave_type"] == "casual_leave"  # kept — the type itself is still fine
        assert saved["step"] == "collecting"

        # Turn 2: an unrelated reply that mentions no date at all ("fever") —
        # must fall through to asking for dates, NOT repeat the same
        # insufficient-balance message a second time.
        mock_extraction(monkeypatch, {})
        writer2 = FakeWriter()
        result2 = await hr_graph.leave_action_node(base_state("fever"), writer2)
        assert "you have 4 days" not in result2["response_text"].lower()
        assert "what dates" in result2["response_text"].lower()

    async def test_zero_balance_denies_clearly_and_suggests_alternate_types(
        self, monkeypatch, fake_slots,
    ):
        """Live UX complaint: a type with ZERO balance (this account's real
        leave_without_pay, total=0) got the same 'what dates would you like
        to try instead?' as a partial shortfall — misleading, since no date
        could ever fix a zero-total type. Must clearly say there's no
        balance for THIS type and suggest other types that actually have
        balance right now, sourced from the same already-fetched
        leave_quota/leave_settings (no extra erp-api call)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {
                    "leave_without_pay": {"total": "0", "remaining": "0"},
                    "casual_leave": {"total": "7", "remaining": "5"},
                    "sick_leave": {"total": "7", "remaining": "0"},  # also zero — must NOT be suggested
                },
                "leave_settings": {"leave_type": [
                    {"slug": "leave_without_pay", "name": "Leave Without Pay"},
                    {"slug": "casual_leave", "name": "Casual Leave"},
                    {"slug": "sick_leave", "name": "Sick Leave"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)
        apply_mock = MagicMock(side_effect=AssertionError("must never be called"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)

        mock_extraction(monkeypatch, {
            "leave_type": "leave_without_pay", "from_date": "2027-10-01", "to_date": "2027-10-01",
            "reason": "personal reasons",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("apply leave without pay for 2027-10-01"), writer)

        apply_mock.assert_not_called()
        message = result["response_text"]
        assert "no Leave Without Pay balance" in message
        assert "Casual Leave" in message  # has real balance — suggested
        assert "Sick Leave" not in message  # also zero — must not be suggested
        assert "what dates" not in message.lower()  # would be misleading — a date can't fix this
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["leave_type"] is None  # cleared — the type itself was the problem
        assert saved["from_date"] is None
        assert saved["step"] == "collecting"
        # No date would fix this — it's a leave-TYPE redirect, not a date
        # question, so the frontend must not be told to show a calendar.
        assert "requires_date_input" not in writer.of_type("done")[0]["data"]

    async def test_zero_balance_rejection_then_new_leave_type_proceeds_correctly(
        self, monkeypatch, fake_slots,
    ):
        """Multi-turn lock-in for the zero-balance redirect above: user
        flagged this exact response as a possible follow-up-flow bug
        ('it should not return after the enter date'). A static trace found
        no functional bug — the leave_type-missing check already runs
        before the dates-missing check, and both back-date/conflict checks
        are gated on date-presence alone, so a reply naming a NEW type with
        real balance and no date yet should correctly ask for dates next,
        not repeat the zero-balance message or misorder the checks. This
        was previously untested — closes that gap."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {
                    "leave_without_pay": {"total": "0", "remaining": "0"},
                    "casual_leave": {"total": "7", "remaining": "5"},
                },
                "leave_settings": {"leave_type": [
                    {"slug": "leave_without_pay", "name": "Leave Without Pay"},
                    {"slug": "casual_leave", "name": "Casual Leave"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        # Turn 1: zero-balance type -> rejected, leave_type + from_date cleared.
        mock_extraction(monkeypatch, {
            "leave_type": "leave_without_pay", "from_date": "2027-10-01", "to_date": "2027-10-01",
            "reason": "personal reasons",
        })
        writer1 = FakeWriter()
        result1 = await hr_graph.leave_action_node(base_state("apply leave without pay for 2027-10-01"), writer1)
        assert "no Leave Without Pay balance" in result1["response_text"]
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["leave_type"] is None
        assert saved["from_date"] is None

        # Turn 2: user names a type that DOES have balance, no date given
        # yet. Must ask for dates next — NOT repeat the zero-balance
        # message, and NOT skip straight past the (now again missing)
        # leave_type check.
        mock_extraction(monkeypatch, {"leave_type": "casual_leave"})
        writer2 = FakeWriter()
        result2 = await hr_graph.leave_action_node(base_state("casual leave instead"), writer2)
        assert "no Leave Without Pay balance" not in result2["response_text"]
        assert "what dates" in result2["response_text"].lower()
        assert writer2.of_type("done")[0]["data"]["requires_date_input"] is True
        saved2 = fake_slots.get_slots(1, "conv-1")
        assert saved2["leave_type"] == "casual_leave"
        assert saved2["from_date"] is None

    async def test_bare_ask_for_dates_signals_requires_date_input(self, monkeypatch, fake_slots):
        """The plain 'What dates would you like to take off?' prompt (no
        date known yet at all, no special suggestions/limit phrasing) must
        carry the frontend calendar-picker signal too."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "casual_leave", "from_date": None,
            "to_date": None, "session_type_slug": None, "reason": None,
        })
        mock_extraction(monkeypatch, {})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("i'd like to apply for leave"), writer)

        assert "what dates" in result["response_text"].lower()
        assert writer.of_type("done")[0]["data"]["requires_date_input"] is True

    async def test_insufficient_balance_blocks_and_preserves_slots(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _low_balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "4"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _low_balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2027-10-01", "to_date": "2027-10-05",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("casual leave full day 2027-10-01 to 2027-10-05"), writer)

        # HA-163 Sprint 2 Scenario A wording (see _insufficient_balance_message).
        assert "you have 4 days" in result["response_text"].lower()
        assert writer.of_type("leave_confirmation") == []
        # Slots preserved so the user can revise dates instead of restarting.
        assert fake_slots.get_slots(1, "conv-1") is not None

    async def test_apply_failure_from_erp_api_surfaces_its_message(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "casual_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day", "reason": None,
        })

        async def _apply_fails(token, *a, **kw):
            return {"http_status": 400, "body": {"success": False, "message": "Attendance is locked for date 2026-09-01"}}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _apply_fails)

        mock_extraction(monkeypatch, {"is_affirmative": True})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("yes"), writer)

        assert "Attendance is locked" in result["response_text"]
        assert writer.of_type("leave_success") == []
        # Regression: step must reset to "collecting" and the rejected dates
        # must clear, or the very next "yes"/"try again" reply re-enters the
        # confirmation branch and resubmits the identical (still-failing)
        # request — see test_apply_failure_reply_does_not_loop_forever below
        # for a live repro of that exact infinite loop.
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] == "collecting"
        assert saved["from_date"] is None
        assert saved["to_date"] is None
        assert saved["leave_type"] == "casual_leave"  # kept — rarely the actual cause

    @pytest.mark.parametrize("query", [
        "no, cancel this",
        "actually never mind",
        "forget it",
        "don't submit it",
    ])
    async def test_declining_at_confirmation_actually_cancels_the_draft(
        self, monkeypatch, fake_slots, query,
    ):
        """Live bug repro: declining a confirmation ('no, cancel this') was
        never actually possible. is_affirmative correctly came back False,
        which fell into the 'treat as a revision' branch — but with every
        slot already filled and nothing new supplied, it just re-validated
        the identical request and re-showed the EXACT SAME confirmation
        prompt, forever. 'actually never mind' additionally got
        misinterpreted by slot extraction as a leave reason, polluting the
        draft. Cancellation must be a real terminal action: the draft is
        wiped and the user is told plainly, not looped back into limbo."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        apply_mock = MagicMock(side_effect=AssertionError("must never submit a declined request"))
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", apply_mock)
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "casual_leave",
            "from_date": "2026-09-10", "to_date": "2026-09-10",
            "session_type_slug": "full_day", "reason": None,
        })

        # Even if extraction misreads the decline as some field (the "never
        # mind" -> reason bug), the deterministic cancel check must win.
        mock_extraction(monkeypatch, {"is_affirmative": False, "reason": query})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state(query), writer)

        apply_mock.assert_not_called()
        assert "cancelled" in result["response_text"].lower()
        assert "shall i submit" not in result["response_text"].lower()
        assert fake_slots.get_slots(1, "conv-1") is None  # draft fully cleared, not looping

    async def test_apply_failure_reply_does_not_loop_forever(self, monkeypatch, fake_slots):
        """Live repro of a real bug: 'full day' -> confirm -> 'yes, submit' ->
        erp-api rejects as a duplicate application -> user replies 'yes' again
        (a completely natural response to '...or try again?') -> before the
        fix, this re-entered the confirmation branch and resubmitted the
        identical rejected request, producing the exact same error forever
        with no way out except typing a brand new date unprompted."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "sick_leave",
            "from_date": "2026-08-13", "to_date": "2026-08-13",
            "session_type_slug": "full_day", "reason": None,
        })

        async def _apply_fails(token, *a, **kw):
            return {"http_status": 400, "body": {
                "success": False, "message": "You have already applied Sick Leave for 2026-08-13.",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _apply_fails)

        # Turn 1: "Yes, please submit it." -> hits the duplicate-application rejection.
        mock_extraction(monkeypatch, {"is_affirmative": True})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Yes, please submit it."), writer)
        assert "already applied" in result["response_text"]

        # Turn 2: user replies "yes" again, same as they naturally would.
        # This must NOT resubmit — apply_leave must not be called again.
        apply_calls = {"count": 0}
        async def _apply_should_not_be_called(token, *a, **kw):
            apply_calls["count"] += 1
            return {"http_status": 400, "body": {"success": False, "message": "should not reach here"}}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _apply_should_not_be_called)

        mock_extraction(monkeypatch, {"is_affirmative": True})
        writer2 = FakeWriter()
        result2 = await hr_graph.leave_action_node(base_state("yes"), writer2)

        assert apply_calls["count"] == 0
        assert "already applied" not in result2["response_text"]
        assert "date" in result2["response_text"].lower()

    async def test_success_picks_the_newest_application_not_the_first(self, monkeypatch, fake_slots):
        """Regression: applyUsersLeave() returns ALL of the user's applied
        leaves (no orderBy), not just the one just created — a real live-test
        run showed the response echoing an old application's id (30) instead
        of the one actually just submitted (31) because the code took
        application[0] instead of the max id."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "casual_leave",
            "from_date": "2026-08-08", "to_date": "2026-08-08",
            "session_type_slug": "full_day", "reason": None,
        })

        async def _apply(token, *a, **kw):
            # Out-of-order on purpose — the old record appears first, exactly
            # as erp-api's unordered query returned it in the live repro.
            return {"http_status": 200, "body": {"success": True, "data": [
                {"id": 30, "from_date": "2026-09-01"},
                {"id": 31, "from_date": "2026-08-08"},
            ]}}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _apply)

        mock_extraction(monkeypatch, {"is_affirmative": True})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("yes"), writer)

        assert writer.of_type("leave_success")[0]["data"]["application_id"] == 31
        assert "31" in result["response_text"]
        assert "30" not in result["response_text"]

    async def test_clear_slots_failure_after_success_prevents_silent_resubmit(self, monkeypatch, fake_slots):
        """If clear_slots fails (both attempts) right after a successful
        submission, the slots must not be left sitting at
        "awaiting_confirmation" — that would let the user's very next
        unrelated reply silently resubmit the identical, already-submitted
        request if extraction happened to read it as affirmative. The
        fallback must force a terminal step instead."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "leave_type": "casual_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day", "reason": None,
        })

        applied = {"count": 0}
        async def _apply(token, *a, **kw):
            applied["count"] += 1
            return {"http_status": 200, "body": {"success": True, "data": [{"id": 500}]}}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _apply)

        # Simulate clear_slots failing every time (both retry attempts).
        monkeypatch.setattr(fake_slots, "clear_slots", lambda *a, **kw: False)

        mock_extraction(monkeypatch, {"is_affirmative": True})
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("yes"), writer)

        assert applied["count"] == 1
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved is not None
        assert saved["step"] != "awaiting_confirmation"

        # Next unrelated affirmative-sounding reply must NOT resubmit — worst
        # case it re-shows a confirmation prompt, never a silent duplicate.
        mock_extraction(monkeypatch, {"is_affirmative": True})
        writer2 = FakeWriter()
        await hr_graph.leave_action_node(base_state("ok thanks"), writer2)
        assert applied["count"] == 1

    async def test_revision_is_persisted_before_conflict_check_can_raise(self, monkeypatch, fake_slots):
        """If _find_conflicting_leave raises something other than the two
        expected erp-api exceptions (e.g. a malformed response body), the
        exception propagates out of leave_action_node uncaught — but this
        turn's merged correction must already be saved by that point, or
        it's silently lost and the next turn resumes from stale
        pre-correction slots."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "casual_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day", "reason": "personal",
        })

        async def _status_malformed(token, **kwargs):
            # Malformed body — .get("data", {}).get("leaves", []) raises
            # AttributeError since "data" is a string, not a dict.
            return {"http_status": 200, "body": {"success": True, "data": "unexpected"}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status_malformed)

        # User corrects the date on a turn where every slot was already filled.
        # Explicit ISO date, not a bare day-of-month — this test is about
        # exception propagation after persisting, not date ambiguity; a bare
        # "the 5th" here would now (correctly) trip the tier-3 ambiguous-
        # bare-day-of-month check and short-circuit before ever reaching
        # the conflict-check code path this test means to exercise.
        mock_extraction(monkeypatch, {"from_date": "2026-09-05", "to_date": "2026-09-05"})
        writer = FakeWriter()
        with pytest.raises(AttributeError):
            await hr_graph.leave_action_node(base_state("actually make it 2026-09-05"), writer)

        # The correction must have been persisted before the crash.
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-09-05"
        assert saved["to_date"] == "2026-09-05"


class TestDeterministicDateOverride:
    """leave_action_node's integration with services/date_resolver.py — see
    tests/test_date_resolver.py for the resolver's own pure-function tests.
    These tests exercise the override's WIRING into the conversation flow:
    that it actually replaces a wrong/absent LLM guess, composes correctly
    with duration counts, respects an explicit LLM-given range, is a true
    no-op for unrecognized phrasing, and runs early enough to affect the
    back-date and conflict checks downstream. All expected dates are
    computed via leave_action_service._today_in_app_timezone() itself (not a
    separately-computed date.today()), since QUOTA_TIMEZONE is configured
    to a real, non-UTC zone in this project — asserting against the same
    reference point the code under test actually uses is what keeps these
    tests correct regardless of exact run time or configured timezone."""

    async def test_next_monday_query_overrides_llm_guess_for_from_and_to_date(
        self, monkeypatch, fake_slots,
    ):
        import services.date_resolver as date_resolver
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        today = leave_action_service._today_in_app_timezone()
        expected = date_resolver.next_weekday_strict(today, 0).isoformat()  # Monday=0

        # The (mocked) LLM deliberately gets it wrong (some arbitrary,
        # unrelated date) — the deterministic override must win regardless.
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2020-01-01", "to_date": "2020-01-01",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("apply casual leave next Monday"), writer)

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == expected
        assert saved["to_date"] == expected

    async def test_duration_and_absolute_date_combination_fixes_original_bug_report(
        self, monkeypatch, fake_slots,
    ):
        """The exact reported bug: 'I want to apply 20 days leaves from 12th
        november' created a 1-day application. The LLM (mocked here exactly
        as it actually behaves — same from_date/to_date, no duration
        concept) still gets the absolute date; the deterministic duration
        extractor is what fixes the day count."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "30", "remaining": "30"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2026-11-12", "to_date": "2026-11-12",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("I want to apply 20 days leaves from 12th november"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-11-12"
        assert saved["to_date"] == "2026-12-01"  # 20 days inclusive, not 1
        assert leave_action_service._compute_requested_days(saved) == 20.0

    async def test_duration_alone_applies_against_an_already_known_from_date(
        self, monkeypatch, fake_slots,
    ):
        """A duration mentioned on a LATER turn, once from_date is already
        known from an earlier one, must still compute the correct to_date."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "30", "remaining": "30"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "casual_leave",
            "from_date": "2026-11-12", "to_date": "2026-11-12",
            "session_type_slug": "full_day", "reason": "personal",
        })
        mock_extraction(monkeypatch, {})
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("for 20 days"), writer)

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["to_date"] == "2026-12-01"

    async def test_explicit_range_wins_over_conflicting_duration_count(
        self, monkeypatch, fake_slots, caplog,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "30", "remaining": "30"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2026-11-05", "to_date": "2026-11-10",
            "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        with caplog.at_level("WARNING"):
            await hr_graph.leave_action_node(
                base_state("apply from 5th to 10th november for a week"), writer,
            )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-11-05"
        assert saved["to_date"] == "2026-11-10"  # unchanged — explicit range wins
        assert any("conflicts with explicit date range" in r.message for r in caplog.records)

    async def test_unrecognized_date_phrasing_with_a_relative_qualifier_now_asks_instead_of_trusting_llm(
        self, monkeypatch, fake_slots,
    ):
        """Superseded by TestLLMOnlyDateConfirmation: unrecognized phrasing
        used to fall through and silently trust whatever the LLM guessed —
        this test used to assert exactly that. Now that a relative-time
        qualifier ("next", here also "quarter") is present with nothing to
        cross-check it, that's precisely the unsafe case
        _llm_date_needs_confirmation exists to catch — the (mocked) LLM's
        guess of Nov 20 must NOT be silently trusted, or shown as a
        suggestion; the bot asks for the exact date instead."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2026-11-20", "to_date": "2026-11-20",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("apply casual leave sometime next quarter"), writer)

        assert "2026-11-20" not in result["response_text"]
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None
        assert saved["to_date"] is None

    async def test_deterministic_override_runs_before_back_date_check(self, monkeypatch, fake_slots):
        """A (mocked, naively-wrong) LLM guess of a PAST date must not get
        the request rejected as back-dated — the deterministic override
        (correctly resolving 'next Monday' to a future date) must run
        first, so the back-date check evaluates the corrected date."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}},
                "leave_settings": {"back_date_leave_allow": "0"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2020-01-01", "to_date": "2020-01-01",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("apply casual leave next Monday"), writer)

        assert "past date" not in result["response_text"].lower()

    async def test_named_month_anchored_range_fixes_reported_bug(self, monkeypatch, fake_slots):
        """The exact reported bug: 'I want to apply sick leave october first
        wednesday to october next saturday' resolved to today's date
        (2026-08-22) instead of a proper October range. The two named-month
        anchors in the query must override BOTH endpoints, taking precedence
        over whatever the (mocked, naively-wrong) LLM guessed."""
        import services.date_resolver as date_resolver
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "10", "remaining": "10"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        today = leave_action_service._today_in_app_timezone()
        range_result = date_resolver.resolve_date_range_phrase(
            "october first wednesday to october next saturday", today,
        )
        expected_from, expected_to = range_result[0]["from_date"], range_result[1]["from_date"]

        # The (mocked) LLM deliberately gets it wrong — collapses to today,
        # exactly as reported — the deterministic range override must win.
        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": today.isoformat(), "to_date": today.isoformat(),
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("I want to apply sick leave october first wednesday to october next saturday"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == expected_from
        assert saved["to_date"] == expected_to
        assert saved["from_date"] != today.isoformat()
        assert saved["to_date"] > saved["from_date"]

    async def test_week_of_month_range_fixes_reported_bug(self, monkeypatch, fake_slots):
        """The exact reported bug: 'i want to apply leave from november
        first week to end of the first week' left both dates unresolved,
        so the bot re-asked 'What dates would you like to take off?' even
        though a full week had already been named. The (mocked) LLM
        deliberately mimics the real failure — extracts nothing for either
        date field — proving the deterministic week-of-month override alone
        is what supplies both endpoints."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "20", "remaining": "20"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {"leave_type": "casual_leave"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("i want to apply leave from november first week to end of the first week"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-11-01"
        assert saved["to_date"] == "2026-11-07"
        assert leave_action_service._compute_requested_days(saved) == 7.0

    async def test_weekday_range_fixes_reported_hallucination_bug(self, monkeypatch, fake_slots):
        """The exact reported bug: 'I want to apply casual leave for
        upcoming wednesday to next sunday for full day due to health
        issue' produced a hallucinated, non-contiguous 2026-08-23 to
        2026-08-28 range. Root cause: the (mocked here exactly as it
        really behaved) LLM produced SOME distinct from/to guess of its
        own, and the old single-phrase override only ever replaces
        from_date by fixed pattern priority ('next sunday' beating
        'upcoming wednesday' despite appearing later in the sentence),
        leaving the LLM's unrelated to_date guess untouched. The new
        two-sided weekday-range resolver must override BOTH endpoints
        together instead."""
        import services.date_resolver as date_resolver
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        today = leave_action_service._today_in_app_timezone()
        query = (
            "I want to apply casual leave for upcoming wednesday to next sunday "
            "for full day due to health issue"
        )
        first, second = date_resolver.resolve_relative_date_range_phrase(query, today)

        # The (mocked) LLM deliberately reproduces the reported hallucination
        # — some distinct but WRONG from/to guess of its own.
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2026-08-23", "to_date": "2026-08-28",
            "session_type_slug": "full_day", "reason": "health issue",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state(query), writer)

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == first["from_date"]
        assert saved["to_date"] == second["from_date"]
        assert saved["from_date"] != "2026-08-23"
        assert saved["to_date"] != "2026-08-28"

    async def test_week_of_month_narrowed_to_weekday_and_duration_fixes_reported_bug(
        self, monkeypatch, fake_slots,
    ):
        """The exact reported bug: 'i want to apply casual leave for
        november first week coming wednesday for 1 day' was treated as a
        7-day request for the ENTIRE first week of November (surfacing
        'You only have 6 day(s)... but this request needs 7.0'), silently
        ignoring both 'coming wednesday' (narrowing to one specific day)
        and the explicit 'for 1 day' — because the old code returned
        immediately with the full week span before either could be
        considered. Balance is deliberately set to 6 remaining: a 7-day
        request would be rejected, but the correct 1-day request must
        succeed."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "6", "remaining": "6"}},
                "leave_settings": {"back_date_leave_allow": "1"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {"leave_type": "casual_leave"})
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("i want to apply casual leave for november first week coming wednesday for 1 day"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-11-04"  # the Wednesday within November's first week
        assert saved["to_date"] == "2026-11-04"    # exactly 1 day, not the whole 7-day week
        assert leave_action_service._compute_requested_days(saved) == 1.0


# ═════════════════════════════════════════════════════════════════════════════
# _llm_date_needs_confirmation / awaiting_date_confirmation — the safety net
# for a date that ONLY the LLM's raw guess produced, with zero deterministic
# cross-check. See date_extraction_direct_openai_sweep.py for the live-LLM
# diagnostic that sized and validated this trigger before implementation.
# ═════════════════════════════════════════════════════════════════════════════

class TestStructuredDateExtractionTier2:
    """leave_action_node's wiring to services.ai_service.extract_structured_
    date_fields / date_resolver.resolve_structured_date — the systemic fix
    for phrasing tier 1's regexes don't cover. The repo-wide autouse fixture
    _no_real_structured_date_calls (conftest.py) defaults every OTHER test
    to "nothing extracted"; these tests explicitly override it to prove the
    wiring actually uses a real result when tier 2 succeeds."""

    async def test_tier2_resolves_a_phrase_tier1_has_no_pattern_for(self, monkeypatch, fake_slots):
        """'the monday after next' matches no date_resolver regex at all
        (see TestLLMOnlyDateConfirmation's version of this same query,
        where tier 2 is left at its default no-op and the bot has to ask).
        Here tier 2 succeeds, so the correct date is used directly — no
        "ask the user" fallback needed."""
        import services.date_resolver as date_resolver
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        async def _fake_structured(query, today):
            return {
                "day_offset": None, "target_weekday": "monday", "weekday_relation": "next_to_next",
                "ordinal": None, "month_offset": None, "duration_days": None,
            }, {"prompt_tokens": 40, "completion_tokens": 10, "total_tokens": 50}
        monkeypatch.setattr(hr_graph, "extract_structured_date_fields", _fake_structured)

        today = leave_action_service._today_in_app_timezone()
        expected = date_resolver.next_to_next_weekday(today, 0).isoformat()  # Monday=0

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("the monday after next"), writer)

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == expected
        assert saved["to_date"] == expected
        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert confirmation[0]["data"]["total_days"] == 1.0
        # Structured-extraction usage recorded like every other LLM call.
        assert result["usage_events"][-1]["source"] == "structured_date_extraction"

    async def test_tier2_applies_duration_days_to_compute_to_date(self, monkeypatch, fake_slots):
        import services.date_resolver as date_resolver
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        today = leave_action_service._today_in_app_timezone()
        expected_from = date_resolver.next_weekday_strict(today, 4).isoformat()  # next Friday

        async def _fake_structured(query, today):
            return {
                "day_offset": None, "target_weekday": "friday", "weekday_relation": "next",
                "ordinal": None, "month_offset": None, "duration_days": 3,
            }, None
        monkeypatch.setattr(hr_graph, "extract_structured_date_fields", _fake_structured)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("starting next friday for 3 days"), writer)

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == expected_from
        from datetime import date as _date, timedelta as _timedelta
        assert saved["to_date"] == (_date.fromisoformat(expected_from) + _timedelta(days=2)).isoformat()

    async def test_tier2_not_attempted_when_tier1_already_matched(self, monkeypatch, fake_slots):
        """Tier 2 costs a real LLM call — must not fire at all when tier 1
        (regex) already resolved the date confidently."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        tier2_calls = []
        async def _tracking_structured(query, today):
            tier2_calls.append(query)
            return {
                "day_offset": None, "target_weekday": None, "weekday_relation": None,
                "ordinal": None, "month_offset": None, "duration_days": None,
            }, None
        monkeypatch.setattr(hr_graph, "extract_structured_date_fields", _tracking_structured)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("apply casual leave next monday"), writer)

        assert tier2_calls == []  # tier 1 (regex) already matched "next monday" — tier 2 never invoked

    async def test_duration_offset_phrase_resolves_via_tier1_not_tier2(self, monkeypatch, fake_slots):
        """Systemic gap found via audit: 'in two weeks' had no weekday name
        and none of the fixed qualifier words, so it was invisible to BOTH
        tier 2's gate and tier 3's cross-check, silently riding on the
        plain first-pass LLM extraction's own guess. Now resolved by a real
        tier-1 regex (date_resolver.resolve_relative_duration_offset_phrase)
        — free, deterministic, and tier 2 must never fire for it."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        tier2_calls = []
        async def _tracking_structured(query, today):
            tier2_calls.append(query)
            return {
                "day_offset": None, "target_weekday": None, "weekday_relation": None,
                "ordinal": None, "month_offset": None, "duration_days": None,
            }, None
        monkeypatch.setattr(hr_graph, "extract_structured_date_fields", _tracking_structured)

        today = leave_action_service._today_in_app_timezone()
        from datetime import timedelta as _td
        expected = (today + _td(days=14)).isoformat()

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("apply casual leave in two weeks"), writer)

        assert tier2_calls == []  # tier 1 resolved it — tier 2 never invoked
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == expected
        assert saved["to_date"] == expected

    async def test_tier2_no_extraction_falls_through_to_tier3(self, monkeypatch, fake_slots):
        """Tier 2 explicitly returns nothing usable — same "ask, don't
        guess" outcome as if tier 2 didn't exist at all."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _fake_structured(query, today):
            return {
                "day_offset": None, "target_weekday": None, "weekday_relation": None,
                "ordinal": None, "month_offset": None, "duration_days": None,
            }, None
        monkeypatch.setattr(hr_graph, "extract_structured_date_fields", _fake_structured)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2026-09-07", "to_date": "2026-09-07",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("the monday after next"), writer)

        assert "2026-09-07" not in result["response_text"]
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None


class TestMatchKnownLeaveType:
    """Direct unit-level lock-in for the deterministic leave-type matcher
    that backs the "never deny a type this company actually has" fix. It
    matches against each type's own slug AND display name after
    normalization, so it can only ever return a real configured type."""

    KNOWN = [
        {"slug": "casual_leave", "name": "Casual Leave"},
        {"slug": "short_leave", "name": "Short Leave"},
    ]

    @pytest.mark.parametrize("text", [
        "Short Leave", "short leave", "SHORT LEAVE", "short_leave",
        "Short-Leave", "  short   leave  ", "short",
    ])
    def test_matches_regardless_of_case_or_separator(self, text):
        assert leave_action_service._match_known_leave_type(text, self.KNOWN) == "short_leave"

    def test_matches_the_other_configured_type_too(self):
        assert leave_action_service._match_known_leave_type("CASUAL", self.KNOWN) == "casual_leave"

    @pytest.mark.parametrize("text", ["maternity", "Maternity Leave", "PL", "bereavement"])
    def test_returns_none_for_a_type_this_company_does_not_have(self, text):
        assert leave_action_service._match_known_leave_type(text, self.KNOWN) is None

    def test_returns_none_when_no_known_list_available(self):
        # erp-api unreachable — must not fabricate a match from nothing.
        assert leave_action_service._match_known_leave_type("Short Leave", None) is None

    def test_returns_none_for_empty_input(self):
        assert leave_action_service._match_known_leave_type("", self.KNOWN) is None
        assert leave_action_service._match_known_leave_type("   ", self.KNOWN) is None

    def test_does_not_match_on_a_missing_display_name(self):
        """A type whose name is absent must not accidentally match empty
        or whitespace-only input via a blank normalized name."""
        known = [{"slug": "comp_off", "name": None}]
        assert leave_action_service._match_known_leave_type("   ", known) is None
        assert leave_action_service._match_known_leave_type("comp off", known) == "comp_off"


class TestQueryNeedsRelativeDateScrutiny:
    """Direct unit-level lock-in for the shared gate predicate (hr_graph.
    _query_needs_relative_date_scrutiny) that replaced two hand-duplicated
    copies of the same expression — the duplication is itself how the
    duration-offset gap went unnoticed (a third clause was only ever going
    to be added to one copy). Confirms the duration-offset signal and the
    newer already-passed-bare-day-of-month signal are both covered, and
    that the still-legitimate exemptions (an unambiguous bare day-number,
    an explicit ISO date range) are NOT regressed into being scrutinized —
    both must still pass through silently, same as before. `today` is now
    a required argument (see date_resolver.mentions_ambiguous_bare_day_of_
    month — the bare-day-of-month signal is only ambiguous relative to
    what day it currently is), so every call below passes one explicitly."""

    def test_true_for_named_weekday(self):
        assert leave_action_service._query_needs_relative_date_scrutiny(
            "apply leave next monday", date(2026, 8, 1),
        ) is True

    def test_true_for_qualifier_word(self):
        assert leave_action_service._query_needs_relative_date_scrutiny(
            "apply leave this weekend", date(2026, 8, 1),
        ) is True

    def test_true_for_duration_offset_phrase(self):
        assert leave_action_service._query_needs_relative_date_scrutiny(
            "apply leave in two weeks", date(2026, 8, 1),
        ) is True
        assert leave_action_service._query_needs_relative_date_scrutiny(
            "15 days from now", date(2026, 8, 1),
        ) is True

    def test_false_for_bare_absolute_day_number_still_upcoming_this_month(self):
        # Deliberately exempt — genuinely unambiguous (the 5th is still
        # ahead when today is the 1st), see _llm_date_needs_confirmation's
        # own docstring.
        assert leave_action_service._query_needs_relative_date_scrutiny(
            "apply leave on the 5th", date(2026, 8, 1),
        ) is False

    def test_false_for_explicit_iso_date_range(self):
        assert leave_action_service._query_needs_relative_date_scrutiny(
            "From 2026-11-18 to 2026-11-19", date(2026, 8, 1),
        ) is False

    def test_true_for_bare_day_of_month_already_passed(self):
        """Live bug repro: 2026-08-27, 'apply leave on 15th' — the 15th has
        already gone by this month, so which month is meant is genuinely
        ambiguous and must now be scrutinized (previously silently ignored)."""
        assert leave_action_service._query_needs_relative_date_scrutiny(
            "apply leave on 15th", date(2026, 8, 27),
        ) is True

    def test_false_for_bare_day_of_month_with_explicit_month_name(self):
        assert leave_action_service._query_needs_relative_date_scrutiny(
            "apply leave on 15th August", date(2026, 8, 27),
        ) is False

    def test_false_for_bare_day_of_month_with_explicit_month_qualifier(self):
        # "current month" specifically (not "next"/"this") — those other
        # qualifier words already trip the pre-existing weekday/qualifier
        # disjunct regardless of the day-of-month signal, so they wouldn't
        # isolate what this test means to check.
        assert leave_action_service._query_needs_relative_date_scrutiny(
            "apply leave on current month's 15th", date(2026, 8, 27),
        ) is False


class TestDeterministicRangeOverrideThreeNewerResolvers:
    """Live bug (found via audit, not yet reported): resolve_next_month_
    weekday_phrase/resolve_this_month_weekday_phrase/resolve_this_week_
    weekday_phrase each silently collapsed a two-sided range to just the
    first endpoint — the same bug shape already fixed for range_result/
    weekday_range_result, just never extended to these three. Verifies the
    fix end-to-end through leave_action_node: both dates get set correctly
    in one turn, with tier 2 never invoked (tier 1 already matched)."""

    async def test_this_week_monday_to_friday_range(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        tier2_calls = []
        async def _tracking_structured(query, today):
            tier2_calls.append(query)
            return {
                "day_offset": None, "target_weekday": None, "weekday_relation": None,
                "ordinal": None, "month_offset": None, "duration_days": None,
            }, None
        monkeypatch.setattr(hr_graph, "extract_structured_date_fields", _tracking_structured)

        # Anchor "today" to a Monday so "Monday of this week" isn't in the past.
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 24))

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply casual leave monday of this week to friday of this week"), writer,
        )

        assert tier2_calls == []
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-08-24"
        assert saved["to_date"] == "2026-08-28"

    async def test_next_month_first_friday_to_last_friday_range(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            # 2026-09-04..2026-09-25 is a 22-day span — balance must cover
            # it or the (separate, working-as-designed) insufficient-
            # balance branch clears the dates before this test can observe
            # the range-override result.
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "30", "remaining": "30"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 24))

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply casual leave first friday of next month to last friday of next month"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-09-04"
        assert saved["to_date"] == "2026-09-25"

    async def test_this_month_first_monday_to_last_friday_range(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            # 2026-08-03..2026-08-28 is a 26-day span — balance must cover
            # it or the (separate, working-as-designed) insufficient-
            # balance branch clears the dates before this test can observe
            # the range-override result.
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "30", "remaining": "30"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 1))

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply casual leave first monday this month to last friday this month"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-08-03"
        assert saved["to_date"] == "2026-08-28"


class TestWeekOfNextMonthNarrowedToWeekday:
    """Live bug, found by mining real production queries: the exact same
    underlying concept ('next month's Nth week, narrowed to a weekday')
    was retried at least 7 times across different word orders — a strong
    signal it was never resolving correctly. Verifies the fix end-to-end
    through leave_action_node, with tier 2 never invoked since tier 1 now
    resolves every one of these deterministically."""

    async def test_next_month_first_week_weekday_word_order(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 24))

        tier2_calls = []
        async def _tracking_structured(query, today):
            tier2_calls.append(query)
            return {
                "day_offset": None, "target_weekday": None, "weekday_relation": None,
                "ordinal": None, "month_offset": None, "duration_days": None,
            }, None
        monkeypatch.setattr(hr_graph, "extract_structured_date_fields", _tracking_structured)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply casual leave for next month first week wednesday"), writer,
        )

        assert tier2_calls == []
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-09-02"
        assert saved["to_date"] == "2026-09-02"

    async def test_weekday_in_ordinal_week_of_next_month_word_order(self, monkeypatch, fake_slots):
        # The exact live repro: weekday named FIRST, then "in the Nth week
        # of next month" — a completely different word order from the
        # test above, must resolve to the same underlying construct.
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 24))

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("Apply leave for wednesday in the second week of next month"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-09-09"
        assert saved["to_date"] == "2026-09-09"

    async def test_next_month_week_with_no_weekday_uses_the_whole_span(self, monkeypatch, fake_slots):
        # No weekday named at all — same "a week mention already implies
        # both endpoints" contract as week_of_month's own bare usage.
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 24))

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "session_type_slug": "full_day", "reason": "personal",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply casual leave for next month first week"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == "2026-09-01"
        assert saved["to_date"] == "2026-09-07"


class TestLLMOnlyDateConfirmation:

    async def test_ambiguous_relative_phrase_reprompts_without_suggesting_a_date(self, monkeypatch, fake_slots):
        """'the monday after next' matches no date_resolver pattern at all
        (confirmed via the diagnostic sweep) — the LLM's own guess must not
        be silently trusted, and must not even be SHOWN to the user as a
        proposal. Live repro: 'second week friday' guessed 2026-09-08 — not
        even a Friday — so suggesting a specific date here risks putting a
        wrong one in front of the user for them to rubber-stamp. Just ask,
        plainly, with no guess attached."""
        import services.date_resolver as date_resolver
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        today = leave_action_service._today_in_app_timezone()
        wrong_guess = date_resolver.next_to_next_weekday(today, 0).isoformat()  # Monday=0
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": wrong_guess, "to_date": wrong_guess,
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("the monday after next"), writer)

        assert wrong_guess not in result["response_text"]  # never surfaced, right or wrong
        assert "exact date" in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] != "awaiting_date_confirmation"
        assert saved["from_date"] is None
        # Frontend signal: this response is specifically asking for a date,
        # so a calendar picker is the right input to show.
        assert writer.of_type("done")[0]["data"]["requires_date_input"] is True
        assert saved["to_date"] is None

    async def test_bare_next_month_with_no_day_reprompts_without_guessing_the_1st(
        self, monkeypatch, fake_slots,
    ):
        """Live bug: 'apply casual leave for next month' (no day, weekday,
        or ordinal at all) silently resolved to just the 1st of next month
        via date_resolver._PATTERNS' bare 'next_month' entry — an
        unannounced guess, since 'next month' alone never names a specific
        day the way 'tomorrow' or 'next Monday' do. Must ask instead of
        silently picking the 1st, same treatment as any other genuinely
        ambiguous relative phrase."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        today = leave_action_service._today_in_app_timezone()
        from services import date_resolver
        first_of_next_month = date_resolver.first_of_next_month(today).isoformat()
        # The (mocked) plain extraction guesses the 1st, exactly as observed live.
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": first_of_next_month, "to_date": first_of_next_month,
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("apply casual leave for next month"), writer)

        assert first_of_next_month not in result["response_text"]  # never surfaced as a suggestion
        assert "exact date" in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None
        assert saved["to_date"] is None
        assert writer.of_type("done")[0]["data"]["requires_date_input"] is True

    async def test_bare_day_of_month_already_passed_reprompts_instead_of_silently_rolling_month(
        self, monkeypatch, fake_slots,
    ):
        """Live bug repro, 2026-08-27: 'Apply leave on 15th' went through
        the entire apply-leave flow and only ever showed 2026-09-15 at the
        final confirmation card — the assistant silently decided the user
        meant NEXT month's 15th (since Aug 15 had already passed) with no
        earlier indication that a month had been inferred at all. Must ask
        instead of silently rolling forward, same treatment as the bare
        'next month' case above and every other genuinely ambiguous
        relative phrase this safety net catches."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        # Anchor "today" to the exact live-repro date — the ambiguity this
        # test exercises (a bare day-of-month that has ALREADY PASSED this
        # month) only exists relative to a specific today; the real
        # wall-clock date drifting past it would otherwise make "15th"
        # genuinely unambiguous (still upcoming) and silently defeat the
        # scenario being tested.
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 27))
        today = leave_action_service._today_in_app_timezone()
        # The (mocked) plain extraction rolls forward to next month's 15th,
        # exactly as observed live.
        next_month_15th = date(today.year + (1 if today.month == 12 else 0),
                                1 if today.month == 12 else today.month + 1, 15).isoformat()
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": next_month_15th, "to_date": next_month_15th,
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Apply leave on 15th"), writer)

        assert next_month_15th not in result["response_text"]  # never surfaced as a suggestion
        assert "exact date" in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None
        assert saved["to_date"] is None
        assert writer.of_type("done")[0]["data"]["requires_date_input"] is True

    async def test_bare_day_of_month_still_upcoming_this_month_is_not_reprompted(
        self, monkeypatch, fake_slots,
    ):
        """Guard case: a bare day-of-month that HASN'T passed yet this
        month is genuinely unambiguous and must not regress into being
        reprompted — the LLM's plain, same-month extraction stands as-is."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        # Unlike the ambiguous case above, this query is NOT flagged, so the
        # flow proceeds into the date-conflict check — must mock get_leave_
        # status or this hits the real network (see _no_conflicting_leaves).
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        today = leave_action_service._today_in_app_timezone()
        import calendar
        last_day_this_month = calendar.monthrange(today.year, today.month)[1]
        still_upcoming_day = today.replace(day=min(today.day + 1, last_day_this_month))
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave",
            "from_date": still_upcoming_day.isoformat(), "to_date": still_upcoming_day.isoformat(),
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state(f"Apply leave on {still_upcoming_day.day}th"), writer,
        )

        assert "exact date" not in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] == still_upcoming_day.isoformat()

    async def test_next_month_weekday_reversed_word_order_resolves_deterministically_not_via_confirmation(
        self, monkeypatch, fake_slots,
    ):
        """Live bug report, in production: 'apply leave ... in the next
        month of first friday ...' always resolved to just the 1st of next
        month (a Tuesday, not a Friday) — the bare 'next month' pattern was
        shadowing the more specific weekday because
        resolve_next_month_weekday_phrase's regex didn't yet cover this
        word order. Must now resolve deterministically and correctly,
        WITHOUT needing a confirmation turn at all — this is a case
        date_resolver genuinely knows how to get right."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        # Anchor "today" so "next month" is unambiguously September 2026 —
        # the assertion below pins the expected result to September's own
        # first Friday (the 4th).
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 24))
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        # The (mocked) LLM deliberately gets it wrong, exactly as observed
        # live — the deterministic override must win regardless.
        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day",
            "reason": "reason is sick leave - leave type is sick for full day",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state(
                "Apply leave for  in the next month of first friday reason is sick leave "
                "- leave type is sick for full day"
            ),
            writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] != "awaiting_date_confirmation"
        assert saved["from_date"] == "2026-09-04"  # first Friday of September 2026, not the 1st
        assert saved["to_date"] == "2026-09-04"
        # Reached the real final submit-confirmation card in one turn — not
        # the new date-confirmation safety net, since this date was resolved
        # with full deterministic confidence.
        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert confirmation[0]["data"]["total_days"] == 1.0

    async def test_this_month_weekday_resolves_deterministically_not_via_confirmation(
        self, monkeypatch, fake_slots,
    ):
        """Live bug report, in production: 'apply sick for last monday this
        month full day reason is fever' gave a DIFFERENT wrong answer on
        every call for the identical query (2026-08-22, then 2026-08-15 a
        minute later) — no pattern covered 'this month' at all, so the LLM
        was guessing blind. Today is pinned via monkeypatch (rather than
        relying on whatever the real calendar date happens to be at test
        time) so 'last Monday this month' has a fixed, reproducible answer
        regardless of when in the month this suite actually runs."""
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 24))
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        # The (mocked) LLM deliberately gets it wrong, exactly as observed
        # live — the deterministic override must win regardless.
        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-22", "to_date": "2026-08-22",
            "session_type_slug": "full_day", "reason": "fever",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("please apply sick for last monday this month full day reason is fever"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] != "awaiting_date_confirmation"
        assert saved["from_date"] == "2026-08-31"  # last Monday of August 2026, not the LLM's guess
        assert saved["to_date"] == "2026-08-31"
        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1
        assert confirmation[0]["data"]["total_days"] == 1.0

    async def test_this_week_weekday_still_ahead_resolves_deterministically(self, monkeypatch, fake_slots):
        """A day within the current calendar week that HASN'T passed yet
        (asked on a Tuesday about this week's Friday) resolves straight to
        confirmation — no ambiguity, no deferral needed."""
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 25))  # a Tuesday
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"sick_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2026-08-25", "to_date": "2026-08-25",
            "session_type_slug": "full_day", "reason": "fever",
        })
        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("apply sick leave for friday of current week full day reason is fever"), writer,
        )

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] != "awaiting_date_confirmation"
        assert saved["from_date"] == "2026-08-28"  # this week's Friday
        confirmation = writer.of_type("leave_confirmation")
        assert len(confirmation) == 1

    async def test_this_week_weekday_already_passed_defers_to_back_date_check(self, monkeypatch, fake_slots):
        """Live bug: 'Monday of current week' asked on a Tuesday (this
        week's Monday is chronologically yesterday) hallucinated an
        unrelated date that wasn't even a Monday — the schema had no way to
        represent 'the specific day within the current week, even if
        already past'. Must now defer to the same, well-tested back-date
        machinery as 'yesterday', not guess and not use the generic
        _llm_date_needs_confirmation wording."""
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone", lambda: date(2026, 8, 25))  # a Tuesday

        # Even if the (mocked) LLM's raw guess is a hallucinated, unrelated
        # date — as observed live — the deterministic layer's own decision
        # to defer must win regardless of what the LLM guessed.
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {}, "leave_settings": {"back_date_leave_allow": "0"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {"from_date": "2026-08-22", "to_date": "2026-08-22"})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("apply causal leave for monday of current week"), writer,
        )

        message = result["response_text"].lower()
        assert "past date" in message  # the existing back-date-disallowed wording
        assert "already passed" not in message  # not the generic _llm_date_needs_confirmation wording
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None

    async def test_invalid_date_range_reprompts_directly_without_yes_no_step(self, monkeypatch, fake_slots):
        """An inverted range (end before start) isn't something to offer a
        yes/no confirmation on — there's nothing sensible to confirm."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2026-09-20", "to_date": "2026-09-10",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("apply leave from 20th september to 10th september"), writer,
        )

        assert "valid date" in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] != "awaiting_date_confirmation"
        assert saved["from_date"] is None
        assert saved["to_date"] is None
        assert writer.of_type("done")[0]["data"]["requires_date_input"] is True

    async def test_past_date_from_unrecognized_phrase_reprompts_without_yes_no_step(
        self, monkeypatch, fake_slots,
    ):
        """The exact motivating gap: a date inferred from a reference
        date_resolver has no pattern for, landing in the past by accident —
        must be caught even though nothing here disagrees with it (there's
        no deterministic candidate to disagree in the first place)."""
        from datetime import timedelta
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "10", "remaining": "10"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        today = leave_action_service._today_in_app_timezone()
        past = (today - timedelta(days=5)).isoformat()
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": past, "to_date": past,
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("leave starting the day after my project deadline"), writer,
        )

        assert "already passed" in result["response_text"].lower()
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["step"] != "awaiting_date_confirmation"
        assert saved["from_date"] is None
        assert writer.of_type("done")[0]["data"]["requires_date_input"] is True

    async def test_deliberate_past_date_word_defers_to_existing_back_date_check(
        self, monkeypatch, fake_slots,
    ):
        """Regression guard for the OTHER direction: 'yesterday' is a word
        date_resolver recognizes but deliberately refuses to resolve (see
        date_resolver.resolve_relative_date_phrase's allow_past guard) —
        this must NOT be swallowed by the new past_date check; it has to
        keep reaching the existing, company-policy-aware
        back-date-disallowed rejection, unchanged."""
        from datetime import timedelta
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {}, "leave_settings": {"back_date_leave_allow": "0"},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        today = leave_action_service._today_in_app_timezone()
        yesterday = (today - timedelta(days=1)).isoformat()
        mock_extraction(monkeypatch, {"from_date": yesterday, "to_date": yesterday})
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("i want to apply leave for yesterday"), writer)

        message = result["response_text"].lower()
        assert "past date" in message  # the ORIGINAL back-date-disallowed wording, not the new one
        assert "already passed" not in message
        assert writer.of_type("done")[0]["data"]["requires_date_input"] is True


# ═════════════════════════════════════════════════════════════════════════════
# _resolve_deterministic_date_range / _resolve_date_range — the generalized,
# reusable date extractor behind has_date_expression-gated flows
# ═════════════════════════════════════════════════════════════════════════════

class TestResolveDeterministicDateRange:
    """Direct unit tests for the pure precedence-chain helper, independent of
    any particular flow — proves it behaves the same way outside the
    apply-leave slot-filling context that _apply_deterministic_date_overrides
    was built for."""

    def test_single_relative_weekday(self):
        today = date(2026, 8, 21)  # a Friday
        result = leave_action_service._resolve_deterministic_date_range("next monday", today)
        assert result == ("2026-08-24", "2026-08-24")

    def test_named_month_range(self):
        today = date(2026, 8, 21)
        result = leave_action_service._resolve_deterministic_date_range(
            "october first wednesday to october next saturday", today,
        )
        assert result is not None
        from_date, to_date = result
        assert from_date < to_date

    def test_duration_extends_a_single_resolved_date(self):
        today = date(2026, 8, 21)
        result = leave_action_service._resolve_deterministic_date_range("tomorrow for 3 days", today)
        assert result == ("2026-08-22", "2026-08-24")

    def test_unrecognized_phrasing_returns_none(self):
        today = date(2026, 8, 21)
        assert leave_action_service._resolve_deterministic_date_range("21th august", today) is None


class TestResolveDateRange:
    """The async orchestrator: deterministic first, LLM fallback only when
    the deterministic chain finds nothing."""

    async def test_deterministic_hit_never_calls_llm(self, monkeypatch):
        def _must_not_be_called(*args, **kwargs):
            raise AssertionError("LLM must not be called when the deterministic resolver already matched")
        monkeypatch.setattr(leave_action_service, "_call_llm", _must_not_be_called)

        result = await leave_action_service._resolve_date_range("next monday", date(2026, 8, 21))

        assert result == ("2026-08-24", "2026-08-24")

    async def test_falls_back_to_llm_for_unrecognized_phrasing(self, monkeypatch):
        captured = {}

        async def _fake_call_llm(prompt, max_tokens=None, model=None):
            captured["prompt"] = prompt
            return {"__result__": {"from_date": "2026-08-21", "to_date": "2026-08-21"}}

        def _fake_extract_text(response):
            return json.dumps(response.get("__result__", {}))

        monkeypatch.setattr(leave_action_service, "_call_llm", _fake_call_llm)
        monkeypatch.setattr(leave_action_service, "_extract_text", _fake_extract_text)

        result = await leave_action_service._resolve_date_range(
            "21th august", date(2026, 8, 21), purpose_hint="the employee's own leave request history",
        )

        assert result == ("2026-08-21", "2026-08-21")
        assert "the employee's own leave request history" in captured["prompt"]

    async def test_fails_open_on_llm_error(self, monkeypatch):
        async def _broken_call_llm(prompt, max_tokens=None, model=None):
            raise RuntimeError("network error")
        monkeypatch.setattr(leave_action_service, "_call_llm", _broken_call_llm)

        result = await leave_action_service._resolve_date_range("21th august", date(2026, 8, 21))

        assert result is None


class TestLeaveActionNodeStatusBranch:

    @pytest.mark.parametrize("query,expected_status", [
        ("show my approve leave", "approved"),
        ("show my approval leave", "approved"),
        ("show my cancel leave", "cancelled"),
        ("show my cancelling leave", "cancelled"),
        ("show my rejection leave", "rejected"),
    ])
    async def test_status_filter_matches_verb_and_noun_forms_not_just_the_exact_word(
        self, monkeypatch, fake_slots, query, expected_status,
    ):
        """Live bug (2026-08-20): 'show my approve leave' (missing the '-d')
        and 'show my cancel leave' (missing '-led') both failed to match the
        old exact-word filter check and fell through to the ambiguous
        clarify, even though the LLM had already correctly classified the
        intent as leave_status. Must recognize common verb/noun forms of
        the same status word, not just its exact literal spelling."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == expected_status
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state(query, "leave_status"), writer)

        assert "make sure i get you the right info" not in result["response_text"].lower()

    async def test_ambiguous_query_asks_type_category_and_date_range(
        self, monkeypatch, fake_slots, fake_history_clarify_state,
    ):
        """'show my leaves' — no status/all/question word, no 'status',
        no date range — must ask for all three dimensions and store nothing
        already known."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("show my leaves", "leave_status"), writer)

        assert "balance" in result["response_text"].lower()
        assert "approved, cancelled, or rejected" in result["response_text"].lower()
        assert "time period" in result["response_text"].lower()
        stored = fake_history_clarify_state.get_state(1, "conv-1")
        assert stored == {"leave_type_slug": None, "date_from": None, "date_to": None}

    async def test_ambiguous_query_with_type_and_range_already_given_only_asks_category(
        self, monkeypatch, fake_slots, fake_history_clarify_state,
    ):
        """'show my sick leaves from 2026-06-01 to 2026-08-01' already
        answers type and date range — only category is still ambiguous, so
        the time-period ask must be dropped and the type/range stored for
        the reply to inherit."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show my sick leaves from 2026-06-01 to 2026-08-01", "leave_status"), writer
        )

        assert "time period" not in result["response_text"].lower()
        assert "sick" in result["response_text"].lower()
        stored = fake_history_clarify_state.get_state(1, "conv-1")
        assert stored == {"leave_type_slug": "sick_leave", "date_from": "2026-06-01", "date_to": "2026-08-01"}

    async def test_unconfigured_type_name_reports_unsupported(self, monkeypatch, fake_slots):
        """Bug found 2026-08-26: 'show my maternity leaves' named a type
        _extract_leave_type_filters' closed vocabulary doesn't recognise at
        all, so the query proceeded as if NO type had been named — showing
        every leave type instead of saying Maternity Leave isn't supported.
        Checked dynamically against this company's real leave_settings
        (fetched here for the first time in the status branch), same
        wording as leave_eligibility_service's equivalent message."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "12", "remaining": "8"}},
                "leave_settings": {"leave_type": [
                    {"name": "Casual Leave", "slug": "casual_leave", "benefit_start": "joining"},
                    {"name": "Sick Leave", "slug": "sick_leave", "benefit_start": "joining"},
                    {"name": "Earned Leave", "slug": "earned_leave", "benefit_start": "confirmation"},
                    {"name": "Short Leave", "slug": "short_leave", "benefit_start": "joining"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _applied(token, **kwargs):
            raise AssertionError("get_applied_leaves must not be called for an unsupported type")
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("show my maternity leaves", "leave_status"), writer)

        assert "Helix AI currently supports" in result["response_text"]
        assert "'Maternity Leave' is not supported in this portal" in result["response_text"]
        assert writer.of_type("leave_status") == []

    @pytest.mark.parametrize("query", [
        "show my pending leaves", "show my approved leaves", "show my cancelled leaves",
        "show my applied leaves", "show my all leaves",
    ])
    async def test_status_word_never_misread_as_a_leave_type(self, monkeypatch, fake_slots, query):
        """Regression guard: a naive '<word> leave(s)' fallback would read
        'pending'/'approved'/etc. as if they were a leave TYPE name (found
        while building the unsupported-type check above) — these are
        status qualifiers, not type names, and must take the normal status
        path with no erp-api lookup for leave_settings at all."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            raise AssertionError("get_leave_balance must not be called for a plain status word")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state(query, "leave_status"), writer)

        assert "is not supported in this portal" not in result["response_text"]

    async def test_dynamically_configured_type_is_not_flagged_unsupported(self, monkeypatch, fake_slots):
        """A company that genuinely configures Paternity Leave must still
        get a real answer for it here — only a truly unconfigured name
        reaches the unsupported-type message."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"paternity_leave": {"total": "5", "remaining": "5"}},
                "leave_settings": {"leave_type": [
                    {"name": "Casual Leave", "slug": "casual_leave", "benefit_start": "joining"},
                    {"name": "Paternity Leave", "slug": "paternity_leave", "benefit_start": "joining"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show my paternity leaves", "leave_status"), writer)

        assert "is not supported in this portal" not in result["response_text"]

    async def test_balance_lookup_failure_falls_through_silently(self, monkeypatch, fake_slots):
        """The extra leave_settings lookup is a nice-to-have check, not a
        hard dependency — if it fails, the status query must still get its
        normal answer rather than erroring out or blocking."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _balance(token, **kwargs):
            raise ErpApiTimeout("timed out")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("show my maternity leaves", "leave_status"), writer)

        assert "try again" not in result["response_text"].lower()
        assert "is not supported in this portal" not in result["response_text"]

    async def test_explicit_date_range_filters_the_results(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "approved"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 1, "leave_type": "Casual Leave", "leave_type_slug": "casual_leave",
                 "from_date": "2026-06-15", "to_date": "2026-06-15", "status": "1", "status_name": "approved"},
                {"id": 2, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": "2026-09-01", "to_date": "2026-09-01", "status": "1", "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show my approved leaves from 2026-06-01 to 2026-08-01", "leave_status"), writer
        )

        assert "Casual Leave" in result["response_text"]
        assert "Sick Leave" not in result["response_text"]

    async def test_status_branch_single_leave(self, monkeypatch, fake_slots):
        """'status' in the query already reads as 'tell me about what I've
        submitted' in common usage, so this stays on the existing
        pending-default — unchanged data-wise, just fetched via the new
        /leave/applied?leave_status=pending endpoint."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "pending"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 30, "leave_type": "Casual Leave", "leave_type_slug": "casual_leave",
                 "from_date": "2026-09-01", "to_date": "2026-09-01",
                 "status": "0", "status_name": "pending", "reason": None, "leave_count": "1"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("what's the status of my leave?", "leave_status"), writer)

        status_events = writer.of_type("leave_status")
        assert len(status_events) == 1
        assert status_events[0]["data"]["leaves"][0]["status_name"] == "pending"
        assert "pending" in result["response_text"]
        assert "Casual Leave" in result["response_text"]

    async def test_status_branch_filters_to_pending_only(self, monkeypatch, fake_slots):
        """'I want to know only pending leave status' must ask erp-api for
        pending specifically — filtering is server-side now (leave_status
        query param), not a client-side post-filter."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "pending"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 31, "leave_type": "Sick Leave", "from_date": "2026-08-10", "to_date": "2026-08-10",
                 "status": "0", "status_name": "pending"},
                {"id": 32, "leave_type": "Earned Leave", "from_date": "2026-08-14", "to_date": "2026-08-14",
                 "status": "0", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("i want to know only pending leave status", "leave_status"), writer
        )

        status_events = writer.of_type("leave_status")
        assert len(status_events) == 1
        returned_leaves = status_events[0]["data"]["leaves"]
        assert len(returned_leaves) == 2
        assert all(lv["status_name"] == "pending" for lv in returned_leaves)
        assert status_events[0]["data"]["filter"] == "pending"
        assert "Sick Leave" in result["response_text"]
        assert "Earned Leave" in result["response_text"]

    async def test_status_branch_filters_by_date(self, monkeypatch, fake_slots):
        """Live bug repro: a leave-status query naming a specific day used to
        return every leave on record — this branch only ever supported
        filtering by status word, never by date. 'today'/'yesterday'/
        'tomorrow' are resolved deterministically by
        _resolve_date_range_phrase (no LLM call involved in date handling at
        all — see get_applied_leaves, the real endpoint this branch calls);
        must filter down to just the leave(s) overlapping that date."""
        from datetime import timedelta
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        today_iso = leave_action_service._today().isoformat()
        other_day_iso = (leave_action_service._today() + timedelta(days=10)).isoformat()

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "pending"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 35, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": other_day_iso, "to_date": other_day_iso, "status": "0", "status_name": "pending"},
                {"id": 34, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": today_iso, "to_date": today_iso, "status": "0", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("what's the status of my leave today", "leave_status"), writer,
        )

        status_events = writer.of_type("leave_status")
        assert len(status_events) == 1
        returned_leaves = status_events[0]["data"]["leaves"]
        assert len(returned_leaves) == 1
        assert returned_leaves[0]["id"] == 34
        assert today_iso in result["response_text"]
        assert other_day_iso not in result["response_text"]

    async def test_status_branch_filters_by_date_deterministically_without_llm(self, monkeypatch, fake_slots):
        """'tomorrow' is phrasing date_resolver already resolves — the LLM
        must never be consulted for it. _call_llm is deliberately left
        UNMOCKED: if _resolve_date_range fell through to the LLM fallback for
        this phrasing, the test would crash on a real network call instead
        of silently passing, the same verification style already used by
        test_status_branch_skips_date_extraction_when_no_date_mentioned."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        from datetime import timedelta
        today = leave_action_service._today_in_app_timezone()
        tomorrow = (today + timedelta(days=1)).isoformat()
        day_after = (today + timedelta(days=2)).isoformat()

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 35, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": day_after, "to_date": day_after, "status": 0, "status_name": "pending"},
                {"id": 34, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": tomorrow, "to_date": tomorrow, "status": 0, "status_name": "pending"},
            ]}}}
        # This branch now calls the /leave/applied endpoint (get_applied_
        # leaves), not the retired /leave/pending one (get_leave_status) —
        # see MEMORY's /leave/applied endpoint migration note.
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show my leave status for tomorrow", "leave_status",
                       has_date_expression=True),
            writer,
        )

        status_events = writer.of_type("leave_status")
        returned_leaves = status_events[0]["data"]["leaves"]
        assert len(returned_leaves) == 1
        assert returned_leaves[0]["id"] == 34
        assert tomorrow in result["response_text"]

    async def test_status_branch_skips_date_extraction_when_no_date_mentioned(self, monkeypatch, fake_slots):
        """No date phrase in the query — _resolve_date_range_phrase returns
        (None, None) and every leave is returned unfiltered, no date
        narrowing applied."""
        """The date-filter resolution must never fire for the common
        no-date-mentioned query — verified by NOT mocking _call_llm at all;
        if the gate (state["has_date_expression"], False by default here via
        base_state) were broken, this would crash trying to make a real
        network call instead of quietly returning all leaves."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "pending"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 1, "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
                 "from_date": "2026-08-21", "to_date": "2026-08-21", "status": "0", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("what's the status of my leave", "leave_status"), writer
        )

        assert len(writer.of_type("leave_status")[0]["data"]["leaves"]) == 1
        assert "pending" in result["response_text"]

    async def test_status_branch_filter_with_no_matches(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leave_status": leave_status, "total_leaves": 0, "leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me my rejected leaves", "leave_status"), writer
        )

        assert len(writer.of_type("leave_status")[0]["data"]["leaves"]) == 0

    async def test_non_pending_filter_is_now_answerable(self, monkeypatch, fake_slots):
        """erp-api's new /leave/applied endpoint (live 2026-08-20) can answer
        'show me my rejected leaves' for real now — the old blanket refusal
        (pending-only /leave/pending couldn't) is gone."""
        # test body continued after this in-file (not part of the conflict block)

        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "rejected"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 50, "leave_type": "Casual Leave", "from_date": "2026-07-01", "to_date": "2026-07-01",
                 "status": "2", "status_name": "rejected", "rejection_reason": "Team short-staffed that week"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me my rejected leaves", "leave_status"), writer
        )

        assert "only show your pending" not in result["response_text"].lower()
        assert "rejected" in result["response_text"]
        assert "Team short-staffed that week" in result["response_text"]

    @pytest.mark.parametrize("query", [
        "is my leave approved",
        "was my leave rejected",
        "did HR approve my leave",
        "has my leave been accepted yet",
    ])
    async def test_status_questions_now_get_a_precise_real_answer(
        self, monkeypatch, fake_slots, query,
    ):
        """Live bug (original): 'is my leave approved' contained the word
        'approved', so it hit the SAME refusal built for explicit 'show me
        my approved leaves' requests. Now upgraded further: since
        /leave/applied?leave_status=all can see every status, a status
        question gets the REAL, precise answer — no more 'I can only see
        pending, check the Leave module' hedging."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "all"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 40, "leave_type": "Casual Leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
                 "status": "1", "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state(query, "leave_status"), writer)

        assert "only show your pending" not in result["response_text"].lower()
        assert "check the Leave module" not in result["response_text"]
        assert "is approved" in result["response_text"]

    async def test_status_question_with_no_match_gives_honest_answer_not_generic_zero(
        self, monkeypatch, fake_slots,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("is my leave approved", "leave_status"), writer)

        assert "couldn't find a matching leave request" in result["response_text"].lower()
        assert result["response_text"] != "You currently have no pending leave requests."

    async def test_explicit_approved_filter_request_now_answered(self, monkeypatch, fake_slots):
        """Regression guard for the other direction: an EXPLICIT request to
        see approved leaves ('show me my approved leaves') now gets real
        data via /leave/applied?leave_status=approved."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "approved"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 41, "leave_type": "Sick Leave", "from_date": "2026-06-01", "to_date": "2026-06-01",
                 "status": "1", "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me my approved leaves", "leave_status"), writer
        )

        assert "only show your pending" not in result["response_text"].lower()
        assert "Sick Leave" in result["response_text"]

    async def test_status_question_with_multiple_matches_asks_which_one(
        self, monkeypatch, fake_slots, fake_disambiguation_state,
    ):
        """'is my leave approved' with 2+ matching candidates is genuinely
        ambiguous — must ask which one instead of dumping every status in
        one line (that's what a LIST request like 'show me my pending
        leaves' gets, not a singular status question)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-07-30", "2026-07-30"),
                _pending_leave(2, "Sick Leave", "2026-08-14", "2026-08-15"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("is my leave approved", "leave_status"), writer)

        assert "which one" in result["response_text"].lower()
        assert "Casual Leave" in result["response_text"]
        assert "Sick Leave" in result["response_text"]
        stored = fake_disambiguation_state.get_candidates(1, "conv-1")
        assert stored is not None and len(stored) == 2

    async def test_status_question_narrows_to_the_one_named_status_among_mixed_records(
        self, monkeypatch, fake_slots,
    ):
        """Live bug (2026-08-20): 'give me reason for why my leave was
        rejected' against an account with many leaves of mixed status was
        dumping ALL of them as 'which one?' instead of narrowing to the
        rejected one. With exactly one rejected record among several others,
        the question must narrow to it and answer directly — including the
        rejection reason — with no disambiguation step at all."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-07-30", "2026-07-30"),
                {**_pending_leave(2, "Sick Leave", "2026-08-05", "2026-08-06"),
                 "status_name": "rejected", "rejection_reason": "Insufficient notice given"},
                {**_pending_leave(3, "Earned Leave", "2026-08-14", "2026-08-15"), "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("give me reason for why my leave was rejected", "leave_status"), writer
        )

        assert "which one" not in result["response_text"].lower()
        assert "Sick Leave" in result["response_text"]
        assert "Insufficient notice given" in result["response_text"]
        assert "Casual Leave" not in result["response_text"]
        assert "Earned Leave" not in result["response_text"]

    async def test_status_question_narrowing_only_offers_matching_status_when_still_ambiguous(
        self, monkeypatch, fake_slots, fake_disambiguation_state,
    ):
        """Two rejected records plus an unrelated approved one — narrowing by
        the asked status must still ask 'which one', but only among the
        rejected pair, not all three."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(1, "Casual Leave", "2026-07-30", "2026-07-30"), "status_name": "rejected"},
                {**_pending_leave(2, "Sick Leave", "2026-08-05", "2026-08-06"), "status_name": "rejected"},
                {**_pending_leave(3, "Earned Leave", "2026-08-14", "2026-08-15"), "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("why was my leave rejected", "leave_status"), writer
        )

        assert "which one" in result["response_text"].lower()
        assert "Casual Leave" in result["response_text"]
        assert "Sick Leave" in result["response_text"]
        assert "Earned Leave" not in result["response_text"]
        stored = fake_disambiguation_state.get_candidates(1, "conv-1")
        assert stored is not None and len(stored) == 2

    async def test_status_question_with_leave_type_narrows_before_status(
        self, monkeypatch, fake_slots,
    ):
        """'why was my sick leave rejected' must narrow by leave type FIRST
        (down to the one Sick Leave record), then by status — combining both
        signals instead of only using one."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(1, "Sick Leave", "2026-07-30", "2026-07-30"),
                 "leave_type_slug": "sick_leave", "status_name": "approved"},
                {**_pending_leave(2, "Sick Leave", "2026-08-05", "2026-08-06"), "leave_type_slug": "sick_leave",
                 "status_name": "rejected", "rejection_reason": "Team short-staffed that week"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("why was my sick leave rejected", "leave_status"), writer
        )

        assert "which one" not in result["response_text"].lower()
        assert "Team short-staffed that week" in result["response_text"]

    async def test_status_question_narrowing_to_zero_falls_back_to_full_set(
        self, monkeypatch, fake_slots, fake_disambiguation_state,
    ):
        """Nobody's leave is actually rejected — narrowing to 'rejected'
        would eliminate every candidate, so it must fall back to the
        unnarrowed set and ask 'which one', not falsely report 'not found'."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-07-30", "2026-07-30"),
                {**_pending_leave(2, "Sick Leave", "2026-08-05", "2026-08-06"), "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("why was my leave rejected", "leave_status"), writer
        )

        assert "couldn't find a matching leave request" not in result["response_text"].lower()
        assert "which one" in result["response_text"].lower()

    async def test_list_request_with_multiple_pending_still_lists_them_all(
        self, monkeypatch, fake_slots, fake_disambiguation_state,
    ):
        """Negative control: 'show me my pending leaves' is a LIST request,
        not a singular status question — must keep the existing summarized
        list behavior, not start asking 'which one'."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "pending"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-07-30", "2026-07-30"),
                _pending_leave(2, "Sick Leave", "2026-08-14", "2026-08-15"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("show me my pending leaves", "leave_status"), writer)

        assert "which one" not in result["response_text"].lower()
        assert "Casual Leave" in result["response_text"]
        assert "Sick Leave" in result["response_text"]
        assert fake_disambiguation_state.get_candidates(1, "conv-1") is None

    @pytest.mark.parametrize("reply,expected_type", [
        ("the casual leave one", "Casual Leave"),
        ("the sick leave", "Sick Leave"),
        ("2026-07-30", "Casual Leave"),
        ("the 14th", "Sick Leave"),
    ])
    async def test_disambiguation_reply_resolves_to_the_right_leave(
        self, monkeypatch, fake_slots, fake_disambiguation_state, reply, expected_type,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_disambiguation_state.set_candidates(1, "conv-1", [
            {**_build_test_card(1, "Casual Leave", "2026-07-30", "2026-07-30", role="Manager")},
            {**_build_test_card(2, "Sick Leave", "2026-08-14", "2026-08-15", role="HR")},
        ])
        status_mock = MagicMock(side_effect=AssertionError("must not re-fetch — candidates already have full data"))
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", status_mock)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state(reply, "leave_status"), writer)

        assert expected_type in result["response_text"]
        assert fake_disambiguation_state.get_candidates(1, "conv-1") is None  # resolved, cleared

    async def test_unresolvable_disambiguation_reply_falls_back_without_guessing(
        self, monkeypatch, fake_slots, fake_disambiguation_state, fake_history_clarify_state,
    ):
        fake_disambiguation_state.set_candidates(1, "conv-1", [
            {**_build_test_card(1, "Casual Leave", "2026-07-30", "2026-07-30", role="Manager")},
            {**_build_test_card(2, "Sick Leave", "2026-08-14", "2026-08-15", role="HR")},
        ])
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("never mind, something else", "leave_status"), writer)

        # Cleared rather than left stale. The fallback reply carries no
        # status/all/question signal of its own, so it now falls through to
        # the "which leaves?" clarify (never silently guesses which
        # candidate was meant, and never silently defaults either).
        assert fake_disambiguation_state.get_candidates(1, "conv-1") is None
        assert "make sure i get you the right info" in result["response_text"].lower()
        assert fake_history_clarify_state.get_state(1, "conv-1") is not None

    async def test_disambiguation_reply_routes_through_classify_node(self, fake_disambiguation_state):
        """classify_node's own fast-path — a bare 'the casual leave one' has
        no HR keywords in it at all, so without the stored candidates it
        would never reach leave_action_node."""
        fake_disambiguation_state.set_candidates(1, "conv-1", [
            _build_test_card(1, "Casual Leave", "2026-07-30", "2026-07-30", role="Manager"),
        ])
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("the casual leave one", intent="general"), writer)

        assert result["intent"] == "leave_status"

    async def test_status_branch_no_leaves(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("what's the status of my leave", "leave_status"), writer)

        assert "You currently have no pending leave requests." in result["response_text"]

    async def test_status_branch_multiple_leaves_summarized(self, monkeypatch, fake_slots):
        """'leave status' defaults to pending (unchanged) — two PENDING
        records get summarized in one message (a display-formatting check,
        not specifically about mixed statuses)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "pending"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 31, "leave_type": "Casual Leave", "from_date": "2026-08-08", "to_date": "2026-08-08",
                 "status": "0", "status_name": "pending"},
                {"id": 30, "leave_type": "Sick Leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
                 "status": "0", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("leave status", "leave_status"), writer)

        assert "Casual Leave" in result["response_text"]
        assert "Sick Leave" in result["response_text"]
        assert "pending" in result["response_text"]

    async def test_status_branch_timeout_gives_clean_message(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _timeout(token, leave_status="all", **kwargs):
            raise ErpApiTimeout("timed out")
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _timeout)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("leave status", "leave_status"), writer)

        assert "try again" in result["response_text"].lower()
        assert writer.of_type("leave_status") == []

    async def test_manager_sees_own_pending_requests_not_blocked(self, monkeypatch, fake_slots):
        """AC5 fix: a manager asking about pending leave requests must see
        their OWN submitted requests, same as any employee — get_applied_leaves
        is always scoped to the caller's own token, so this never leaks a
        team-approval view. Only leave_balance/apply_leave remain restricted
        for managers (see TestLeaveActionNodeRoleGate)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "pending"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 40, "leave_type": "Casual Leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
                 "status": "0", "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        assert writer.of_type("done")[0]["intent"] == "leave_status"
        status_events = writer.of_type("leave_status")
        assert len(status_events) == 1
        assert status_events[0]["data"]["leaves"][0]["leave_type"] == "Casual Leave"
        assert "Casual Leave" in result["response_text"]


# ═════════════════════════════════════════════════════════════════════════════
# HEL-281 — mandatory fields, display limit / "View More", follow-up suggestions
# ═════════════════════════════════════════════════════════════════════════════

def _pending_leave(id_, leave_type, from_date, to_date):
    return {"id": id_, "leave_type": leave_type, "from_date": from_date, "to_date": to_date,
            "status": 0, "status_name": "pending"}


def _build_test_card(id_, leave_type, from_date, to_date, role=None):
    """Builds a real, fully-normalized card via the actual production
    _build_leave_card — used to seed fake_disambiguation_state directly,
    since that store holds already-built cards, not raw erp-api records."""
    raw = {"id": id_, "leave_type": leave_type, "from_date": from_date, "to_date": to_date,
           "status_name": "pending"}
    if role:
        raw["role"] = role
    return leave_action_service._build_applied_leave_card(raw)


class TestLeaveActionNodePendingRequestCards:

    async def test_card_falls_back_to_date_span_when_leave_count_is_omitted(
        self, monkeypatch, fake_slots,
    ):
        """/leave/applied normally includes leave_count directly, but the
        card must still degrade gracefully (computed date-span estimate,
        synthesized LR-<id> reference) if a payload ever omits it."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-08-10", "2026-08-11"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["total_days"] == 2.0
        assert card["reference"] == "LR-2041"
        assert "2 day" in result["response_text"] or "2.0 day" in result["response_text"]

    async def test_card_uses_leave_count_directly_once_provided(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2057, "Sick Leave", "2026-08-14", "2026-08-15"), "leave_count": "2"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["total_days"] == "2"

    async def test_card_prefers_total_days_over_leave_count(self, monkeypatch, fake_slots):
        """Live-confirmed 2026-08-21: /leave/applied now returns total_days
        directly (erp-api's own authoritative figure, correct for half-days
        unlike a date-span estimate) alongside the older leave_count field.
        total_days must win when both are present."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2064, "Short Leave", "2026-08-21", "2026-08-21"),
                 "total_days": 0.5, "leave_count": "1"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("do i have any pending leave requests", "leave_status"), writer)

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["total_days"] == 0.5

    async def test_card_carries_approver_name_and_role(self, monkeypatch, fake_slots):
        """Live-confirmed 2026-08-21: /leave/applied now returns
        approver_name and role for pending/approved/rejected AND cancelled
        records alike — the raw fields land on the card regardless of
        status. Deliberately NOT surfaced in the message text for a
        cancelled record though (see test_cancelled_status_never_names_an_approver):
        cancellation is employee-initiated via our own cancel_leave flow,
        not something the approver "did", so this only checks the card
        carries the raw fields, not that the message repeats them."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2064, "Short Leave", "2026-08-21", "2026-08-21"),
                 "status_name": "cancelled", "approver_name": "A GeoFencing", "role": "manager"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me all my leaves", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["approver_name"] == "A GeoFencing"
        assert card["approver_role"] == "manager"

    async def test_card_omits_approver_fields_when_erp_api_doesnt_send_them(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2065, "Casual Leave", "2026-08-22", "2026-08-22"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["approver_name"] is None
        assert "Approver" not in result["response_text"]

    @pytest.mark.parametrize("role,expected_label", [
        ("manager", "Pending with Manager"),
        ("hr", "Pending with HR"),
        ("HR", "Pending with HR"),
    ])
    async def test_pending_card_names_the_actual_approval_stage(
        self, monkeypatch, fake_slots, role, expected_label,
    ):
        """Mockup repro: 'Do I have any pending leave requests?' must show
        which stage a request is at ('Pending with Manager' / 'Pending with
        HR'), not a generic 'Pending Approval' — driven by erp-api's own
        role field, never a hardcoded two-stage guess."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"), "role": role},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["status_label"] == expected_label
        assert expected_label.lower() in result["response_text"].lower()

    async def test_pending_card_names_the_approver_by_name_when_erp_api_sends_one(
        self, monkeypatch, fake_slots,
    ):
        """'Pending with Manager' alone doesn't say WHO — when erp-api sends
        both a role and the approver's actual name, the chip/status_label
        must show both ('Pending with John Smith (Manager)'), and the prose
        message must not then repeat the name a second time in a separate
        'Approver: ...' sentence."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
                 "role": "manager", "approver_name": "John Smith"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["status_label"] == "Pending with John Smith (Manager)"
        # Mid-sentence: lowercase leading word, name/role casing preserved.
        assert "is pending with John Smith (Manager)" in result["response_text"]
        # Not repeated as a separate "Approver: John Smith (Manager)." sentence.
        assert result["response_text"].count("John Smith") == 1

    async def test_pending_card_names_the_approver_without_a_role(self, monkeypatch, fake_slots):
        """erp-api sends a name but no role — show the name alone rather
        than silently dropping it."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
                 "approver_name": "John Smith"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["status_label"] == "Pending with John Smith"

    async def test_pending_card_falls_back_to_generic_label_without_a_role(self, monkeypatch, fake_slots):
        """erp-api omitting role entirely (older payload shape, or a request
        type this doesn't apply to) must not invent which stage it's at."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["status_label"] == "Pending Approval"
        assert "pending" in result["response_text"].lower()
        assert "pending with" not in result["response_text"].lower()

    @pytest.mark.parametrize("status_name,expected_label", [
        ("approved", "Approved by John Smith (Manager)"),
        ("rejected", "Rejected by John Smith (Manager)"),
    ])
    async def test_decided_status_names_the_approver_by_name_and_role_too(
        self, monkeypatch, fake_slots, status_name, expected_label,
    ):
        """Not just pending — approved/rejected records must also fold the
        approver's name and role into status_label ('Approved by John Smith
        (Manager)'), the same way pending does ('Pending with John Smith
        (Manager)'), instead of a bare 'Approved'/'Rejected' with the name
        only available in a separate sentence. Cancelled is deliberately
        excluded — see test_cancelled_status_never_names_an_approver."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2057, "Sick Leave", "2026-08-14", "2026-08-15"),
                 "status_name": status_name, "approver_name": "John Smith", "role": "manager"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me all my leaves", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["status_label"] == expected_label
        # Mid-sentence: lowercase leading word, name/role casing preserved,
        # and not repeated as a separate "Approver: ..." sentence.
        assert f"is {expected_label[0].lower()}{expected_label[1:]}" in result["response_text"]
        assert result["response_text"].count("John Smith") == 1

    async def test_decided_status_falls_back_to_plain_label_without_approver_info(
        self, monkeypatch, fake_slots,
    ):
        """erp-api sending neither a role nor a name for a decided record
        must not invent one — falls back to the plain 'Approved' wording."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2057, "Sick Leave", "2026-08-14", "2026-08-15"), "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me all my leaves", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["status_label"] == "Approved"
        assert "approved by" not in result["response_text"].lower()

    async def test_cancelled_status_never_names_an_approver(self, monkeypatch, fake_slots):
        """Cancellation is employee-initiated via our own cancel_leave flow,
        not an action an approver takes — status_label must stay the plain
        'Cancelled' even when erp-api still sends a role/name on the record
        (e.g. the approver it had been routed to before it was cancelled),
        unlike approved/rejected which DO fold that in."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2057, "Sick Leave", "2026-08-14", "2026-08-15"),
                 "status_name": "cancelled", "approver_name": "John Smith", "role": "manager"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me all my leaves", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["status_label"] == "Cancelled"
        assert "John Smith" not in result["response_text"]

    async def test_rejected_reason_shown_inline_short_with_approver(self, monkeypatch, fake_slots):
        """Rejected + reason + approver combine into one short line — status,
        approver name/role, and reason all in the same clause, rather than a
        separate 'Reason given:' or 'Approver:' sentence."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(64, "Short Leave", "2026-08-21", "2026-08-21"),
                 "status_name": "rejected", "rejection_reason": "fever",
                 "approver_name": "A GeoFencing", "role": "manager"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me all my leaves", "leave_status"), writer
        )

        answer = result["response_text"]
        assert "is rejected by A GeoFencing (Manager) — fever." in answer
        assert "Reason given" not in answer
        # Not repeated as a separate "Approver: ..." sentence.
        assert answer.count("A GeoFencing") == 1

    async def test_card_carries_a_leave_type_code_and_a_design_worded_status_label(
        self, monkeypatch, fake_slots,
    ):
        """Matches the Cancel Leave Request card design: 'Casual Leave (CL)'
        and 'Pending Approval' rather than the bare title-cased status."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-08-07", "2026-08-07"),
                 "leave_type_slug": "casual_leave"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["leave_type_code"] == "CL"
        assert card["status_label"] == "Pending Approval"

    async def test_card_date_label_shows_weekday_for_a_single_day(self, monkeypatch, fake_slots):
        """Figma repro: 'Thu, 30 Jul 2026' — weekday shown for a one-day
        request, since there's no ambiguity about which day it refers to."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("do i have any pending leave requests", "leave_status"), writer)

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["date_label"] == "Thu, 30 Jul 2026"

    async def test_card_date_label_shows_weekday_on_both_ends_for_a_range(self, monkeypatch, fake_slots):
        """A real multi-day range now shows the weekday on BOTH ends, not
        just the single-day case — 'Fri, 14 Aug - Sat, 15 Aug 2026' (live
        UX request, 2026-08-24), not the old compressed '14 – 15 Aug 2026'."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2057, "Sick Leave", "2026-08-14", "2026-08-15"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("do i have any pending leave requests", "leave_status"), writer)

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["date_label"] == "Fri, 14 Aug - Sat, 15 Aug 2026"

    async def test_card_submitted_at_label_has_no_weekday(self, monkeypatch, fake_slots):
        """Figma repro: 'Applied on 28 Jul 2026' — no weekday on the applied
        date, distinct from the leave date(s) above it."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"), "applied_date": "2026-07-28"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("do i have any pending leave requests", "leave_status"), writer)

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["submitted_at_label"] == "28 Jul 2026"

    async def test_preview_and_success_cards_carry_the_date_label_too(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """date_label/submitted_at_label come from _build_applied_leave_card,
        which both the cancel preview and success cards are built on top
        of (via **selected) — confirms the formatting reaches those cards
        too, not just the plain leave-status list."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-08-07", "2026-08-07"),
                 "leave_type_slug": "casual_leave", "applied_date": "2026-07-28"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["date_label"] == "Fri, 07 Aug 2026"
        assert preview["submitted_at_label"] == "28 Jul 2026"

    async def test_card_leave_type_code_is_none_for_an_unmapped_slug(self, monkeypatch, fake_slots):
        """No guessing at a code for a type outside the known table — None is
        the correct, honest answer, not a fabricated abbreviation."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2099, "Bereavement Leave", "2026-08-07", "2026-08-07"),
                 "leave_type_slug": "bereavement_leave"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        card = writer.of_type("leave_status")[0]["data"]["leaves"][0]
        assert card["leave_type_code"] is None

    async def test_rejected_leave_includes_the_rejection_reason(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "rejected"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
                 "status_name": "rejected", "rejection_reason": "Insufficient notice given"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me my rejected leaves", "leave_status"), writer
        )

        assert "rejected" in result["response_text"]
        assert "Insufficient notice given" in result["response_text"]


class TestLeaveActionNodeShowsEverythingInOneResponse:
    """No more artificial 5-item cap / "view more" pagination (removed
    2026-08-20 per explicit request) — a listing always returns every
    matching leave in one response, so total_count == len(leaves) and
    has_more is always False."""

    async def test_large_list_is_returned_in_full_not_capped(self, monkeypatch, fake_slots):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(2, "Sick Leave", "2026-08-02", "2026-08-02"),
                _pending_leave(3, "Earned Leave", "2026-08-03", "2026-08-03"),
                _pending_leave(4, "Comp Off", "2026-08-04", "2026-08-04"),
                _pending_leave(5, "Casual Leave", "2026-08-05", "2026-08-05"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        data = writer.of_type("leave_status")[0]["data"]
        assert len(data["leaves"]) == 5
        assert data["total_count"] == 5
        assert data["display_limit"] == 5
        assert data["has_more"] is False
        assert "showing" not in result["response_text"].lower()
        for leave_type in ("Casual Leave", "Sick Leave", "Earned Leave", "Comp Off"):
            assert leave_type in result["response_text"]

    async def test_bare_more_is_not_misrouted_now_that_pagination_is_gone(self, fake_slots):
        """'show me more' has no HR keywords of its own — with the paging
        mechanism removed there's nothing to resume, so it must fall through
        to normal classification instead of being force-fed into leave_status."""
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("show me more", intent="general"), writer)

        assert result["intent"] != "leave_status"


class TestLeaveActionNodePendingRequestFollowUps:

    async def test_pending_results_get_balance_apply_and_cancel_suggestions(
        self, monkeypatch, fake_slots,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("do i have any pending leave requests", "leave_status"), writer)

        suggestions = writer.of_type("leave_status")[0]["data"]["suggestions"]
        assert "Would you like to check your leave balance?" in suggestions
        assert "Would you like to apply for leave?" in suggestions
        assert "You can also ask me to cancel a pending or approved request." in suggestions

    async def test_zero_pending_gets_balance_and_apply_suggestions_but_not_cancel(
        self, monkeypatch, fake_slots,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("do i have any pending leave requests", "leave_status"), writer
        )

        suggestions = writer.of_type("leave_status")[0]["data"]["suggestions"]
        assert "Would you like to check your leave balance?" in suggestions
        assert "Would you like to apply for leave?" in suggestions
        assert "cancel" not in " ".join(suggestions).lower()
        assert result["response_text"].startswith("You currently have no pending leave requests.")

    async def test_unfiltered_query_still_gets_cancel_suggestion(self, monkeypatch, fake_slots):
        """/leave/pending only ever returns pending requests, so an unfiltered
        'what's my leave status' (no explicit 'pending' word) must still get
        the cancel suggestion — the results ARE pending regardless of wording,
        since a non-pending filter word is refused before erp-api is even called."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 9, "leave_type": "Casual Leave", "from_date": "2026-07-01", "to_date": "2026-07-01",
                 "status": 0, "status_name": "pending"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("what's the status of my leave", "leave_status"), writer)

        suggestions = writer.of_type("leave_status")[0]["data"]["suggestions"]
        assert "You can also ask me to cancel a pending or approved request." in suggestions

    async def test_non_pending_filter_is_now_answered_via_leave_applied(
        self, monkeypatch, fake_slots,
    ):
        """erp-api's new /leave/applied endpoint (live 2026-08-20) can answer
        'approved'/'rejected'/'cancelled' filters for real now — the old
        blanket refusal (pending-only /leave/pending couldn't) is gone."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            assert leave_status == "approved"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 9, "leave_type": "Casual Leave", "from_date": "2026-07-01", "to_date": "2026-07-01",
                 "status": "1", "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("show me my approved leaves", "leave_status"), writer
        )

        assert writer.of_type("leave_status") != []
        assert "only show your pending" not in result["response_text"].lower()
        assert "Casual Leave" in result["response_text"]


# ═════════════════════════════════════════════════════════════════════════════
# cancel_leave — real Match -> Select -> Preview -> Confirm flow (only the
# final erp-api write is stubbed — no cancel-leave endpoint exists yet)
# ═════════════════════════════════════════════════════════════════════════════

def _cancel_extraction(date=None, date_to=None, leave_type=None, request_id=None, is_affirmative=False, reason=None):
    return {"date": date, "date_to": date_to, "leave_type": leave_type, "request_id": request_id,
            "is_affirmative": is_affirmative, "reason": reason}


def _quota(slug="casual_leave", remaining="5", total="12"):
    return {"http_status": 200, "body": {"success": True, "data": {
        "leave_quota": {slug: {"total": total, "remaining": remaining}},
    }}}


class TestLeaveActionNodeCancelBranch:

    async def test_manager_can_reach_cancel_branch_too(self, monkeypatch, fake_slots, fake_cancel_state):
        """Full self-service for managers (this session's other fix) applies
        here as well — no role gate on cancel_leave."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota()
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel my leave", "cancel_leave"), writer
        )

        assert writer.of_type("done")[0]["intent"] == "cancel_leave"
        assert "Casual Leave" in result["response_text"]

    async def test_zero_pending_says_theres_nothing_to_cancel(self, monkeypatch, fake_slots, fake_cancel_state):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert "don't have any leave requests to cancel" in result["response_text"]
        # No leave data at all in this turn — distinct from "cancelled",
        # which stays False on every non-completing turn regardless.
        assert writer.of_type("done")[0]["data"]["leave_to_cancel"] is False

    async def test_single_pending_unambiguous_query_goes_straight_to_preview(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """A single active request needs no disambiguation (AC#1) — the
        employee should see the balance-impact preview and confirmation
        prompt directly (AC#2), not a stub refusal."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
                 "leave_type_slug": "casual_leave"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2041"
        assert preview["current_balance"] == "5"
        # This request is still PENDING (not yet approved) — erp-api only
        # ever deducts balance on approval, so nothing was deducted and
        # nothing is restored by cancelling it. Live bug (2026-08-25): this
        # used to show "1"/"6" here unconditionally (the leave's own
        # duration reused as the restored-days figure), producing a false
        # "+1 day restored" for a request whose balance was never touched.
        assert preview["days_to_restore"] == "0"
        assert preview["projected_balance"] == "5"
        assert preview["balance_restored"] is False
        assert preview["balance_impact_note"] == (
            "This request hasn't been approved yet, so no days were deducted — "
            "cancelling it won't change your Casual Leave (CL) balance."
        )
        assert "LR-2041" in result["response_text"]
        assert "cancel this request" in result["response_text"].lower()
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "awaiting_confirmation"
        # Says the balance is unchanged in plain words, not a "5 -> 5" arrow.
        assert "unchanged" in result["response_text"].lower()
        assert "hasn't been approved yet" in result["response_text"]

    async def test_approved_leave_preview_shows_the_real_balance_restoration(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The counterpart to the pending case above — an APPROVED leave
        genuinely had its balance deducted, so cancelling it really does
        restore those days. This is the one case where the "+X day(s)
        restored" note and the balance increase are both correct."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                # Dated ahead of "today" — this test is about restoration
                # MATH for an approved leave, not the separate approved+
                # backdated cancellation block (see
                # TestApprovedBackdatedCancelBlock), so this candidate must
                # still be normally previewable.
                {**_pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"),
                 "leave_type_slug": "casual_leave", "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        # _fmt_days-normalized (matches total_days elsewhere) — a whole
        # number renders as "1"/"6", never "1.0"/"6.0".
        assert preview["days_to_restore"] == "1"
        assert preview["projected_balance"] == "6"
        assert preview["balance_restored"] is True
        assert preview["balance_impact_note"] == "+1 day restored to Casual Leave (CL)"
        # Names the leave type instead of generic "day(s)" ("5 day(s) ->
        # ... 6 day(s)"), and pluralizes correctly on both sides. Also states
        # the "+1 day restored" count explicitly alongside the before/after
        # numbers, not just the numbers alone — the spoken counterpart to
        # the pending branch explicitly saying why it ISN'T restoring.
        assert (
            "Current balance: 5 Casual Leaves -> after cancellation: 6 Casual Leaves "
            "(+1 day restored to Casual Leave (CL))."
        ) in result["response_text"]
        # The spoken sentence uses the same Figma-formatted date as the card
        # (preview["date_label"]) instead of the raw "2026-07-30 to
        # 2026-07-30" ISO pair — a live gap found 2026-08-25: the card and
        # the chat bubble disagreed on how the date was shown.
        assert preview["date_label"] == "Mon, 14 Jun 2027"
        assert "Mon, 14 Jun 2027" in result["response_text"]
        assert "2027-06-14 to 2027-06-14" not in result["response_text"]

    async def test_preview_card_carries_employee_identity(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The cancel-leave card should identify who it belongs to: the
        numeric id needs no extra call (it's the JWT's user_id, already
        `company_id` in state), and `name` comes best-effort from
        /ai/leave/context."""
        async def _context(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "is_manager": False, "name": "B Geo"}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _context)

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["employee"] == {"user_id": 1, "name": "B Geo", "emp_code": "1"}

    async def test_preview_card_uses_erp_apis_real_emp_code_when_present(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live-confirmed 2026-08-21: /ai/leave/context now returns emp_no
        (e.g. 'geo3') — the real, human-readable employee code. It must win
        over the synthesized '<user_id>' fallback."""
        async def _context(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "is_manager": False, "name": "B Geo", "emp_no": "geo3"}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _context)

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["employee"] == {"user_id": 1, "name": "B Geo", "emp_code": "geo3"}

    async def test_preview_card_carries_leave_type_code_and_status_label(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Matches the Cancel Leave Request card design: 'Casual Leave (CL)'
        and 'Pending Approval', not just the raw type name/status."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-08-07", "2026-08-07"),
                 "leave_type_slug": "casual_leave"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["leave_type_code"] == "CL"
        assert preview["status_label"] == "Pending Approval"

    async def test_preview_shown_when_context_has_no_name(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The role-gate context call is the ONLY /ai/leave/context call in
        this flow — if it succeeds but the payload has no `name` (as most
        fixtures in this file model), the card still renders with the
        numeric identifier and a null name, never a blocked preview."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["employee"] == {"user_id": 1, "name": None, "emp_code": "1"}
        assert "cancel this request" in result["response_text"].lower()

    async def test_multiple_pending_vague_query_asks_for_selection(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """AC#1 — Helix AI must not automatically select a request when the
        query is ambiguous; it must show the matching requests and ask."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(2, "Sick Leave", "2026-08-02", "2026-08-02"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        requests = writer.of_type("leave_cancellation_selection")[0]["data"]["requests"]
        assert len(requests) == 2
        # A "which leave do you mean?" response is a QUESTION, not a
        # resolved action — distinct from cancel_leave, which covers
        # preview/confirm/execute once matched to exactly one request. Must
        # also be in main._STATEFUL_QUERY_INTENTS (this depends on the live
        # candidate list exactly like cancel_leave does).
        assert writer.of_type("done")[0]["intent"] == "cancel_ask"

    async def test_multiple_type_matches_asks_for_the_missing_date_or_reference(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """'cancel my casual leave' matching 2 casual-leave records gets a
        targeted follow-up naming what's still needed, not the generic
        'pick by number or reference' meant for a truly vague query."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(2, "Casual Leave", "2026-08-10", "2026-08-10"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)
        mock_extraction(monkeypatch, _cancel_extraction(leave_type="casual_leave"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel my casual leave", "cancel_leave"), writer,
        )

        assert writer.of_type("done")[0]["intent"] == "cancel_ask"
        assert "You have multiple Casual Leave requests" in result["response_text"]
        assert "leave date, applied date, or reference ID" in result["response_text"]
        assert len(writer.of_type("leave_cancellation_selection")[0]["data"]["requests"]) == 2

    async def test_multiple_date_matches_asks_for_the_missing_type_or_reference(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """'cancel my leave on the 1st' matching a casual AND a sick leave
        both on that date gets the reverse targeted follow-up — asking for
        the leave type this time, not a date (already given)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(2, "Sick Leave", "2026-08-01", "2026-08-01"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-08-01"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel my leave on the 1st", "cancel_leave"), writer,
        )

        assert writer.of_type("done")[0]["intent"] == "cancel_ask"
        assert "You have multiple leave requests on 01 Aug 2026" in result["response_text"]
        assert "which leave type" in result["response_text"].lower()

    async def test_multiple_matches_with_both_type_and_date_asks_for_reference(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Both type AND date already given but still ambiguous (e.g.
        duplicate submissions) — nothing left to ask for but the reference
        ID directly."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(2, "Casual Leave", "2026-08-01", "2026-08-01"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)
        mock_extraction(monkeypatch, _cancel_extraction(leave_type="casual_leave", date="2026-08-01"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel my casual leave on the 1st", "cancel_leave"), writer,
        )

        assert writer.of_type("done")[0]["intent"] == "cancel_ask"
        assert "give me the reference ID" in result["response_text"]

    async def test_still_unresolved_selection_reply_stays_cancel_ask(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card1 = _build_test_card(1, "Casual Leave", "2026-08-01", "2026-08-01")
        card2 = _build_test_card(2, "Sick Leave", "2026-08-02", "2026-08-02")
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": [card1, card2]})

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("hmm not sure", "cancel_leave"), writer)

        assert "couldn't quite tell which request" in result["response_text"].lower()
        assert writer.of_type("done")[0]["intent"] == "cancel_ask"

    async def test_applied_date_matches_when_leave_date_does_not(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The disambiguation prompts now explicitly offer 'applied date' as
        a way to identify a request — it has to actually work, not just be
        a suggestion nothing implements. A date that matches when the leave
        was SUBMITTED (not its own from/to dates) must narrow correctly."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            leaves = [
                _pending_leave(1, "Casual Leave", "2026-08-24", "2026-08-24"),
                _pending_leave(2, "Sick Leave", "2026-08-29", "2026-08-29"),
            ]
            leaves[0]["applied_date"] = "2026-08-20"
            leaves[1]["applied_date"] = "2026-08-22"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": leaves}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        # Neither leave's OWN dates (24th/29th) are 22nd -- only leave #2's
        # submitted_at is.
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-08-22"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel the leave I applied for on 22 aug", "cancel_leave"), writer,
        )

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"

    async def test_selection_reply_naming_an_absolute_date_resolves_via_llm(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live bug report (2026-08-24): 'cancel my leave request for 24
        aug' as a reply to an already-shown selection list repeated 'I still
        couldn't tell which request you mean' forever, even though one of
        the listed candidates IS dated 2026-08-24. The selection-reply
        resolver used to run ONLY deterministic weekday/relative-day
        matching on the raw text — an absolute date like '24 aug' has no
        deterministic parser (same as the very first cancel turn), so it
        needs the same LLM-backed extraction _extract_cancel_fields uses."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card1 = _build_test_card(84, "Casual Leave", "2026-08-24", "2026-08-24")
        card2 = _build_test_card(83, "Sick Leave", "2026-08-29", "2026-08-29")
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": [card1, card2]})

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-08-24"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel my leave request for 24 aug", "cancel_leave"), writer,
        )

        assert "couldn't tell which request" not in result["response_text"].lower()
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-84"

    async def test_vague_query_offers_approved_leaves_too_not_just_pending(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """An approved future leave is a normal thing to cancel (erp-api's
        own /leave/cancel restores balance specifically for an APPROVED
        leave — pending hasn't even had balance deducted yet), so the vague
        picker must not silently hide it."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            approved = _pending_leave(2, "Casual Leave", "2026-09-25", "2026-09-25")
            approved["status_name"] = "approved"
            rejected = _pending_leave(3, "Sick Leave", "2026-08-01", "2026-08-01")
            rejected["status_name"] = "rejected"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
                approved,
                rejected,
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        requests = writer.of_type("leave_cancellation_selection")[0]["data"]["requests"]
        statuses = {r["status_name"] for r in requests}
        assert statuses == {"pending", "approved"}  # rejected must not appear

    async def test_explicit_reference_id_skips_selection_even_with_multiple_pending(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Matching priority #1 (LLD §6) — an explicit request ID narrows
        straight to one match and the preview, no selection step needed."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(2, "Sick Leave", "2026-08-02", "2026-08-02"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel LR-2", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"
        assert "LR-2" in result["response_text"]

    async def test_bare_number_after_leave_matches_by_reference_id(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live bug repro: 'cancel leave 78' has no LR-/# prefix at all, so
        it used to fall through to the vague 'show me every candidate' path
        instead of resolving straight to LR-78. Scoped to a number directly
        following 'leave'/'request' so it can't misfire on a day-count or a
        date elsewhere in the same query."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(77, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(78, "Sick Leave", "2026-08-02", "2026-08-02"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel leave 78", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-78"
        assert "LR-78" in result["response_text"]

    async def test_reference_id_wins_over_a_coincidentally_matching_date(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """'my LR code is 20 and the leave date is also 20' — ID matching is
        checked first and returns immediately once it finds a hit, so a
        bare 'cancel leave 20' resolves to LR-20 specifically, never to a
        different candidate that merely happens to fall on the 20th.
        Nothing is cancelled by this match alone — the preview still has to
        be confirmed, so a wrong guess here is corrected by the user, not
        silently executed."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(20, "Casual Leave", "2026-09-05", "2026-09-05"),
                _pending_leave(44, "Sick Leave", "2026-08-20", "2026-08-20"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel leave 20", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-20"
        assert preview["from_date"] == "2026-09-05"  # not the Aug-20 candidate

    async def test_hash_prefixed_reference_matches_with_a_leading_space(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live bug: \\b before '#' never matched '#2041' preceded by a
        space (the normal typed form, 'cancel #2041') — \\b needs a word/
        non-word transition, and space->'#' is non-word->non-word. Only the
        unusual no-space form ('cancel#2041') ever worked before."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(2041, "Sick Leave", "2026-08-02", "2026-08-02"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel #2041", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2041"

    async def test_day_count_and_date_are_never_misread_as_a_reference_id(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The bare-number id pattern only fires directly after 'leave'/
        'request' — a day-count ('for 3 days') or a date phrase ('on the
        20th') must still fall through to the vague multi-candidate list,
        not resolve to whichever record happens to share that number."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(3, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(20, "Sick Leave", "2026-08-02", "2026-08-02"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(
            base_state("cancel my leave for 3 days", "cancel_leave"), writer,
        )

        assert writer.of_type("leave_cancellation_preview") == []
        selection = writer.of_type("leave_cancellation_selection")[0]["data"]["requests"]
        assert len(selection) == 2  # never narrowed to LR-3

    async def test_type_match_with_mixed_statuses_narrows_to_the_one_cancellable_match(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Regression test for a live finding (2026-08-20): 'cancel my sick
        leave' matched 3 sick-leave records of different statuses (1
        approved, 2 already-cancelled) and showed all 3 as pick options —
        offering an already-cancelled record as a 'choice' is as unhelpful
        as it is for the vague-query case. When exactly one of several
        specific matches is actually cancellable, it must go straight to
        preview, not a selection list."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            # Dated ahead of "today" — this test is about narrowing to the
            # one cancellable match among mixed statuses, not the separate
            # approved+backdated cancellation block (see
            # TestApprovedBackdatedCancelBlock), so the approved record here
            # must still be a normal, previewable candidate.
            approved = _pending_leave(44, "Sick Leave", "2027-06-14", "2027-06-14")
            approved["status_name"] = "approved"
            cancelled1 = _pending_leave(31, "Sick Leave", "2026-08-18", "2026-08-18")
            cancelled1["status_name"] = "cancelled"
            cancelled2 = _pending_leave(42, "Sick Leave", "2026-12-01", "2026-12-01")
            cancelled2["status_name"] = "cancelled"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                approved, cancelled1, cancelled2,
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(leave_type="sick_leave"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my sick leave", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-44"
        assert preview["status_name"] == "approved"

    async def test_type_match_with_no_cancellable_candidates_reports_it_honestly(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Same scenario, but EVERY matching record is already decided (two
        sick-leave matches, both cancelled) — must say so and fall back to
        the general pending/approved list, not silently offer uncancellable
        records as choices."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            cancelled1 = _pending_leave(31, "Sick Leave", "2026-08-18", "2026-08-18")
            cancelled1["status_name"] = "cancelled"
            cancelled2 = _pending_leave(42, "Sick Leave", "2026-12-01", "2026-12-01")
            cancelled2["status_name"] = "cancelled"
            pending_other = _pending_leave(52, "Casual Leave", "2026-08-20", "2026-08-20")
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                cancelled1, cancelled2, pending_other,
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)
        mock_extraction(monkeypatch, _cancel_extraction(leave_type="sick_leave"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my sick leave", "cancel_leave"), writer)

        assert "already been decided" in result["response_text"].lower()
        requests = writer.of_type("leave_cancellation_selection")[0]["data"]["requests"]
        assert {r["reference"] for r in requests} == {"LR-52"}

    async def test_a_date_with_no_leave_history_at_all_reports_not_found_not_already_decided(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live bug report (2026-08-24): 'cancel my leave 1 jan 2020' —
        _extract_request_id's bare-ID pattern misread 'leave 1' (from '1 jan
        2020') as reference id=1, which happened to match an unrelated
        already-cancelled record (id=1) elsewhere in the employee's history.
        The response said 'already decided' for a date that has NO leave
        history at all, instead of the correct 'nothing found for that
        date'. A genuinely nonexistent date must never be misread as a bare
        reference number."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            # id=1 exists but is unrelated (long since decided) — the bug
            # was this record getting matched via a misparsed "id=1" at all.
            decided = _pending_leave(1, "Casual Leave", "2026-01-05", "2026-01-05")
            decided["status_name"] = "cancelled"
            pending = _pending_leave(52, "Sick Leave", "2026-08-20", "2026-08-20")
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                decided, pending,
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)
        mock_extraction(monkeypatch, _cancel_extraction(date="2020-01-01"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("i want to cancel my leave 1 jan 2020", "cancel_leave"), writer,
        )

        assert "already" not in result["response_text"].lower()
        assert "nothing on record fits it" in result["response_text"].lower()

    async def test_date_match_narrows_to_one_candidate(self, monkeypatch, fake_slots, fake_cancel_state):
        """Matching priority #2 (LLD §6) — an exact date narrows straight to
        one match even though the leave type wasn't mentioned."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"),
                _pending_leave(2, "Sick Leave", "2026-08-21", "2026-08-21"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-08-21"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave for Friday", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"
        # Live UX request (2026-08-24): the preview is asking for
        # CONFIRMATION first and foremost — the reason is only mentioned in
        # the same sentence as a heads-up, not a dedicated ask — so this
        # stays False here regardless of whether a reason is already known.
        # It only flips True once confirmation has actually happened and a
        # reason still needs its own turn (see the dedicated-ask tests).
        assert preview["ask_cancel_leave_reason"] is False
        assert writer.of_type("done")[0]["data"]["cancelled"] is False

    async def test_preview_flag_stays_false_even_when_a_reason_was_already_given(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2, "Sick Leave", "2026-08-21", "2026-08-21"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-08-21", reason="feeling better"))

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave for Friday, feeling better now", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["ask_cancel_leave_reason"] is False

    async def test_friday_resolves_deterministically_even_when_llm_extraction_fails(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Regression test for a live bug report (2026-08-20): 'cancel my
        leave request for Friday' failed to narrow down to the Friday date
        at all when the LLM's own date resolution didn't come through. The
        deterministic weekday fallback (_resolve_weekday_date) must resolve
        'Friday' on its own, with zero LLM involvement."""
        import datetime as _dt
        today = leave_action_service._today()
        friday = today + _dt.timedelta(days=(4 - today.weekday()) % 7)

        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-01-01", "2026-01-01"),
                {**_pending_leave(2, "Sick Leave", friday.isoformat(), friday.isoformat())},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        # Total extraction failure — same as the live incident.
        async def _broken_call_llm(prompt, max_tokens=None, model=None):
            raise RuntimeError("LLM provider unreachable")
        monkeypatch.setattr(leave_action_service, "_call_llm", _broken_call_llm)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave request for Friday", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"

    async def test_single_date_matches_a_multi_day_leaves_span_not_just_its_first_day(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """A leave doesn't have to be a single day: from_date=24th,
        to_date=26th is a real shape too. 'cancel my leave for 26 aug'
        (the LAST day of the span, not its first) must still match it."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-01-01", "2026-01-01"),
                _pending_leave(2, "Sick Leave", "2026-08-24", "2026-08-26"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-08-26"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel my leave for 26 aug", "cancel_leave"), writer,
        )

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"

    async def test_weekday_fallback_matches_any_day_within_a_multi_day_span(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Regression: the past-occurrence weekday fallback used to check
        only from_date's weekday, so a multi-day leave named by a LATER day
        in its own span ('cancel my leave for <weekday>') would never match
        even though its span does include that weekday. The span's end date
        is pinned to today (not a hardcoded literal) so the leave is never
        treated as backdated-and-blocked (_leave_date_has_passed requires
        the end date to be STRICTLY before today) regardless of which real
        calendar day the suite happens to run on."""
        import datetime as _dt
        today = leave_action_service._today()
        start = today - _dt.timedelta(days=2)
        # Names a day in the span whose weekday is neither from_date's (so
        # this still exercises the "later day in its own span" regression,
        # not just a from_date match) nor the fixed filler candidate's own
        # weekday (2026-01-01) — otherwise that single-day filler would
        # coincidentally also match on some real calendar days, turning
        # this into an ambiguous 2-candidate "selection" instead of one
        # clean "preview". A 3-day span always covers 3 distinct weekdays,
        # so at least one is safe from both exclusions.
        jan1_weekday = _dt.date(2026, 1, 1).weekday()
        query_day = next(
            d for d in (start, start + _dt.timedelta(days=1), today)
            if d.weekday() not in (start.weekday(), jan1_weekday)
        )
        query_weekday = query_day.strftime("%A").lower()
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-01-01", "2026-01-01"),
{**_pending_leave(2, "Sick Leave", start.isoformat(), today.isoformat()), "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        # LLM resolves the weekday to some far-off date that matches nothing.
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-09-02"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state(f"cancel my leave for {query_weekday}", "cancel_leave"), writer,
        )

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"

    async def test_bare_weekday_matches_a_past_occurrence_not_just_the_next_one(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live bug report (2026-08-24): 'cancel my leave request for
        friday' found nothing, because the only Friday leave on file was a
        few days BEHIND today, and the weekday resolver only ever computes
        the NEXT occurrence on/after today. A bare weekday name (no "next")
        must also match a candidate whose own date falls on that weekday,
        even when it's in the past."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-24", "2026-08-24"),
                # A Friday in the past relative to "today" (2026-08-24, a
                # Monday). Left as the default PENDING status — this test is
                # about the weekday-matching fallback, not the approved+
                # backdated cancellation block (see TestApprovedBackdatedCancelBlock
                # for that), and an approved record here would now hit that
                # separate rule and never reach a preview at all.
                _pending_leave(2, "Casual Leave", "2026-08-21", "2026-08-21"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        # Simulates the LLM resolving "friday" to the wrong (future) date,
        # exactly like the live incident — the deterministic fallback in
        # _match_cancel_candidates must still find the past Friday.
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-08-28"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave request for friday", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"
        assert 'matching "Friday"' in result["response_text"]

    async def test_found_one_match_lead_in_names_the_search_criterion(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """New UX addition: when a search by a SPECIFIC criterion (date/
        type/reference) resolves straight to one match, the preview message
        leads with 'I found one leave request matching "X" in your
        submitted requests' — echoing back what was searched for. A
        naturally-single pending leave with NO criteria given at all must
        NOT get this lead-in, since nothing was actually searched for."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Sick Leave", "2026-08-21", "2026-08-21"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(request_id="1"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel LR-1", "cancel_leave"), writer)

        assert 'I found one leave request matching "LR-1" in your submitted requests:' in result["response_text"]

    async def test_no_lead_in_for_a_naturally_single_pending_leave_with_no_criteria(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Sick Leave", "2026-08-21", "2026-08-21"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert "I found one leave request matching" not in result["response_text"]

    async def test_relative_day_words_resolve_deterministically(self, monkeypatch, fake_slots, fake_cancel_state):
        """'today'/'yesterday'/'day before yesterday'/'tomorrow' must all
        resolve without any LLM involvement, same reasoning as the weekday
        fallback — a closed, unambiguous vocabulary."""
        import datetime as _dt
        today = leave_action_service._today()
        two_days_ago = (today - _dt.timedelta(days=2)).isoformat()

        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-01-01", "2026-01-01"),
                _pending_leave(2, "Sick Leave", two_days_ago, two_days_ago),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _broken_call_llm(prompt, max_tokens=None, model=None):
            raise RuntimeError("LLM provider unreachable")
        monkeypatch.setattr(leave_action_service, "_call_llm", _broken_call_llm)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel my leave request for day before yesterday", "cancel_leave"), writer,
        )

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"

    async def test_month_name_and_abbreviation_resolve_deterministically(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """'25 aug', 'aug 25', '25th August', and a misspelled month name
        ('25 agust') must all resolve without any LLM involvement — same
        closed-vocabulary reasoning as the weekday/relative-day fallbacks."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-01-01", "2026-01-01"),
                _pending_leave(2, "Sick Leave", "2026-08-25", "2026-08-25"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _broken_call_llm(prompt, max_tokens=None, model=None):
            raise RuntimeError("LLM provider unreachable")
        monkeypatch.setattr(leave_action_service, "_call_llm", _broken_call_llm)

        for query in (
            "cancel my leave for 25 aug", "cancel my leave for aug 25",
            "cancel my leave for 25th August", "cancel my leave for 25 agust",
        ):
            fake_cancel_state.clear_state(1, "conv-1")
            writer = FakeWriter()
            result = await hr_graph.leave_action_node(base_state(query, "cancel_leave"), writer)
            assert writer.of_type("leave_cancellation_selection") == [], query
            preview = writer.of_type("leave_cancellation_preview")[0]["data"]
            assert preview["reference"] == "LR-2", query

    async def test_numeric_ddmm_date_resolves_deterministically(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """'14/08', '08/14', and '14-08-2026' must all resolve to the same
        day-first date (day=14, month=08), even when the alternate ordering
        (month-first) would also technically parse — day-first wins per
        this codebase's established convention."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-01-01", "2026-01-01"),
                _pending_leave(2, "Sick Leave", "2026-08-14", "2026-08-14"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        async def _broken_call_llm(prompt, max_tokens=None, model=None):
            raise RuntimeError("LLM provider unreachable")
        monkeypatch.setattr(leave_action_service, "_call_llm", _broken_call_llm)

        for query in ("cancel my leave for 14/08", "cancel my leave for 08/14", "cancel my leave for 14-08-2026"):
            fake_cancel_state.clear_state(1, "conv-1")
            writer = FakeWriter()
            result = await hr_graph.leave_action_node(base_state(query, "cancel_leave"), writer)
            assert writer.of_type("leave_cancellation_selection") == [], query
            preview = writer.of_type("leave_cancellation_preview")[0]["data"]
            assert preview["reference"] == "LR-2", query

    async def test_explicit_date_span_matches_the_leaves_own_from_to_dates(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """'cancel my leave request from 25 Aug to 29 Aug' describes the
        leave record's OWN span, not a calendar-period filter — must match
        a candidate whose from_date/to_date equal that exact span."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-08-24", "2026-08-24"),
                _pending_leave(2, "Sick Leave", "2026-08-25", "2026-08-29"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-08-25", date_to="2026-08-29"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel my leave request from 25 aug to 29 aug", "cancel_leave"), writer,
        )

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"

    async def test_range_phrase_narrows_to_one_candidate(self, monkeypatch, fake_slots, fake_cancel_state):
        """A calendar-period phrase ('last week') is just as specific a
        criterion as an exact date — reuses the same resolver as the
        leave_status 'show my leaves' branch."""
        import datetime as _dt
        today = leave_action_service._today()
        this_week_start = today - _dt.timedelta(days=today.weekday())
        last_week_day = (this_week_start - _dt.timedelta(days=3)).isoformat()

        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2026-01-01", "2026-01-01"),
                _pending_leave(2, "Sick Leave", last_week_day, last_week_day),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("cancel my leave request from last week", "cancel_leave"), writer,
        )

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"

    async def test_date_match_against_a_cancelled_record_still_goes_to_preview(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Per the simplified design (2026-08-20): this layer only finds
        WHICH request is meant — it does not pre-judge cancellability.
        A specific reference match against an already-cancelled record still
        goes straight to preview; erp-api's own /leave/cancel call is the
        sole authority on whether it's actually cancellable, surfaced only
        when the employee confirms."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, leave_status="all", **kwargs):
            cancelled = _pending_leave(51, "Casual Leave", "2026-08-20", "2026-08-20")
            cancelled["status_name"] = "cancelled"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(52, "Casual Leave", "2026-08-20", "2026-08-20"),  # different id, still pending
                cancelled,
                _pending_leave(44, "Sick Leave", "2026-08-14", "2026-08-14"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(request_id="51"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel LR-51", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection") == []
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-51"
        assert preview["status_name"] == "cancelled"

    async def test_date_with_no_matching_leave_reports_honestly(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(44, "Sick Leave", "2026-08-14", "2026-08-14"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)
        mock_extraction(monkeypatch, _cancel_extraction(date="2026-09-01"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave for 2026-09-01", "cancel_leave"), writer)

        assert "nothing on record fits it" in result["response_text"].lower()
        requests = writer.of_type("leave_cancellation_selection")[0]["data"]["requests"]
        assert {r["reference"] for r in requests} == {"LR-44"}

    async def test_vague_query_never_offers_a_non_pending_candidate(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """A vague 'cancel my leave' with mixed-status records must only
        ever list PENDING candidates — a cancelled/approved/rejected record
        isn't something the employee can actually cancel."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            cancelled = _pending_leave(51, "Casual Leave", "2026-08-20", "2026-08-20")
            cancelled["status_name"] = "cancelled"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(52, "Casual Leave", "2026-08-20", "2026-08-20"),
                cancelled,
                _pending_leave(44, "Sick Leave", "2026-08-14", "2026-08-14"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        requests = writer.of_type("leave_cancellation_selection")[0]["data"]["requests"]
        assert {r["reference"] for r in requests} == {"LR-52", "LR-44"}

    async def test_selection_by_number_resolves_to_preview(self, monkeypatch, fake_slots, fake_cancel_state):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card1 = leave_action_service._build_applied_leave_card(_pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"))
        card2 = leave_action_service._build_applied_leave_card(_pending_leave(2, "Sick Leave", "2026-08-02", "2026-08-02"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": [card1, card2]})

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="3")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("2", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "awaiting_confirmation"

    async def test_selection_reply_that_still_doesnt_resolve_re_shows_the_list(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card1 = leave_action_service._build_applied_leave_card(_pending_leave(1, "Casual Leave", "2026-08-01", "2026-08-01"))
        card2 = leave_action_service._build_applied_leave_card(_pending_leave(2, "Sick Leave", "2026-08-02", "2026-08-02"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": [card1, card2]})

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("hmm not sure", "cancel_leave"), writer)

        assert "couldn't quite tell which request" in result["response_text"].lower()
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "awaiting_selection"

    async def test_confirm_reply_cancels_the_leave_and_reports_updated_balance(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """AC#3/AC#4 — explicit confirmation is required, revalidation runs
        before executing, and once erp-api confirms the cancellation the
        authoritative post-cancellation balance (not the pre-cancellation
        preview figure) is reported back."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        # A known reason means confirmation executes immediately — the
        # ask-for-a-reason step (when none is known) is covered separately
        # in test_confirm_without_a_known_reason_asks_for_one_then_executes.
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        captured_cancel_call = {}

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            captured_cancel_call.update(leave_id=leave_id, cancel_reason=cancel_reason)
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        assert captured_cancel_call == {"leave_id": 2041, "cancel_reason": "plans changed"}
        assert "has been cancelled" in result["response_text"]
        assert "LR-2041" in result["response_text"]
        # Now shows "X of Y available" (matches the Figma design) rather
        # than just the bare remaining count, whenever erp-api's balance
        # call returns both figures.
        assert "Updated balance: Casual Leave — 6 of 12 available" in result["response_text"]
        # Same Figma-formatted date as the card, not the raw "2026-07-30 to
        # 2026-07-30" ISO pair — a live gap found 2026-08-25.
        assert "Thu, 30 Jul 2026" in result["response_text"]
        assert "2026-07-30 to 2026-07-30" not in result["response_text"]
        assert fake_cancel_state.get_state(1, "conv-1") is None

        success_data = writer.of_type("leave_cancel_success")[0]["data"]
        assert success_data["status_name"] == "Cancelled"
        assert success_data["updated_balance"] == "6"
        assert success_data["employee"] == {"user_id": 1, "name": None, "emp_code": "1"}

    async def test_confirm_reply_balance_message_falls_back_gracefully_without_a_total(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """erp-api's balance quota entry omitting 'total' (only 'remaining')
        must still name the leave type rather than reading '6 day(s)
        available' — the fallback wording gets the same treatment as the
        'X of Y' branch, just without the 'of Y' part."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"remaining": "1"}},  # no "total" key
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        assert "Updated balance: 1 Casual Leave available." in result["response_text"]  # singular, no "of Y"

    async def test_success_card_carries_employee_identity(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        async def _context(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "is_manager": False, "name": "B Geo"}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _context)
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        success_data = writer.of_type("leave_cancel_success")[0]["data"]
        assert success_data["employee"] == {"user_id": 1, "name": "B Geo", "emp_code": "1"}

    async def test_success_card_carries_every_field_the_design_needs(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Figma repro: the success card needs leave_type, its code, dates,
        the reference, a 'Cancelled' status label, and both the remaining
        AND total balance (for 'X of Y available') — none of which erp-api's
        own /leave/cancel response carries (it only returns {leave_id,
        status, status_name, leave_type_slug, leave_count, cancel_reason}).
        These must come from the originally-matched candidate card, with
        cancel_leave's own fresher status overriding the stale 'pending'
        one."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(
            {**_pending_leave(2041, "Casual Leave", "2026-08-07", "2026-08-07"), "leave_type_slug": "casual_leave"})
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-08-07", "2026-08-07"), "leave_type_slug": "casual_leave"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6", total="12")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        success_data = writer.of_type("leave_cancel_success")[0]["data"]
        assert success_data["leave_type"] == "Casual Leave"
        assert success_data["leave_type_code"] == "CL"
        assert success_data["from_date"] == "2026-08-07"
        assert success_data["to_date"] == "2026-08-07"
        assert success_data["reference"] == "LR-2041"
        assert success_data["status_name"] == "cancelled"
        assert success_data["status_label"] == "Cancelled"
        assert success_data["updated_balance"] == "6"
        assert success_data["updated_total"] == "12"
        assert "Casual Leave — 6 of 12 available" in result["response_text"]

    async def test_confirm_without_a_reason_asks_for_one_instead_of_defaulting(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Confirm + reason are ONE step when possible — the preview prompt
        already asks for both together. But a confirm reply that gives NO
        reason at all must now ask a dedicated follow-up for it (live UX
        request, 2026-08-24), not silently substitute a generic placeholder
        nobody actually said."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": None})
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        assert "reason for cancelling" in result["response_text"].lower()
        new_state = fake_cancel_state.get_state(1, "conv-1")
        assert new_state["step"] == "awaiting_reason"
        assert new_state["selected"]["id"] == 2041
        # Frontend-facing flag so the UI can render a reason input specifically,
        # rather than parsing the answer text to infer this is a reason-ask.
        assert writer.of_type("done")[0]["data"]["ask_cancel_leave_reason"] is True

    async def test_reason_turn_executes_the_cancellation_with_the_given_reason(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The follow-up to the missing-reason ask above — the whole reply
        IS the reason, no extraction needed."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_reason", "selected": card})

        captured_cancel_call = {}

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            captured_cancel_call.update(leave_id=leave_id, cancel_reason=cancel_reason)
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("my plans changed", "cancel_leave"), writer)

        assert captured_cancel_call == {"leave_id": 2041, "cancel_reason": "my plans changed"}
        assert "has been cancelled" in result["response_text"]
        assert fake_cancel_state.get_state(1, "conv-1") is None
        assert writer.of_type("leave_cancel_success")[0]["data"]["ask_cancel_leave_reason"] is False
        # Frontend-facing flag for the whole cancel-leave lifecycle — False
        # on every response by default, True only once actually cancelled.
        assert writer.of_type("done")[0]["data"]["cancelled"] is True

    async def test_reason_turn_still_honors_a_change_of_heart(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """A 'keep it'/'never mind' reply at the reason-ask step must still
        decline the cancellation, not get filed away as a literal reason."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_reason", "selected": card})

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("keep request", "cancel_leave"), writer)

        assert "kept your" in result["response_text"].lower()
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "declined"
        # Frontend-facing flag so the UI can react to a decline without
        # parsing the message text.
        assert writer.of_type("done")[0]["data"]["keep_leave_request"] is True

    async def test_confirm_reply_with_reason_inline_executes_in_one_step(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The primary one-step case: a SINGLE reply carrying both the
        confirmation AND the reason ('yes, my plans changed') must execute
        immediately using that reason, no separate ask."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": None})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        captured_cancel_call = {}

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            captured_cancel_call.update(leave_id=leave_id, cancel_reason=cancel_reason)
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True, reason="my plans changed"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("yes, my plans changed", "cancel_leave"), writer)

        assert captured_cancel_call == {"leave_id": 2041, "cancel_reason": "my plans changed"}
        assert "has been cancelled" in result["response_text"]
        assert fake_cancel_state.get_state(1, "conv-1") is None

    async def test_confirm_reply_forwards_a_reason_the_employee_actually_gave(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """A reason captured on the original matching turn (e.g. 'cancel my
        leave, my plans changed') must reach erp-api's cancel_reason field
        rather than being silently dropped or replaced with the default."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(
            1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "my plans changed"},
        )

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        captured_cancel_call = {}

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            captured_cancel_call.update(leave_id=leave_id, cancel_reason=cancel_reason)
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        assert captured_cancel_call["cancel_reason"] == "my plans changed"

    async def test_cancel_failure_from_erp_api_surfaces_its_message_verbatim(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """AC#5 — erp-api itself may reject the cancellation (ownership/
        eligibility check, e.g. payroll-locked) even though it was still in
        the pending list a moment ago. Its message must be shown verbatim,
        not replaced with a generic failure or a false success."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 400, "body": {
                "success": False, "message": "This leave request is locked due to payroll processing.",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        assert result["response_text"].startswith("This leave request is locked due to payroll processing.")
        assert writer.of_type("leave_cancel_success") == []
        assert fake_cancel_state.get_state(1, "conv-1") is None

    async def test_cancel_erp_api_timeout_leaves_a_clean_retry_message(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            raise ErpApiTimeout("timed out")
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        assert "couldn't reach the HR system in time" in result["response_text"]

    async def test_decline_reply_keeps_the_request_and_remembers_it_as_declined(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card})
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=False))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Keep Request", "cancel_leave"), writer)

        assert "kept" in result["response_text"].lower()
        assert "Casual Leave" in result["response_text"]
        # Not cleared outright — a short-lived "declined" memory instead,
        # so a follow-up like "cancel again" can resume straight to
        # confirmation (see TestResumingCancelAfterDecline).
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "declined"
        assert writer.of_type("done")[0]["data"]["keep_leave_request"] is True
        assert writer.of_type("done")[0]["data"]["cancelled"] is False

    async def test_keep_request_declines_even_when_llm_misreads_it_as_affirmative(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Regression test for a live incident (2026-08-19): against the real
        staging LLM, 'Keep Request' — the actual UI decline button's label —
        came back from extraction as is_affirmative=true, and the old
        'decline and not is_affirmative' guard let that misread silently
        execute a real cancellation nobody asked for. The deterministic
        decline pattern must win outright whenever it's the ONLY
        deterministic signal that matches, regardless of what the LLM says."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": None})

        cancel_mock = MagicMock(side_effect=AssertionError("must not cancel — this reply is an unambiguous decline"))
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", cancel_mock)
        # The exact live failure mode: LLM extraction wrongly says affirmative.
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Keep Request", "cancel_leave"), writer)

        assert "kept" in result["response_text"].lower()
        assert writer.of_type("leave_cancel_success") == []
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "declined"
        cancel_mock.assert_not_called()

    async def test_confirm_cancellation_confirms_even_when_llm_extraction_fails(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The deterministic confirm pattern must also win outright on its
        own — including when the LLM extraction call fails entirely (matches
        _extract_cancel_fields' fail-closed-to-{} behavior), so a literal
        'Confirm Cancellation' button click always works even during an LLM
        outage, not just when the LLM happens to agree."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)

        # Simulate a total extraction failure — _extract_cancel_fields must
        # catch this and return {} (see its try/except), not propagate.
        async def _broken_call_llm(prompt, max_tokens=None, model=None):
            raise RuntimeError("LLM provider unreachable")
        monkeypatch.setattr(leave_action_service, "_call_llm", _broken_call_llm)

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        assert "has been cancelled" in result["response_text"]
        assert fake_cancel_state.get_state(1, "conv-1") is None

    async def test_yes_cancel_it_confirms_deterministically_even_when_llm_disagrees(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The LLD's own example lists 'Yes, cancel it' as a POSITIVE
        confirmation. It also contains the bare \\bcancel\\b word that alone
        would mean decline — but a leading 'yes' wins outright over a bare
        cancel elsewhere in the message, without ever consulting the LLM.
        Proven here by mocking is_affirmative=False (the LLM disagreeing)
        and confirming it still executes."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=False))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Yes, cancel it", "cancel_leave"), writer)

        assert "has been cancelled" in result["response_text"]

    async def test_yes_cancel_reference_id_confirms_instead_of_re_asking(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Regression test for a live bug report (2026-08-20): 'yes Cancel
        LR-32' — an unambiguous confirmation naming the exact request already
        selected — used to fall through to the LLM's unreliable
        is_affirmative and re-show the identical yes/no prompt forever
        instead of moving the flow forward."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(32, "Short Leave", "2026-08-17", "2026-08-17"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": None})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(32, "Short Leave", "2026-08-17", "2026-08-17"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "short_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="short_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=False))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("yes Cancel LR-32", "cancel_leave"), writer)

        # Must have moved the flow FORWARD (deterministic confirm detected),
        # not repeated the identical "would you like to cancel" prompt. No
        # reason was given, so it now asks for one instead of executing
        # immediately — still forward progress, just not straight to done.
        assert "didn't catch that" not in result["response_text"].lower()
        assert "reason for cancelling" in result["response_text"].lower()
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "awaiting_reason"

    async def test_bare_no_declines_without_needing_the_word_cancel(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """A bare 'No' reply at this strict binary confirmation moment must
        decline, not loop back asking again (AC#3)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card})
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=False))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("No", "cancel_leave"), writer)

        assert "kept" in result["response_text"].lower()
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "declined"

    async def test_ambiguous_confirmation_reply_re_asks_and_keeps_state(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card})
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=False))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("what do you think", "cancel_leave"), writer)

        assert "didn't catch that" in result["response_text"].lower()
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "awaiting_confirmation"

    async def test_confirm_calls_cancel_leave_directly_with_no_revalidation_fetch(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Per the simplified design (2026-08-20): erp-api's /leave/cancel
        call owns ALL eligibility validation (ownership, current status,
        lock state, policy) — this layer no longer re-fetches to pre-check
        before calling it. Confirming must go straight to cancel_leave()."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        applied_mock = MagicMock(side_effect=AssertionError("must not re-fetch /leave/applied before executing"))
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", applied_mock)

        captured = {}

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            captured.update(leave_id=leave_id, cancel_reason=cancel_reason)
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("confirm", "cancel_leave"), writer)

        applied_mock.assert_not_called()
        assert captured == {"leave_id": 2041, "cancel_reason": "plans changed"}
        assert "has been cancelled" in result["response_text"]

    async def test_already_cancelled_rejection_from_cancel_api_is_forwarded_verbatim(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """erp-api's /leave/cancel call is the single source of truth on
        eligibility now — when it rejects an already-cancelled request, that
        exact reason is shown, not a client-side guess."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(_pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 400, "body": {
                "success": False, "message": "This leave request has already been cancelled.",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("confirm", "cancel_leave"), writer)

        assert "already been cancelled" in result["response_text"].lower()
        assert fake_cancel_state.get_state(1, "conv-1") is None

    async def test_cancel_request_during_apply_flow_stays_apply_leave_not_cancel_leave(self, fake_slots):
        """UPDATED (live bug report): unlike leave_balance/leave_status, a
        bare 'cancel'-phrased reply while an apply draft is in progress does
        NOT mean "look up a different, already-submitted leave to cancel" —
        it means "discard this draft". Treating it as a generic interruption
        used to route straight into the cancel_leave flow (asking to pick a
        PENDING submitted leave to cancel) while silently leaving the draft
        alive in the background — and a later "Keep Request" reply in that
        wrong flow could then get misread as an affirmative answer to the
        apply flow's own stale confirmation prompt, submitting a leave
        nobody confirmed. See TestClassifyNodeMidFlowInterruption's
        cancel-during-apply tests for the full fix; this only needs a
        reference number ("cancel LR-2041") to still be treated as a
        genuine interruption."""
        fake_slots.set_slots(1, "conv-1", {"step": "collecting", "leave_type": "casual_leave"})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("cancel my pending leave"), writer)

        assert result["intent"] == "apply_leave"


# ═════════════════════════════════════════════════════════════════════════════
# classify_node — mid-flow cancel-leave re-entry (Fast-path 0.6)
# ═════════════════════════════════════════════════════════════════════════════

class TestClassifyNodeCancelMidFlow:

    async def test_selection_reply_routes_straight_to_leave_action_node(self, monkeypatch, fake_cancel_state):
        """A bare '2' or 'LR-2041' reply has no leave keywords in it at all —
        without the stored cancel state it would never reach
        leave_action_node. Neither does it hit fast_classify confidently, so
        (like apply-leave's own confirmation step) it goes through the real
        fallback classifier — mocked here to return what a context-aware
        real classifier would say for a selection-turn reply."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "cancel_leave", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": []})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("2", intent="general"), writer)

        assert result["intent"] == "cancel_leave"
        assert result["is_hr"] is True

    async def test_confirmation_reply_routes_straight_to_leave_action_node(self, monkeypatch, fake_cancel_state):
        """Same reasoning as the selection-reply test above: a bare 'Confirm
        Cancellation' carries no keyword either, so it goes through the
        fallback classifier."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "cancel_leave", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": {}})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("Confirm Cancellation", intent="general"), writer)

        assert result["intent"] == "cancel_leave"

    async def test_confident_different_intent_interrupts_without_losing_cancel_state(self, fake_cancel_state):
        """A confident, unrelated question ('what's my leave balance') must be
        answered directly rather than swallowed as a selection/confirmation
        reply — mirrors apply-leave's Fast-path 0.5 interruption handling."""
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": []})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("what's my leave balance", intent="general"), writer)

        assert result["intent"] == "leave_balance"
        # State is left untouched for the flow to resume afterward.
        assert fake_cancel_state.get_state(1, "conv-1") is not None

    async def test_no_cancel_state_falls_through_to_normal_classification(self, fake_cancel_state):
        """Negative control: with no stored cancel state, a bare '2' must not
        be force-routed into cancel_leave."""
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("2", intent="general"), writer)

        assert result["intent"] != "cancel_leave"

    async def test_greeting_like_reason_at_awaiting_reason_step_is_not_treated_as_an_interruption(
        self, fake_cancel_state,
    ):
        """Live bug report: a cancellation reason like 'hello' or 'hi' hits
        fast_classify's single-keyword greeting match at full confidence, so
        the interruption check used to misread it as a topic switch and
        answer with a greeting instead of routing it to leave_action_node's
        reason-turn branch (which takes the whole reply verbatim as the
        reason). Unlike every other cancel step, 'awaiting_reason' expects
        free text with no keyword at all — must always route through."""
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_reason", "selected": {}})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("hello", intent="general"), writer)

        assert result["intent"] == "cancel_leave"

    async def test_greeting_like_query_still_interrupts_at_other_cancel_steps(self, fake_cancel_state):
        """Contrast with the reason-step test above: at every OTHER cancel
        step (selection/confirmation), a confident different intent — even
        a bare greeting — is still treated as a genuine interruption, since
        those steps expect a specific selection/yes-no reply, not free
        text."""
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": []})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("hello", intent="general"), writer)

        assert result["intent"] == "greeting"

    async def test_genuinely_different_question_at_confirmation_step_is_answered_not_re_asked(
        self, monkeypatch, fake_cancel_state,
    ):
        """Live bug report: a user asked to confirm a cancellation changed
        their mind mid-confirmation and asked something else entirely
        ('check leave eligibility') — colloquial enough that fast_classify's
        closed keyword lists didn't confidently match it (unlike 'what's my
        leave balance' in the test above), so the OLD code (no fallback at
        all here) fell straight through to leave_action_node, which then
        re-asked the same yes/no confirmation ('Sorry, I didn't catch
        that...') instead of ever answering the real question. Must now
        fall back to the real classifier — same as apply-leave's own
        confirmation step already does — and answer directly."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            assert "pending leave-cancellation request" in prompt
            assert "cancel_leave" in prompt
            return "leave_eligibility", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": {}})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("check leave eligibility", intent="general"), writer)

        assert result["intent"] == "leave_eligibility"
        # Cancel state is left untouched so the flow can resume afterward,
        # same as every other interruption in this suite.
        assert fake_cancel_state.get_state(1, "conv-1") is not None

    async def test_bare_yes_reply_still_resolves_via_fallback_not_misread_as_off_topic(
        self, monkeypatch, fake_cancel_state,
    ):
        """A bare 'yes' carries no keyword either, so it also goes through
        the fallback — the awaited-context prompt is what lets the real
        classifier correctly read it as continuing the cancellation instead
        of guessing it's unrelated."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            assert "whether to CONFIRM cancelling this leave request" in prompt
            return "cancel_leave", None, False
        monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)

        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": {}})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("yes", intent="general"), writer)

        assert result["intent"] == "cancel_leave"


# ═════════════════════════════════════════════════════════════════════════════
# HEL-283 for the cancel flow — erp-api's /leave/cancel rejection goes through
# the same services.leave_failure layer as apply, so cancel gets identical
# reason codes, badges, leak-guarding and fallback rather than a second,
# looser implementation of the same rule.
# ═════════════════════════════════════════════════════════════════════════════

class TestCancelFailureCards:

    def _set_awaiting_confirmation(self, fake_cancel_state, leave_action_service,
                                    id_=2041, leave_type="Casual Leave",
                                    from_date="2026-07-30", to_date="2026-07-30",
                                    reason="plans changed"):
        card = leave_action_service._build_applied_leave_card(
            _pending_leave(id_, leave_type, from_date, to_date))
        fake_cancel_state.set_state(1, "conv-1", {
            "step": "awaiting_confirmation", "selected": card, "reason": reason,
        })

    async def test_already_cancelled_maps_to_its_reason_code(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live erp-api payload captured 2026-08-19."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        self._set_awaiting_confirmation(fake_cancel_state, leave_action_service)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 400, "body": {
                "success": False, "message": "This leave request has already been cancelled.",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("confirm", "cancel_leave"), writer)

        failure = writer.of_type("leave_failure")[0]["data"]["failure"]
        assert failure["reason_code"] == ["ALREADY_CANCELLED"]
        assert failure["action"] == "cancel_leave"
        assert failure["title"] == "Cancellation Not Completed"

    async def test_attendance_locked_maps_to_its_reason_code(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live erp-api payload captured 2026-08-19."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        self._set_awaiting_confirmation(fake_cancel_state, leave_action_service)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 400, "body": {
                "success": False,
                "message": "You cannot cancel this leave because attendance has already been calculated.",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("confirm", "cancel_leave"), writer)

        failure = writer.of_type("leave_failure")[0]["data"]["failure"]
        assert failure["reason_code"] == ["ATTENDANCE_LOCKED"]

    async def test_backend_reason_is_never_reworded(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """AC1-AC3: the employee sees erp-api's sentence, character for
        character, and never a generic 'something went wrong' — including for
        a policy rejection erp-api hasn't classified (e.g. LP-14's 48-hour
        cancellation-notice rule)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        self._set_awaiting_confirmation(fake_cancel_state, leave_action_service)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 400, "body": {
                "success": False,
                "message": "Policy LP-14: approved leave can only be cancelled at least "
                           "48 hours before the start date. Your leave starts on 06 Aug 2026.",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("confirm", "cancel_leave"), writer)

        failure = writer.of_type("leave_failure")[0]["data"]["failure"]
        assert failure["display_message"] == [
            "Policy LP-14: approved leave can only be cancelled at least "
            "48 hours before the start date. Your leave starts on 06 Aug 2026.",
        ]
        # Never guessed into a SPECIFIC category the ticket names but erp-api
        # has never actually returned — it gets the generic POLICY_RULE
        # default instead (product decision, 2026-08-24), not INSUFFICIENT_
        # BALANCE/BLOCKED_DATE which would be a wrong, specific guess.
        assert failure["reason_code"] == ["POLICY_RULE"]
        assert failure["badge"] == ["policy_rule"]
        assert failure["is_fallback"] is False
        assert result["response_text"].startswith("Policy LP-14")

    async def test_technical_detail_never_reaches_the_employee(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """AC5: stack traces / SQL must be replaced, not displayed."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        self._set_awaiting_confirmation(fake_cancel_state, leave_action_service)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 500, "body": {
                "success": False,
                "message": "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("confirm", "cancel_leave"), writer)

        failure = writer.of_type("leave_failure")[0]["data"]["failure"]
        assert failure["is_fallback"] is True
        assert "SQLSTATE" not in result["response_text"]
        assert "Unable to complete your leave request" in result["response_text"]

    async def test_unknown_error_code_gets_the_controlled_fallback(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """AC5: a bare code explains nothing, so it must not be shown."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        self._set_awaiting_confirmation(fake_cancel_state, leave_action_service)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 400, "body": {"success": False, "message": "ERR_5521"}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("confirm", "cancel_leave"), writer)

        failure = writer.of_type("leave_failure")[0]["data"]["failure"]
        assert failure["is_fallback"] is True
        assert "ERR_5521" not in result["response_text"]

    async def test_successful_cancellation_emits_no_failure_card(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        self._set_awaiting_confirmation(fake_cancel_state, leave_action_service)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("confirm", "cancel_leave"), writer)
        assert writer.of_type("leave_failure") == []

    async def test_done_event_carries_the_same_card(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The terminal done event repeats the card so a client rendering
        from it alone still receives the full structure."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        self._set_awaiting_confirmation(fake_cancel_state, leave_action_service)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 400, "body": {
                "success": False, "message": "This leave request has already been cancelled.",
            }}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("confirm", "cancel_leave"), writer)

        card = writer.of_type("leave_failure")[0]["data"]
        done = writer.of_type("done")[0]["data"]
        assert done["failure"] == card["failure"]


class TestCancelFailureIsBackendOnly:
    """HEL-283 on the cancel flow. The enhancement is the SHAPE — status,
    reason_code, human-readable text — not the content. erp-api's
    /leave/cancel is the single source of truth for whether a matched request
    is cancellable (the fresh-turn branch deliberately does no client-side
    pending/approved pre-check), so its rejection is the whole reason and
    nothing local is ever added beside it."""

    def _arrange(self, monkeypatch, fake_cancel_state, cancel_body, listed_status="pending"):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(
            _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(
            1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": None})

        async def _status(token, **kwargs):
            lv = _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30")
            lv["status_name"] = listed_status
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [lv]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _status)

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 400, "body": cancel_body}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)
        # A reason is supplied here so these tests reach _execute_cancel
        # directly — reason-collection itself is covered separately; this
        # class is only testing the failure-card SHAPE once erp-api rejects.
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True, reason="testing"))

    async def _run(self, monkeypatch, fake_cancel_state, cancel_body, listed_status="pending"):
        self._arrange(monkeypatch, fake_cancel_state, cancel_body, listed_status)
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(
            base_state("Confirm Cancellation", "cancel_leave"), writer)
        return writer.of_type("leave_failure")[0]["data"]["failure"], result

    REJECTION = {"success": False,
                 "message": "This leave request is locked due to payroll processing."}

    async def test_only_the_backend_reason_is_shown(
            self, monkeypatch, fake_slots, fake_cancel_state):
        """One rejection means one reason. Nothing is derived locally to sit
        beside it — a sentence the backend never said is what AC5 forbids."""
        failure, result = await self._run(monkeypatch, fake_cancel_state, self.REJECTION)
        assert failure["display_message"] == [
            "This leave request is locked due to payroll processing."]
        assert len(failure["reason_code"]) == 1
        assert result["response_text"].startswith(
            "This leave request is locked due to payroll processing.")

    async def test_no_reason_is_invented_even_when_the_status_moved(
            self, monkeypatch, fake_slots, fake_cancel_state):
        """A request approved between preview and confirmation still yields
        exactly erp-api's reason. Helix does not re-derive why it was
        refused — that decision, and its wording, belong to the backend."""
        failure, _ = await self._run(
            monkeypatch, fake_cancel_state, self.REJECTION, listed_status="approved")
        assert failure["display_message"] == [
            "This leave request is locked due to payroll processing."]
        assert len(failure["display_message"]) == 1

    async def test_the_shape_is_the_enhancement(
            self, monkeypatch, fake_slots, fake_cancel_state):
        """What Helix adds is structure, not content: a machine-readable
        status and reason code wrapped around the backend's own sentence."""
        failure, _ = await self._run(monkeypatch, fake_cancel_state, {
            "success": False,
            "message": "This leave request has already been cancelled."})
        assert failure["status"] == "REJECTED"
        assert failure["action"] == "cancel_leave"
        assert failure["title"] == "Cancellation Not Completed"
        assert failure["reason_code"] == ["ALREADY_CANCELLED"]
        assert failure["display_message"] == ["This leave request has already been cancelled."]
        assert failure["is_fallback"] is False

    async def test_next_action_is_offered_on_a_real_rejection(
            self, monkeypatch, fake_slots, fake_cancel_state):
        """AC6: derived from the reason_code, never from reading the message.
        REJECTION's wording doesn't match any specific pattern, so it
        defaults to POLICY_RULE (HA-163 Sprint 2 Scenario C) — a policy
        block is HR's call, not something re-picking a request fixes, so it
        gets the Help Desk suggestion rather than the generic one below."""
        failure, result = await self._run(monkeypatch, fake_cancel_state, self.REJECTION)
        assert failure["next_action"] == "Would you like to contact HR for help with this?"
        assert "Would you like to contact HR for help with this?" in result["response_text"]
        assert failure["next_actions"] == [{"label": "Contact HR Help Desk", "action": "contact_hr"}]

    async def test_next_action_offers_to_view_requests_for_a_non_policy_rejection(
            self, monkeypatch, fake_slots, fake_cancel_state):
        """A state-conflict rejection (already cancelled, attendance locked)
        isn't a policy call — Contact HR wouldn't help here, so this keeps
        the original "see your other requests" suggestion instead."""
        failure, result = await self._run(monkeypatch, fake_cancel_state, {
            "success": False, "message": "This leave request has already been cancelled."})
        assert failure["next_action"] == "Would you like to see your other leave requests?"
        assert "Would you like to see your other leave requests?" in result["response_text"]
        assert failure["next_actions"] == [
            {"label": "View My Leave Requests", "action": "view_leave_requests"}]

    async def test_no_next_action_when_the_backend_explained_nothing(
            self, monkeypatch, fake_slots, fake_cancel_state):
        """AC5/AC6 together: with only a bare code to go on we don't know
        enough to suggest a step, so no SPOKEN sentence is invented. The
        Contact HR chip is still attached (HA-163 Sprint 2's "always attach
        chips" rule) — safe because it echoes the fallback message's own
        "...or contact HR support" line rather than contradicting it."""
        failure, result = await self._run(
            monkeypatch, fake_cancel_state, {"success": False, "message": "ERR_9001"})
        assert failure["is_fallback"] is True
        assert failure["next_action"] is None
        assert "ERR_9001" not in result["response_text"]
        assert failure["next_actions"] == [{"label": "Contact HR Help Desk", "action": "contact_hr"}]

    async def test_a_status_change_never_gates_a_cancellation(
            self, monkeypatch, fake_slots, fake_cancel_state):
        """The pre-check this flow deliberately does not do must not creep
        back in: an approved request erp-api accepts is cancelled, because a
        future approved leave is a normal thing to withdraw."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(
            _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30"))
        fake_cancel_state.set_state(
            1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": None})

        async def _approved(token, **kwargs):
            lv = _pending_leave(2041, "Casual Leave", "2026-07-30", "2026-07-30")
            lv["status_name"] = "approved"
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [lv]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _approved)

        async def _ok(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": 2041, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1"}}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _ok)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True, reason="testing"))

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)
        assert writer.of_type("leave_failure") == []
        assert writer.of_type("leave_cancel_success")


class TestApprovedBackdatedCancelBlock:
    """2026-08-26 product direction: an APPROVED leave whose date has
    already passed can never actually be cancelled (erp-api would always
    refuse it), so Helix catches this on its own — before ever showing a
    balance-impact preview or making the mutating /leave/cancel call — and
    shows the same leave_failure card shape a real erp-api policy rejection
    would produce."""

    async def test_approved_backdated_leave_is_blocked_with_no_preview(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-08-01", "2026-08-01"),
                 "leave_type_slug": "casual_leave", "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        cancel_mock = MagicMock(side_effect=AssertionError("must never call /leave/cancel for a blocked request"))
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", cancel_mock)
        balance_mock = MagicMock(side_effect=AssertionError("must never fetch balance for a blocked request — no preview is shown"))
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", balance_mock)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_preview") == []
        cancel_mock.assert_not_called()
        balance_mock.assert_not_called()

        card = writer.of_type("leave_failure")[0]["data"]["failure"]
        assert card["status"] == "REJECTED"
        assert card["action"] == "cancel_leave"
        assert card["title"] == "Cancellation Not Completed"
        assert card["sub_title"] == "Blocked by leave policy"
        assert card["reason_code"] == ["POLICY_RULE"]
        assert card["badge"] == ["policy_rule"]
        assert card["badge_label"] == ["Policy rule"]
        assert card["display_message"] == [
            "An approved leave cannot be cancelled after its leave date has passed."]
        assert card["is_fallback"] is False
        assert card["next_action"] == "Would you like to contact HR for help with this?"
        assert card["next_actions"] == [{"label": "Contact HR Help Desk", "action": "contact_hr"}]

        assert result["response_text"].startswith(
            "An approved leave cannot be cancelled after its leave date has passed. "
            "Would you like to contact HR for help with this?"
        )
        # No dangling state left behind for the next turn to misread.
        assert fake_cancel_state.get_state(1, "conv-1") is None

    async def test_done_event_carries_the_same_blocked_card(self, monkeypatch, fake_slots, fake_cancel_state):
        """Same done-event parity guarantee every other leave_failure card
        gets — a client rendering from the terminal done event alone must
        still see the full card, not just the flat sentence."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2026-08-01", "2026-08-01"),
                 "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        failure_card = writer.of_type("leave_failure")[0]["data"]
        done_data = writer.of_type("done")[0]["data"]
        assert done_data["failure"] == failure_card["failure"]

    async def test_pending_backdated_leave_is_not_blocked(self, monkeypatch, fake_slots, fake_cancel_state):
        """The block is specific to APPROVED leaves — a pending request
        whose leave date has passed is a different situation entirely (it
        was never going to happen on that date to begin with) and must
        still go through the normal preview/confirm flow."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2026-08-01", "2026-08-01"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert writer.of_type("leave_failure") == []
        assert writer.of_type("leave_cancellation_preview")

    async def test_approved_future_leave_is_not_blocked(self, monkeypatch, fake_slots, fake_cancel_state):
        """Negative control: an approved leave whose date HASN'T passed yet
        must reach the normal balance-impact preview, not this block."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"), "status_name": "approved"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert writer.of_type("leave_failure") == []
        assert writer.of_type("leave_cancellation_preview")


class TestLeaveToCancelFlag:
    """`leave_to_cancel` says whether this turn has a real leave record (or
    records) to work with — distinct from `cancelled`, which tracks whether
    an actual cancellation just completed. True on every turn by default;
    False only where there is genuinely no leave data at all."""

    async def test_no_leave_requests_at_all_is_false(self, monkeypatch, fake_slots, fake_cancel_state):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert writer.of_type("done")[0]["data"]["leave_to_cancel"] is False

    async def test_records_exist_but_none_are_cancellable_is_false(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Records exist, but every one of them is already cancelled or
        rejected — nothing left that could ever be cancelled, so this reads
        the same as having no leave data at all."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(31, "Sick Leave", "2026-08-18", "2026-08-18"), "status_name": "cancelled"},
                {**_pending_leave(32, "Casual Leave", "2026-08-19", "2026-08-19"), "status_name": "rejected"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert "don't have any pending or approved leave requests to cancel" in result["response_text"]
        assert writer.of_type("done")[0]["data"]["leave_to_cancel"] is False

    async def test_erp_api_unreachable_before_any_fetch_is_false(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """No leave data was ever retrieved — this is a system error, not a
        genuine "nothing to cancel" answer, but there is still no leave data
        in this turn to report."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            raise ErpApiUnavailable("erp-api down")
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert writer.of_type("done")[0]["data"]["leave_to_cancel"] is False

    async def test_single_match_preview_is_true(self, monkeypatch, fake_slots, fake_cancel_state):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert writer.of_type("done")[0]["data"]["leave_to_cancel"] is True

    async def test_ambiguous_selection_list_is_true(self, monkeypatch, fake_slots, fake_cancel_state):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(1, "Casual Leave", "2027-06-14", "2027-06-14"),
                _pending_leave(2, "Sick Leave", "2027-07-01", "2027-07-02"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection")
        assert writer.of_type("done")[0]["data"]["leave_to_cancel"] is True

    async def test_successful_execution_is_true(self, monkeypatch, fake_slots, fake_cancel_state):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(
            _pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(is_affirmative=True))

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("Confirm Cancellation", "cancel_leave"), writer)

        done_data = writer.of_type("done")[0]["data"]
        assert done_data["cancelled"] is True
        assert done_data["leave_to_cancel"] is True


class TestCancelConfirmationEdgeCases:
    """Live UX reports (2026-08-27): a fresh cancel-leave request sent while
    an earlier one is still sitting unresolved was being swallowed as a
    reply to the OLD confirmation instead of starting a new match; a
    reference number wasn't recognized when spoken with a space ("lr 137");
    and an unmatched reference during selection fell through to being
    misread as a position instead of an honest "not found"."""

    async def test_fresh_cancel_request_during_stale_confirmation_reruns_matching(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """A stale 'awaiting_confirmation' state for one leave (Casual) must
        not swallow a brand-new request naming a DIFFERENT type (Sick) as a
        decline just because it contains the bare word 'cancel' — it must
        instead be treated as a fresh match against that new criterion."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        stale_selected = leave_action_service._build_applied_leave_card(
            _pending_leave(1, "Casual Leave", "2027-06-14", "2027-06-14"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": stale_selected, "reason": None})

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {**_pending_leave(2, "Sick Leave", "2027-07-01", "2027-07-01"), "leave_type_slug": "sick_leave"},
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(leave_type="sick_leave"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("I want to cancel my sick leave", "cancel_leave"), writer)

        assert "kept" not in result["response_text"].lower()
        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-2"
        assert preview["leave_type"] == "Sick Leave"

    async def test_yes_still_confirms_the_currently_pending_request(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Negative control: an explicit confirm marker must still confirm
        the CURRENT pending request even if it happens to also name a leave
        type — the fresh-request detour must never override a genuine yes."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(
            _pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card, "reason": "plans changed"})

        async def _cancel(token, leave_id, cancel_reason, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_id": leave_id, "status": 3, "status_name": "Cancelled",
                "leave_type_slug": "casual_leave", "leave_count": "1", "cancel_reason": cancel_reason,
            }, "message": "Leave request cancelled successfully."}}
        monkeypatch.setattr(hr_graph.erp_client, "cancel_leave", _cancel)

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="6")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(leave_type="casual_leave", is_affirmative=True))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("yes cancel my casual leave", "cancel_leave"), writer)

        assert "has been cancelled" in result["response_text"]

    @pytest.mark.parametrize("word", ["discard", "discarded", "kept", "save", "saved"])
    async def test_bare_decline_synonyms_keep_the_request(
        self, word, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(
            _pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card})
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state(word, "cancel_leave"), writer)

        assert "kept" in result["response_text"].lower()
        # State isn't cleared outright anymore — a short-lived "declined"
        # memory lets a follow-up like "cancel again" resume straight to
        # confirmation instead of re-matching from scratch (see
        # TestResumingCancelAfterDecline below).
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "declined"

    async def test_keep_request_message_names_the_specific_request(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Humanized (2026-08-27): the decline reply names WHICH request was
        kept (date + reference), not just its leave type — especially
        important once more than one request has been in play."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(
            _pending_leave(2041, "Sick Leave", "2027-06-14", "2027-06-14"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_confirmation", "selected": card})
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Keep Request", "cancel_leave"), writer)

        assert "Mon, 14 Jun 2027" in result["response_text"]
        assert "LR-2041" in result["response_text"]

    async def test_reference_with_a_space_is_recognized(self, monkeypatch, fake_slots, fake_cancel_state):
        """'lr 137' — no hyphen, a plain space — is the most natural way to
        say a reference out loud and previously matched neither reference
        pattern at all."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _status(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(137, "Casual Leave", "2027-06-14", "2027-06-14"),
                _pending_leave(138, "Sick Leave", "2027-07-01", "2027-07-01"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _status)

        async def _balance(token, **kwargs):
            return _quota(remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await hr_graph.leave_action_node(base_state("cancel lr 137", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-137"

    async def test_selection_reply_with_unmatched_reference_gives_a_specific_not_found_message(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """A reference number named during an 'awaiting_selection' reply
        that doesn't exist in the shown candidate list must say so
        specifically and re-show the list — never silently fall through to
        misreading the same digits as a position (a live risk when the
        un-matched number happens to be small, e.g. "LR-2" with only 2
        candidates on screen)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        candidates = [
            leave_action_service._build_applied_leave_card(_pending_leave(41, "Casual Leave", "2027-06-14", "2027-06-14")),
            leave_action_service._build_applied_leave_card(_pending_leave(42, "Sick Leave", "2027-07-01", "2027-07-01")),
        ]
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": candidates, "reason": None})
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("LR-2", "cancel_leave"), writer)

        assert "couldn't find a request with reference lr-2" in result["response_text"].lower()
        assert writer.of_type("leave_cancellation_selection")
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "awaiting_selection"

    async def test_unmatched_reference_message_never_double_prefixes_when_llm_includes_lr(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live bug report: clicking a 'Cancel Ref #LR-136' quick-reply
        produced 'reference LR-LR-136' — the LLM cancel-extraction prompt
        explicitly allows request_id to come back already including the
        "LR-" prefix (see _build_leave_cancel_extraction_prompt's own
        example), but the not-found message template also prepends "LR-",
        so an unstripped "LR-136" from the LLM doubled up. Must normalize to
        bare digits regardless of which form the LLM returns."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        candidates = [
            leave_action_service._build_applied_leave_card(_pending_leave(41, "Casual Leave", "2027-06-14", "2027-06-14")),
            leave_action_service._build_applied_leave_card(_pending_leave(42, "Sick Leave", "2027-07-01", "2027-07-01")),
        ]
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": candidates, "reason": None})
        mock_extraction(monkeypatch, _cancel_extraction(request_id="LR-136"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("Cancel   Ref #LR-136", "cancel_leave"), writer)

        assert "lr-lr-136" not in result["response_text"].lower()
        assert "couldn't find a request with reference lr-136" in result["response_text"].lower()


class TestResumingCancelAfterDecline:
    """Live UX report: after 'Keep Request', a follow-up like 'cancel my
    previous request' or a bare 'cancel again' used to fall all the way
    through to the vague-query path (no leave type/date/reference of its
    own to match on) and re-show the FULL candidate list — instead of
    picking straight back up on the same request that was just declined.
    Declining now leaves a short-lived "declined" state (see
    TestCancelConfirmationEdgeCases's decline tests) instead of clearing it
    outright, so these can resume directly."""

    async def test_vague_cancel_again_after_decline_resumes_the_same_confirmation(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(
            _pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "declined", "selected": card, "reason": None})

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my previous request", "cancel_leave"), writer)

        assert "would you like to cancel this request" in result["response_text"].lower()
        assert "LR-2041" in result["response_text"]
        assert writer.of_type("leave_cancellation_preview")
        assert not writer.of_type("leave_cancellation_selection")
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "awaiting_confirmation"

    async def test_bare_cancel_again_after_decline_resumes_the_same_confirmation(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        card = leave_action_service._build_applied_leave_card(
            _pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "declined", "selected": card, "reason": None})

        async def _balance(token, **kwargs):
            return _quota(slug="casual_leave", remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel again", "cancel_leave"), writer)

        assert "would you like to cancel this request" in result["response_text"].lower()
        assert "LR-2041" in result["response_text"]

    async def test_naming_a_different_request_after_decline_starts_a_fresh_match_instead(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """A follow-up that DOES name a concrete, different criterion (here,
        a leave type never mentioned in the declined request) must not be
        swallowed as a resume of the old one — it's answered via the normal
        fresh-match path."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        declined_card = leave_action_service._build_applied_leave_card(
            _pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"))
        fake_cancel_state.set_state(1, "conv-1", {"step": "declined", "selected": declined_card, "reason": None})

        async def _applied(token, leave_status="all", **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(3099, "Sick Leave", "2027-08-01", "2027-08-01"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)

        async def _balance(token, **kwargs):
            return _quota(slug="sick_leave", remaining="5")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        mock_extraction(monkeypatch, _cancel_extraction(leave_type="sick_leave"))

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("cancel my sick leave", "cancel_leave"), writer)

        assert "LR-3099" in result["response_text"]
        assert "LR-2041" not in result["response_text"]
