"""
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 (access check, 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 datetime
import json
from datetime import date
import pytest
from unittest.mock import patch, MagicMock, AsyncMock

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

    # The manager individual-report state the real leave_slot_service also
    # holds; nothing here arms it, so a lookup is never waiting on a picker.
    def get_report_state(self, company_id, conversation_id):
        return None

    def clear_report_state(self, company_id, conversation_id):
        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, **kwargs):
        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)


def mock_confirmation_verdict(monkeypatch, verdict: str = "replace", replacement=None):
    """Patches classify_confirmation_reply — the model call that reads a reply
    to "Just to confirm, did you mean "X"?" as agree / decline / replace /
    other — to return `verdict`.

    Defaults to "replace": the tests that use it answer the read-back with a
    DIFFERENT reason ("no, i have fever", "dentists"), and are about what the
    flow does with that new reason, not about the model's reading of it.
    `replacement` is the model's cleaned value; None makes the flow fall back
    to this turn's extraction or the raw reply, as it does live."""
    async def _fake_classify(question, current_value, reply, field_label="value"):
        return verdict, replacement, {}

    monkeypatch.setattr(leave_action_service, "classify_confirmation_reply", _fake_classify)


async def approve_reason_readback(monkeypatch, writer, result=None):
    """Answer the reason read-back ("Just to confirm, did you mean "X"?") with
    "yes", the way an employee does.

    CEO review point 1: a reason Helix extracted or cleaned is read back for
    approval before the confirmation card - asked whenever the stored reason
    is not exactly what was typed (_reason_matches_what_was_typed). A test
    about what happens AT the card has to get past that step first. Returns
    `result` untouched when no read-back was asked."""
    if result is not None and "did you mean" not in result["response_text"].lower():
        return result
    mock_extraction(monkeypatch, {})
    return await hr_graph.leave_action_node(base_state("yes"), writer)




# ═════════════════════════════════════════════════════════════════════════════
# 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_leave_call_can_ever_name_another_employee(self):
        """Self-scoping is what keeps one employee out of another's leave data
        now that role no longer gates this feature: erp-api resolves the
        subject from the forwarded JWT alone (Auth::user()), and these
        functions give it no field that could name anyone else. Pins that —
        the request bodies/params must carry leave details only, never a
        user/employee identifier."""
        captured = []

        async def _request(method, url, headers=None, json=None, params=None, **kwargs):
            captured.append({"json": json, "params": params})
            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_balance("caller-token")
            await erp_client.get_pending_leaves("caller-token", applied_leave_date="2026-09-04")
            await erp_client.apply_leave("caller-token", "casual_leave", "2026-09-04", "2026-09-04",
                                          session_type_slug="full_day", reason="personal")

        allowed_body_keys = {"leave_type_slug", "from_date", "to_date", "session_type_slug", "reason"}
        allowed_param_keys = {"applied_leave_date"}
        for call in captured:
            assert set(call["json"] or {}) <= allowed_body_keys, call["json"]
            assert set(call["params"] or {}) <= allowed_param_keys, call["params"]

    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_pending_leaves_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_pending_leaves("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


# ═════════════════════════════════════════════════════════════════════════════
# leave_action_node — access check, balance branch, apply branch
# ═════════════════════════════════════════════════════════════════════════════

#: Several tests here apply for a hardcoded date in early September 2026,
#: and apply-leave refuses a date in the past. They passed until the wall
#: clock went past those dates and then started failing on "You can't apply
#: for leave on a past date", which is nothing to do with what any of them
#: checks. Pinned before the earliest of them.
#:
#: Only ever turns a past-date rejection back into a valid date - every
#: other hardcoded date in this module is response data (already-applied
#: leaves), and the tests that build a date relative to "today" compute it
#: from this pin, so they move with it.
PINNED_TODAY = date(2026, 8, 18)


@pytest.fixture(autouse=True)
def _pin_today(monkeypatch):
    monkeypatch.setattr(leave_action_service, "_today_in_app_timezone",
                        lambda: PINNED_TODAY)
    monkeypatch.setattr(leave_action_service, "_today", lambda: PINNED_TODAY)


@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)
    # hr_graph carries its OWN copy of classify_node (see hr_graph.py) and it is
    # the one actually wired into the graph, so it reads hr_graph.leave_slot_service
    # — without this the fake is invisible to every routing assertion here.
    monkeypatch.setattr(hr_graph, "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)
    # Same reason as fake_slots: hr_graph.classify_node is the live classifier
    # and reads hr_graph.leave_cancel_state.
    monkeypatch.setattr(hr_graph, "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_applied_leaves 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_pending_leaves/get_applied_leaves implementations."""
    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_applied_leaves", _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),
        ("HRMS_TEAM_LEAVE_QUERY", True),  # wired — team_leave_query_node calls erp_client
        ("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)

        # 6cd64a4 (application flow fixes): with a half-filled draft open, EVERY
        # interruption is asked about first - "carry on with it, or discard it?" -
        # so the draft is never silently orphaned. The draft itself is untouched.
        assert result["intent"] == "clarify_needed"
        assert result["clarify_options"] == ["Carry on with it", "Discard it"]
        assert fake_slots.get_slots(1, "conv-1")["leave_type"] == "casual_leave"

    @pytest.mark.parametrize("query", ["cancel my leave", "cancel this application"])
    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"

    @pytest.mark.parametrize("query", [
        "cancel LR-2041",
        # Not a reference number, but just as unambiguous: a draft has never
        # been "pending"/"submitted"/"approved" and is exactly ONE request,
        # so a status word or a plural object can only mean an
        # already-submitted one. See _SUBMITTED_LEAVE_TARGET_PATTERNS, which
        # superseded the older rule that kept every reference-less cancel in
        # the apply flow — including "cancel my leaves".
        "cancel my pending request",
        "cancel my leaves",
    ])
    async def test_cancel_naming_a_submitted_request_during_apply_flow_still_interrupts(
        self, fake_slots, query,
    ):
        """Contrast with the bare-cancel test above: a phrase that
        unambiguously names an already-submitted request is trusted to mean
        a genuinely different one, 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(query), writer)

        # 6cd64a4 (application flow fixes): with a half-filled draft open, EVERY
        # interruption is asked about first - "carry on with it, or discard it?" -
        # so the draft is never silently orphaned. The draft itself is untouched.
        # Still recognised as a cancel of a SUBMITTED request, never as a
        # discard of this draft: the draft survives the question.
        assert result["intent"] == "clarify_needed"
        assert "discard it and I'll answer your other question" in result["clarify_message"]
        assert fake_slots.get_slots(1, "conv-1")["leave_type"] == "casual_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
        )

        # 6cd64a4: while the confirmation card is open the turn is HELD in the
        # apply flow until the card is resolved; leave_action_node's own
        # confirmation handler answers it ("reply yes to submit, no to
        # discard...") rather than the question being lost as slot input.
        assert result["intent"] == "apply_leave"
        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)

        # "leave_policy" was renamed "policy" (85ff98d). The draft here is
        # blank, so it is not held - the question is answered directly.
        assert result["intent"] == "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)

        # Still caught as a real question - never swallowed as reason text -
        # and, with this much of the draft filled in, asked about first (6cd64a4).
        assert result["intent"] == "clarify_needed"
        assert fake_slots.get_slots(1, "conv-1").get("reason") is None

    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"
        # _build_intent_prompt now returns a chat-messages list (system +
        # history + final user message) rather than one flattened string —
        # the awaited-slot directive lands in the final message's content.
        assert "the DATES for their leave" in captured["prompt"][-1]["content"]

    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)

        # 6cd64a4: the confirmation card holds the turn in the apply flow, so
        # the reply is never put to the fallback classifier at all - which is
        # stronger than the prompt describing the step: nothing can misfire
        # and drop the ready-to-submit request.
        assert result["intent"] == "apply_leave"
        assert "prompt" not in captured

    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)

        # 6cd64a4: held in the apply flow until the card is resolved - see
        # test_unrelated_topic_interrupts_apply_flow_classification.
        assert result["intent"] == "apply_leave"
        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.
        #
        # "unclear", deliberately NOT the "unknown"/"flagged" the guardrail
        # paths return: a refusal and a comprehension failure used to be
        # recorded identically, so hr_query_log, get_last_intent and every
        # dashboard over them could not tell "we blocked this" from "we did
        # not understand this". Keep these two assertions distinct from the
        # ones in test_moderation_override.py — that is the whole point of
        # the split, and a change that makes them match again has undone it.
        assert result["intent"] == "unclear"
        assert result["is_hr"] is False
        assert result["error"] == "unclear"
        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 TestLeaveActionNodeContextFetch:

    async def test_manager_gets_the_same_flow_as_an_employee(self, monkeypatch, fake_slots):
        """Role no longer gates leave: erp-api's balance/apply/status routes are
        self-scoped for every caller, so a manager asking about their own leave
        goes down the identical path an employee does."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        called = []

        async def _balance(token, **kwargs):
            called.append(token)
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": {"casual_leave": {"total": "12", "remaining": "9"}},
            }}}
        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"
        assert "isn't available for your role" not in result["response_text"]
        assert len(called) == 1
        balance_events = writer.of_type("leave_balance")
        assert len(balance_events) == 1
        assert balance_events[0]["data"]["leave_quota"]["casual_leave"]["remaining"] == "9"

    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 TestNeverGuessAContradictoryOrVagueRequest:
    """HA-667's CEO review, the half with teeth. Now that Helix understands
    most of a message at once, it has to stop GUESSING the rest.

    Each of these reached the confirmation card before, offered for
    submission. Two were not merely wrong but impossible — a 0-day and a
    -1-day leave request.
    """

    @staticmethod
    def _slots(**over):
        base = {"step": "collecting", "leave_type": "casual_leave",
                "session_type_slug": "full_day", "reason": "Personal work",
                "reason_confirmed": True}
        base.update(over)
        return base

    @staticmethod
    def _erp(monkeypatch):
        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)

    # -- a range that ends before it starts --------------------------------
    async def test_a_backwards_range_is_never_offered_for_submission(
        self, monkeypatch, fake_slots,
    ):
        """Live: "-1.0 day(s) ... from 2026-09-17 to 2026-09-15", with a
        Submit button under it."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots())
        mock_extraction(monkeypatch, {"from_date": "2026-11-20", "to_date": "2026-11-10"})

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("from 20th to 10th november"), writer)

        assert writer.of_type("leave_confirmation") == []
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None and saved["to_date"] is None, (
            "both ends are cleared — which one is the mistake is exactly what is unknown"
        )
        assert "date" in result["response_text"].lower()

    async def test_the_check_runs_even_when_a_deterministic_resolver_matched(
        self, monkeypatch, fake_slots,
    ):
        """The guard existed but sat below an early-out that skipped it
        whenever a deterministic resolver had matched — which is precisely
        when the inversion was being introduced."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots())
        mock_extraction(monkeypatch, {"from_date": "2026-11-20", "to_date": "2026-11-10"})

        writer = FakeWriter()
        await leave_action_service.leave_action_node(
            base_state("from 20th to 10th november, tomorrow"), writer)

        assert writer.of_type("leave_confirmation") == []

    # -- a day count that contradicts the range ----------------------------
    async def test_a_day_count_that_contradicts_the_range_is_asked_about(
        self, monkeypatch, fake_slots,
    ):
        """Helix used to let the range win silently."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots())
        mock_extraction(monkeypatch, {"from_date": "2026-11-05", "to_date": "2026-11-10"})

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("2 days leave from 5th to 10th november"), writer)

        assert writer.of_type("leave_confirmation") == []
        assert "2 days" in result["response_text"]
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None and saved["to_date"] is None

    async def test_extraction_can_report_the_contradiction_itself(
        self, monkeypatch, fake_slots,
    ):
        """The CEO's own example. The model RECONCILES such a message unless
        told not to — "2 days leave from Thursday to Saturday" came back as
        Thu..Fri, the count silently winning and Saturday dropped, leaving no
        conflict in the slots for the deterministic check to find."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots())
        mock_extraction(monkeypatch, {
            "from_date": "2026-11-05", "to_date": "2026-11-06",
            "dates_contradict_duration": True,
        })

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("2 days leave from Thursday to Saturday"), writer)

        assert writer.of_type("leave_confirmation") == []
        assert "don't match" in result["response_text"]
        # No numbers quoted: the model reports THAT the message disagrees with
        # itself, not a pair of counts. Anything the resolvers made of the
        # same phrase is a different reading and must not be quoted back.
        for n in ("2 days", "cover 7", "cover 2"):
            assert n not in result["response_text"]

    # -- a week named with nothing inside it -------------------------------
    @pytest.mark.parametrize("query", [
        "apply casual leave next week",
        "I need casual leave for next week",
        "casual leave the following week",
    ])
    async def test_a_bare_week_span_asks_instead_of_taking_the_whole_week(
        self, monkeypatch, fake_slots, query,
    ):
        """It resolved to Monday-Sunday — seven days, weekend included — and
        offered that. An employee's real working days depend on a roster
        Helix cannot see, so it asks."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots())
        # Dated forward off TODAY. A literal here rots the moment it goes
        # past, and the back-date guard then answers before this gate does —
        # the test would fail for a reason unrelated to what it checks.
        _mon = datetime.date.today() + datetime.timedelta(days=(7 - datetime.date.today().weekday()))
        mock_extraction(monkeypatch, {"from_date": _mon.isoformat(),
                                      "to_date": (_mon + datetime.timedelta(days=6)).isoformat()})

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(base_state(query), writer)

        assert writer.of_type("leave_confirmation") == []
        assert writer.of_type("done")[0]["data"].get("requires_date_input") is True, (
            "the date picker is what the review asks for when dates can't be determined"
        )
        assert "exact dates" in result["response_text"].lower()

    @pytest.mark.parametrize("query", [
        "apply casual leave next week monday",
        "apply casual leave next week from monday to wednesday",
        "apply casual leave on 14 september next week",
    ])
    def test_a_week_with_a_day_named_inside_it_is_left_alone(self, query):
        """The exclusion that keeps the rule safe: these name something
        inside the week, so they are ordinary date phrases."""
        assert leave_action_service._names_a_bare_week_span(query) is False

    # -- two requests in one message ---------------------------------------
    @pytest.mark.parametrize("query,expected_first", [
        ("I want casual leave tomorrow and sick leave on Friday", "Casual Leave"),
        ("I need sick leave and casual leave next week", "Sick Leave"),
    ])
    async def test_two_leave_types_in_one_message_are_taken_one_at_a_time(
        self, monkeypatch, fake_slots, query, expected_first,
    ):
        """Extraction does not refuse a two-request message, it BLENDS one.
        "casual leave tomorrow and sick leave on Friday" came back as sick
        leave tomorrow — a request the employee never made."""
        self._erp(monkeypatch)
        fake_slots.clear_slots(1, "conv-1")
        mock_extraction(monkeypatch, {"leave_type": "sick_leave",
                                      "from_date": "2026-09-16", "to_date": "2026-09-16"})

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(base_state(query), writer)

        assert "one leave request at a time" in result["response_text"]
        assert expected_first in result["response_text"], (
            "offers the type they named FIRST, not whichever the match table lists first"
        )
        assert writer.of_type("leave_confirmation") == []

    async def test_a_single_type_is_unaffected(self, monkeypatch, fake_slots):
        self._erp(monkeypatch)
        fake_slots.clear_slots(1, "conv-1")
        mock_extraction(monkeypatch, {
            "leave_type": "casual_leave", "from_date": "2026-11-05", "to_date": "2026-11-05",
            "session_type_slug": "full_day", "reason": "Personal work",
        })

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("apply casual leave on 5th november for personal work"), writer)

        assert "one leave request at a time" not in result["response_text"]

    async def test_a_second_type_mid_flow_is_a_type_change_not_a_second_request(
        self, monkeypatch, fake_slots,
    ):
        """Scoped to a FRESH request on purpose. Mid-flow "I have no casual
        leave, use sick leave instead" names two types and is one request."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots(
            from_date="2026-11-05", to_date="2026-11-05"))
        mock_extraction(monkeypatch, {"leave_type": "sick_leave"})

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("I have no casual leave, use sick leave instead"), writer)

        assert "one leave request at a time" not in result["response_text"]

class TestReasonIsCleanedAndConfirmedBeforeSaving:
    """HA-666. Helix cleans the leave reason — strips filler, fixes plain
    spelling, capitalises — but the CEO review's conditions are the ones with
    teeth, and they are what this class pins:

      * nothing AI-touched is saved without the employee seeing it
      * a word Helix cannot read confidently is ASKED about, not guessed
      * a word it already corrected is NOT asked about (that reads as Helix
        not understanding its own answer)
      * filler that strips to nothing never becomes the reason

    The prompt work is exercised against the real model separately; this is
    the deterministic half, where the guarantees actually hold.
    """

    @staticmethod
    def _slots(**over):
        future = (datetime.date.today() + datetime.timedelta(days=30)).isoformat()
        base = {"step": "collecting", "leave_type": "casual_leave",
                "from_date": future, "to_date": future,
                "session_type_slug": "full_day", "reason": None}
        base.update(over)
        return base

    @staticmethod
    def _erp(monkeypatch):
        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)

    # -- read back for approval on EVERY flow ------------------------------
    async def test_every_application_asks_the_employee_to_approve_the_reason(
        self, monkeypatch, fake_slots,
    ):
        """CEO point 1. Not only when a word was ambiguous — by this point
        Helix has stripped filler, fixed spelling and recapitalised, and the
        employee has seen none of it."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots())
        mock_extraction(monkeypatch, {"reason": "Personal work"})

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(base_state("persnl work"), writer)

        assert 'did you mean "Personal work"' in result["response_text"]
        assert writer.of_type("leave_confirmation") == [], (
            "nothing may be confirmed before the reason is approved"
        )

    async def test_approving_it_moves_on_and_the_card_names_it(self, monkeypatch, fake_slots):
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots(
            reason="Personal work", reason_confirm={"as_typed": "", "suggestion": ""}))
        mock_extraction(monkeypatch, {})

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

        assert writer.of_type("leave_confirmation")[0]["data"]["reason"] == "Personal work"
        assert "reason: personal work" in result["response_text"].lower(), (
            "the card field alone is not the employee SEEING it"
        )

    async def test_an_edit_helix_rewrote_is_confirmed_on_its_own_terms(
        self, monkeypatch, fake_slots,
    ):
        """Helix cleans a rewrite exactly as it cleaned the first attempt, so
        a CHANGED rewrite is just as much an AI-modified reason. It gets its
        own approval — it does not slip through on the strength of the first
        answer."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots(
            reason="Personal work", reason_confirm={"as_typed": "", "suggestion": ""}))
        # "no, i have fever" is stored as "Fever" — filler stripped, capital
        # added. That is a modification, so it is read back.
        mock_extraction(monkeypatch, {"reason": "Fever"})
        mock_confirmation_verdict(monkeypatch)

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("no , i have fever"), writer)

        assert fake_slots.get_slots(1, "conv-1")["reason"] == "Fever"
        assert 'did you mean "Fever"' in result["response_text"]
        assert writer.of_type("leave_confirmation") == []

    async def test_an_edit_stored_verbatim_needs_no_second_approval(
        self, monkeypatch, fake_slots,
    ):
        """The other half of the rule. If the employee types the reason and
        Helix stores exactly that, there is no AI modification to approve —
        asking would spend a turn confirming their own words back at them.
        The confirmation card still names it before anything is submitted."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots(
            reason="Personal work", reason_confirm={"as_typed": "", "suggestion": ""}))
        mock_extraction(monkeypatch, {"reason": "Personal work at the bank"})
        mock_confirmation_verdict(monkeypatch)

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("personal work at the bank"), writer)

        assert fake_slots.get_slots(1, "conv-1")["reason"] == "Personal work at the bank"
        assert "did you mean" not in result["response_text"].lower()
        assert writer.of_type("leave_confirmation")[0]["data"]["reason"] == "Personal work at the bank"
        assert "reason: personal work at the bank" in result["response_text"].lower()

    # -- the rule that decides whether the question is worth asking --------
    @pytest.mark.parametrize("typed,cleaned,same", [
        ("Fever", "Fever", True),                                  # untouched
        ("personal work", "Personal work", True),                  # case only
        ("personal work.", "Personal work", True),                 # trailing stop
        ("  Fever  ", "Fever", True),                              # whitespace
        ("i have personal work", "Personal work", False),          # filler stripped
        ("The reason is vacation", "Vacation", False),             # filler stripped
        ("feever and weaknes", "Fever and weakness", False),       # spelling fixed
        ("fever", "Fever and cough", False),                       # words added
    ])
    def test_only_a_changed_reason_needs_approving(self, typed, cleaned, same):
        """Equality, deliberately not containment — a containment test would
        wave through "i have personal work" -> "Personal work", and stripping
        filler IS a modification the employee should see."""
        assert leave_action_service._reason_matches_what_was_typed(typed, cleaned) is same

    async def test_rejecting_it_asks_again_instead_of_guessing(self, monkeypatch, fake_slots):
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots(
            reason="Personal work", reason_confirm={"as_typed": "", "suggestion": ""}))
        mock_extraction(monkeypatch, {})

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(base_state("no"), writer)

        assert fake_slots.get_slots(1, "conv-1")["reason"] is None
        assert "what would you like the reason to say" in result["response_text"].lower()
        assert writer.of_type("leave_confirmation") == []

    # -- an unreadable word is named in that same question -----------------
    async def test_an_unreadable_word_is_named_rather_than_shown_as_settled(
        self, monkeypatch, fake_slots,
    ):
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots())
        mock_extraction(monkeypatch, {
            "reason": "Fvr", "reason_uncertain_as_typed": "fvr",
            "reason_uncertain_suggestion": "fever",
        })

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(base_state("reason is fvr"), writer)

        assert '"fvr"' in result["response_text"] and '"fever"' in result["response_text"]
        assert writer.of_type("leave_confirmation") == []

    async def test_yes_applies_the_suggestion_keeping_its_case(self, monkeypatch, fake_slots):
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots(
            reason="Fvr", reason_confirm={"as_typed": "fvr", "suggestion": "fever"}))
        mock_extraction(monkeypatch, {})

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

        assert fake_slots.get_slots(1, "conv-1")["reason"] == "Fever", (
            "the lowercase suggestion must not un-capitalise the reason"
        )
        assert "reason: fever" in result["response_text"].lower()

    async def test_no_to_a_spelling_offer_keeps_the_word_and_the_reason(
        self, monkeypatch, fake_slots,
    ):
        """"no" here rejects the SPELLING, not the reason — so unlike a plain
        rejection it must not throw the reason away and start over."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots(
            reason="Fvr", reason_confirm={"as_typed": "fvr", "suggestion": "fever"}))
        mock_extraction(monkeypatch, {})

        writer = FakeWriter()
        await leave_action_service.leave_action_node(base_state("no"), writer)

        assert fake_slots.get_slots(1, "conv-1")["reason"] == "Fvr"
        assert len(writer.of_type("leave_confirmation")) == 1

    async def test_a_one_word_answer_replaces_only_that_word(self, monkeypatch, fake_slots):
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots(
            reason="Mtg w/ drs", reason_confirm={"as_typed": "drs", "suggestion": "doctors"}))
        mock_extraction(monkeypatch, {})
        mock_confirmation_verdict(monkeypatch)

        writer = FakeWriter()
        await leave_action_service.leave_action_node(base_state("dentists"), writer)

        assert fake_slots.get_slots(1, "conv-1")["reason"] == "Mtg w/ dentists", (
            "answering one word must not reduce the reason to only that word"
        )

    # -- a word already corrected is never singled out ---------------------
    @pytest.mark.parametrize("reason,as_typed,suggestion", [
        ("Weakness", "weaknes", "weakness"),
        ("Vacation", "vacationn", "vacation"),
        ("Personal work", "persnal", "personal"),
        ("Fever", "fvr", "fvr"),
        ("Court hearing case no 4471/2026",
         "court hearing case no 4471/2026", "court hearing"),
    ])
    async def test_a_word_already_corrected_is_never_singled_out(
        self, monkeypatch, fake_slots, reason, as_typed, suggestion,
    ):
        """The reason is still read back — that is every flow — but with the
        plain question. Quoting a word Helix already fixed reads as it not
        understanding its own answer."""
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots())
        mock_extraction(monkeypatch, {
            "reason": reason, "reason_uncertain_as_typed": as_typed,
            "reason_uncertain_suggestion": suggestion,
        })

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(base_state("whatever"), writer)

        assert f'did you mean "{reason}"' in result["response_text"]
        assert f'"{as_typed}"' not in result["response_text"]

    # -- filler that strips to nothing is never stored ---------------------
    async def test_filler_only_reply_is_never_saved_as_the_reason(self, monkeypatch, fake_slots):
        self._erp(monkeypatch)
        fake_slots.set_slots(1, "conv-1", self._slots())

        first = None
        for turn, text in enumerate(("my reason is that", "I am applying because"), start=1):
            mock_extraction(monkeypatch, {})
            writer = FakeWriter()
            result = await leave_action_service.leave_action_node(base_state(text), writer)
            saved = fake_slots.get_slots(1, "conv-1")
            assert saved["reason"] is None, f"filler stored on turn {turn}: {text!r}"
            assert writer.of_type("leave_confirmation") == []
            if turn == 1:
                first = result["response_text"]
            else:
                assert "valid reason" in result["response_text"].lower()
                assert result["response_text"] != first, (
                    "the second ask must not repeat the first verbatim — that is "
                    "the loop this branch exists to break"
                )

class TestLeaveAbbreviationsComeFromCompanyConfig:
    """HA-665 after the review. Helix holds no opinion about what "CL" means.
    It reads which leave types a company HAS, then asks whether what the
    employee typed is one of that company's abbreviations for them.

    The order is the point: configuration first, shorthand second. A company
    calling casual leave "PL" works with no code change, and a company
    without earned leave never resolves "EL" to anything.
    """

    # Exactly what /api/v1/ai/leaves/abbreviations returns today.
    API = {
        "A": "Absent", "L": "Leave", "EL": "Earned Leave", "CL": "Casual Leave",
        "SL": "Sick Leave", "CO": "Comp Off", "LWP": "Leave Without Pay",
        "HD": "Half Day Leave", "SHL": "Short Leave", "P": "Present", "O": "Off",
        "PA": "Half Day Absent", "R(PA)": "Approved Regularization",
        "R(A)": "Approved Regularization", "R(P)": "Approved Regularization",
        "LC": "Half Day Absent", "NCNS": "No Come No Show",
    }
    FOUR = [
        {"slug": "casual_leave", "name": "Casual Leave"},
        {"slug": "sick_leave", "name": "Sick Leave"},
        {"slug": "short_leave", "name": "Short Leave"},
        {"slug": "comp_off", "name": "Comp Off"},
    ]

    def test_only_configured_types_survive(self):
        assert leave_action_service._abbreviations_for_configured_types(
            self.API, self.FOUR) == {
            "CL": "casual_leave", "SL": "sick_leave",
            "SHL": "short_leave", "CO": "comp_off"}

    def test_a_type_the_company_does_not_have_gets_no_abbreviation(self):
        """No Earned Leave here, so "EL" means nothing — even though the
        endpoint lists it."""
        kept = leave_action_service._abbreviations_for_configured_types(self.API, self.FOUR)
        assert "EL" not in kept and "LWP" not in kept

    @pytest.mark.parametrize("junk", [
        "A", "P", "O",              # attendance markers, not leave types
        "L",                        # a bare letter loose in a leave parser
        "HD",                       # a session type here, not a type to apply for
        "NCNS", "LC", "PA", "R(P)", "R(A)", "R(PA)",
    ])
    def test_non_leave_codes_discard_themselves(self, junk):
        """None of these match a configured slug, so the gate drops them on
        its own — there is no exclusion list to keep in sync with the API."""
        kept = leave_action_service._abbreviations_for_configured_types(self.API, self.FOUR)
        assert junk not in kept

    def test_a_company_with_more_types_gets_more_abbreviations(self):
        six = self.FOUR + [
            {"slug": "earned_leave", "name": "Earned Leave"},
            {"slug": "leave_without_pay", "name": "Leave Without Pay"},
        ]
        kept = leave_action_service._abbreviations_for_configured_types(self.API, six)
        assert kept["EL"] == "earned_leave" and kept["LWP"] == "leave_without_pay"

    def test_a_company_specific_abbreviation_needs_no_code_change(self):
        """The case that proves nothing is hardcoded."""
        assert leave_action_service._abbreviations_for_configured_types(
            {"PL": "Casual Leave"}, self.FOUR) == {"PL": "casual_leave"}

    @pytest.mark.parametrize("payload,configured", [
        (None, FOUR), ({}, FOUR), (API, None), (API, []),
    ])
    def test_missing_data_is_never_guessed_around(self, payload, configured):
        """No config or no abbreviations means no shorthand. Helix does NOT
        fall back to a built-in table — that is the thing the review ruled
        out."""
        assert leave_action_service._abbreviations_for_configured_types(
            payload, configured) == {}

    def test_display_name_and_slug_are_both_accepted(self):
        """The two endpoints spell the same type differently."""
        assert leave_action_service._abbreviations_for_configured_types(
            {"CL": "casual leave", "SL": "sick_leave"}, self.FOUR) == {
            "CL": "casual_leave", "SL": "sick_leave"}


class TestReasonExamplesMatchTheLeaveType:
    """HA-665's third requirement. Asking for a reason with no examples left
    employees guessing at the register expected; asking with SICK examples
    while they apply for casual leave is worse."""

    @pytest.mark.parametrize("slug,expected", [
        ("sick_leave", "Fever"),
        ("casual_leave", "Home maintenance"),
        ("earned_leave", "Vacation"),
        ("short_leave", "Bank work"),
    ])
    def test_each_type_gets_its_own_examples(self, slug, expected):
        assert expected in leave_action_service._reason_examples_for(slug)

    def test_sick_examples_never_appear_for_casual_leave(self):
        casual = leave_action_service._reason_examples_for("casual_leave")
        assert "Fever" not in casual and "Medical checkup" not in casual

    @pytest.mark.parametrize("slug", [None, "", "comp_off", "some_custom_type"])
    def test_unknown_or_unlisted_types_get_neutral_examples(self, slug):
        """The fallback deliberately spans personal AND medical, so it steers
        nobody toward either — including when the reason is asked before any
        type is known."""
        text = leave_action_service._reason_examples_for(slug)
        assert "Personal work" in text and "Doctor's appointment" in text

    def test_examples_are_rendered_ready_to_append(self):
        assert leave_action_service._reason_examples_for("sick_leave").startswith(" (e.g. ")


class TestSwitchingLeaveTypeMidConversation:
    """HA-665's mid-flow-switch edge case: the type updates AND the suggested
    reason examples update with it."""

    @staticmethod
    def _erp(monkeypatch):
        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"},
                                "sick_leave": {"total": "7", "remaining": "7"}},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_status", _no_conflicting_leaves)

    async def test_the_switch_message_is_not_stored_as_the_reason(
        self, monkeypatch, fake_slots,
    ):
        """Live: "apply SL" -> "full day" -> "actually make it CL" saved the
        reason as "actually make it CL" and went straight to confirmation.
        The type switch had already spent one attempt at the reason, so the
        raw-text fallback fired on the very next turn."""
        self._erp(monkeypatch)
        future = (datetime.date.today() + datetime.timedelta(days=20)).isoformat()
        fake_slots.set_slots(1, "conv-1", {
            "step": "collecting", "leave_type": "sick_leave",
            "from_date": future, "to_date": future,
            "session_type_slug": "full_day", "reason": None,
            "reason_attempts": 1,
        })
        mock_extraction(monkeypatch, {"leave_type": "casual_leave"})

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("actually make it CL"), writer)

        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["leave_type"] == "casual_leave", "the type must switch"
        assert saved["reason"] is None, "the switch message is not a reason"
        assert writer.of_type("leave_confirmation") == []
        # ...and the NEW type's examples come with the re-ask.
        assert "Casual Leave" in result["response_text"]
        assert "Home maintenance" in result["response_text"]
        assert "Fever" not in result["response_text"]

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_applied_leaves", _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", "reason_confirmed": True,
        })

        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
        # Configured in erp-api, but not something Helix can file (product rule,
        # HELIX_APPLICABLE_LEAVE_TYPES) - so never offered.
        assert "Comp Off" not in message
        assert "Leave Without Pay" not in message

    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_applied_leaves", _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. "yes, submit
        # it" is the confirm button's own text and a whole-message affirmative,
        # so it goes straight through (tiers 1 and 2 in leave_action_service's
        # banner); only a yes carrying a CHANGE is held back to be asked about.
        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_applied_leaves", _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
        )
        result = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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()
        result = await hr_graph.leave_action_node(
            base_state(f"apply sick leave from {range_from.isoformat()} to {range_to.isoformat()}"), writer
        )
        result = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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_applied_leaves", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {
            "leave_type": "short_leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
            # Short leave is part of ONE day, so the flow asks which half when
            # none is given (7cbef21) - supplied here so this test stays about
            # the multi-day guard it contrasts with.
            "session_type_slug": "first_half_day", "reason": "personal",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("short leave on 1 Sept first half reason personal"), writer)
        result = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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_applied_leaves", _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)
        result = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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. The old "accept it verbatim"
        # fallback was removed on purpose - it filed "I want to apply for sick
        # leave" as the reason a manager read ("Nothing is ever saved unasked").
        # The loop it guarded against is prevented instead by REWORDING the
        # ask, so it names what is missing rather than repeating itself.
        mock_extraction(monkeypatch, {})
        writer2 = FakeWriter()
        result2 = await hr_graph.leave_action_node(base_state("I want to apply for sick leave"), writer2)

        assert writer2.of_type("leave_confirmation") == []
        assert result2["response_text"] != result["response_text"]  # reworded, not repeated
        assert "valid reason" in result2["response_text"].lower()
        saved2 = fake_slots.get_slots(1, "conv-1")
        assert saved2["reason"] is None               # nothing saved unasked
        assert saved2["reason_attempts"] == 2

    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_applied_leaves", _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)

        # What this test exists for: never "We don't have a fever009 leave type".
        assert "don't have" not in result["response_text"].lower()
        # The raw-text fallback it used to reach is gone (see the test above),
        # so an unreadable reply is asked for again rather than filed as the
        # reason - still as a REASON question, never a leave-type one.
        assert "reason" in result["response_text"].lower()
        assert writer.of_type("leave_confirmation") == []
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["leave_type"] == "sick_leave"  # untouched throughout
        assert saved["reason"] is None

    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", "_pending_submit": True, "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", "_pending_submit": True, "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_applied_leaves", 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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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)

        # 10 Aug is the date this scenario is written around, so "today"
        # has to sit before it - otherwise the back-date check answers
        # first and the balance rejection under test never runs.
        # Both, like the _pin_today fixture: the apply flow reads
        # _today_in_app_timezone, the roll-forward-if-past check reads
        # _today, and leaving them disagreeing rolls to_date a year on.
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone",
                            lambda: date(2026, 8, 5))
        monkeypatch.setattr(leave_action_service, "_today", lambda: date(2026, 8, 5))

        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_applied_leaves", _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_applied_leaves", _status)

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

        # 10 Aug is the date this scenario is written around, so "today"
        # has to sit before it - otherwise the back-date check answers
        # first and the balance rejection under test never runs.
        # Both, like the _pin_today fixture: the apply flow reads
        # _today_in_app_timezone, the roll-forward-if-past check reads
        # _today, and leaving them disagreeing rolls to_date a year on.
        monkeypatch.setattr(leave_action_service, "_today_in_app_timezone",
                            lambda: date(2026, 8, 5))
        monkeypatch.setattr(leave_action_service, "_today", lambda: date(2026, 8, 5))

        mock_extraction(monkeypatch, {
            "leave_type": "earned_leave", "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 earned leave 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", "_pending_submit": True, "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, **kwargs):
            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_applied_leaves", _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,
        )
        result = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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_applied_leaves", _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_queries_every_status_not_just_pending(self, monkeypatch, fake_slots):
        """Regression guard for a gap that hid behind a too-generous mock.

        _find_conflicting_leave accepts "pending" OR "approved", but it used
        to query /leave/pending, which returns PENDING rows only — so the
        "approved" half could never match and an already-APPROVED leave on
        the requested date went undetected all the way to the confirmation
        card. test_conflicting_date_blocks_before_confirmation_not_after did
        not catch it: it stubs an approved row onto the conflict lookup, so
        the mock answered something the real endpoint never would.

        This test pins the REQUEST rather than the response — leave_status
        must be "all", and the single-day request must still be date-scoped
        so the paginate(20) fix beside it survives. A stub cannot paper over
        a wrong query the way it can paper over a wrong filter."""
        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)

        seen = {}

        async def _applied(token, leave_status="all", applied_leave_date=None, **kwargs):
            seen.update(leave_status=leave_status, applied_leave_date=applied_leave_date)
            # Only an APPROVED row — the exact shape /leave/pending could
            # never have returned.
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                {"id": 77, "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_applied_leaves", _applied)

        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()
        result = await hr_graph.leave_action_node(base_state("2026-08-14"), writer)

        assert seen["leave_status"] == "all", (
            "pending-only would make the approved-leave conflict invisible")
        assert seen["applied_leave_date"] == "2026-08-14", (
            "single-day requests must stay date-scoped past the paginate(20) window")
        apply_mock.assert_not_called()
        assert writer.of_type("leave_confirmation") == []
        assert "already applied" in result["response_text"].lower()
        assert "Earned Leave" in result["response_text"]

    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_applied_leaves", _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)
        result = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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_applied_leaves", _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)
        result = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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
        earned_leave, 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": {
                    "earned_leave": {"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": "earned_leave", "name": "Earned Leave"},
                    {"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_applied_leaves", _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": "earned_leave", "from_date": "2027-10-01", "to_date": "2027-10-01", "session_type_slug": "full_day",
            "reason": "personal reasons",
        })
        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("apply earned leave for 2027-10-01"), writer)

        apply_mock.assert_not_called()
        message = result["response_text"]
        assert "no Earned Leave 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": {
                    "earned_leave": {"total": "0", "remaining": "0"},
                    "casual_leave": {"total": "7", "remaining": "5"},
                },
                "leave_settings": {"leave_type": [
                    {"slug": "earned_leave", "name": "Earned Leave"},
                    {"slug": "casual_leave", "name": "Casual Leave"},
                ]},
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_balance", _balance)
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _no_conflicting_leaves)

        # Turn 1: zero-balance type -> rejected, leave_type + from_date cleared.
        mock_extraction(monkeypatch, {
            "leave_type": "earned_leave", "from_date": "2027-10-01", "to_date": "2027-10-01", "session_type_slug": "full_day",
            "reason": "personal reasons",
        })
        writer1 = FakeWriter()
        result1 = await hr_graph.leave_action_node(base_state("apply earned leave for 2027-10-01"), writer1)
        assert "no Earned Leave 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 NOT repeat the zero-balance message, and must not skip
        # past the (now again missing) leave_type check.
        #
        # It must also not re-ask for dates. The rejection stashes them
        # rather than dropping them (balance_retry_from_date/to_date) and a
        # reply naming a DIFFERENT type brings them back — the whole point
        # of the live report behind that behaviour was that switching type
        # made the employee retype dates they had already given. So the
        # flow moves on to the next genuinely missing slot instead.
        mock_extraction(monkeypatch, {"leave_type": "casual_leave"})
        writer2 = FakeWriter()
        result2 = await hr_graph.leave_action_node(base_state("casual leave instead"), writer2)
        assert "no Earned Leave balance" not in result2["response_text"]
        assert "what dates" not in result2["response_text"].lower()
        saved2 = fake_slots.get_slots(1, "conv-1")
        assert saved2["leave_type"] == "casual_leave"
        assert saved2["from_date"] == "2027-10-01"   # carried across the switch
        assert saved2["to_date"] == "2027-10-01"
        # The stash is consumed, not left to re-fire on a later turn.
        assert saved2.get("balance_retry_leave_type") 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_applied_leaves", _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", "_pending_submit": True, "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_cancels_the_draft(
        self, monkeypatch, fake_slots, query,
    ):
        """Declining must never loop (the original bug: the identical
        confirmation re-shown forever, and "actually never mind" filed as the
        reason) and must never submit. A whole-message decline is tier 2 --
        unambiguous, so it resolves the card on sight. A decline carrying a
        CHANGE ("no but make it 3 days") is tier 3 and is asked about instead;
        see tests/test_confirmation_gate_is_load_bearing.py."""
        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 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 "discarded" 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
    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", "_pending_submit": True, "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", "_pending_submit": True, "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_applied_leaves", _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", "_pending_submit": True, "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_applied_leaves", _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 TestCancelCardButtonsAreNotStolenByAnApplyDraft:
    """QA: pressing "Keep Request" on a cancel-confirmation card replied
    "I've cancelled that leave request" — while actually discarding the
    in-progress APPLICATION and leaving the request the card was about
    untouched. Wrong about both halves of what happened.

    An apply draft deliberately survives a switch into the cancel flow (see
    resume_reminder — an interruption must not silently bin a half-finished
    application). But classify_node's apply mid-flow fast-path keyed only on
    "is there a draft", never on "is the cancel flow mid-question", so once
    both were live the draft won every reply, including the cancel card's own
    buttons.

    "Confirm Cancellation" was the more dangerous half: it also landed in the
    apply flow, on the draft's own "shall I submit this?" step, as an
    affirmative — submitting an application at the moment the user was trying
    to cancel a different leave.
    """

    APPLY_DRAFT = {"step": "awaiting_confirmation", "leave_type": "sick_leave",
                   "from_date": "2026-09-25", "to_date": "2026-09-25", "reason": "abc"}
    CANCEL_PENDING = {"step": "awaiting_confirmation",
                      "selected": {"reference": "LR-253", "leave_type": "Short Leave",
                                   "from_date": "2026-09-18", "to_date": "2026-09-18"}}

    @staticmethod
    async def _classify(query, slots, cancel_state, llm_says="cancel_leave"):
        """`llm_says` stands in for the real classifier on the turns that
        genuinely reach it (a bare "yes" carries no keyword of its own, so it
        is answered by the LLM with the awaited-slot prompt, not by a
        fast-path). Set it to what a correct classifier would return for the
        scenario, so the assertion is about the ROUTING under test rather
        than about the stub."""
        import services.classify_node as cn
        state = {"query": query, "context": [], "company_id": 1,
                 "conversation_id": "conv-1", "bearer_token": "t"}
        with patch.object(cn.leave_slot_service, "get_slots", return_value=slots), \
             patch.object(cn.leave_cancel_state, "get_state", return_value=cancel_state), \
             patch.object(cn.leave_eligibility_clarify_state, "get_state", return_value=None), \
             patch.object(cn.leave_type_clarify_state, "get_state", return_value=None), \
             patch.object(cn.leave_history_clarify_state, "get_state", return_value=None), \
             patch.object(cn, "classify_intent_structured",
                          AsyncMock(return_value=(llm_says, None, False))):
            return await cn.classify_node(state, lambda e: None)

    @pytest.mark.parametrize("button", ["Keep Request", "Confirm Cancellation"])
    async def test_cancel_card_button_reaches_the_cancel_flow(self, button):
        result = await self._classify(button, self.APPLY_DRAFT, self.CANCEL_PENDING)
        assert result["intent"] == "cancel_leave"

    @pytest.mark.parametrize("reply", ["cancel", "yes", "sick leave"])
    async def test_apply_flow_still_owns_its_replies_with_no_cancel_question(self, reply):
        """Negative control — the guard must only stand the apply fast-path
        down while a cancel question is genuinely open."""
        result = await self._classify(reply, self.APPLY_DRAFT, None,
                                      llm_says="apply_leave")
        assert result["intent"] == "apply_leave"

    @pytest.mark.parametrize("reply", ["cancel", "yes"])
    async def test_a_declined_cancel_state_does_not_stand_the_apply_flow_down(self, reply):
        """"declined" is a passive short-lived memory (so a vague "cancel
        again" can resume), not a question awaiting an answer — it must not
        pull replies out of the apply flow."""
        declined = {"step": "declined", "selected": {"reference": "LR-253",
                                                     "leave_type": "Short Leave"}}
        result = await self._classify(reply, self.APPLY_DRAFT, declined,
                                      llm_says="apply_leave")
        assert result["intent"] == "apply_leave"

    def test_keep_request_says_kept_not_cancelled(self):
        selected = {"reference": "LR-253", "leave_type": "Short Leave",
                    "from_date": "2026-09-18", "to_date": "2026-09-18"}
        assert leave_action_service._decide_cancel_confirmation("Keep Request", {}) == "decline"
        message = leave_action_service._keep_request_message(selected)
        assert "kept" in message.lower()
        assert "cancelled" not in message.lower()
        assert "LR-253" in message

    @pytest.mark.parametrize("text,expected", [
        ("Keep Request", True),
        ("keep request", True),
        ("KEEP REQUEST", True),
        ("Keep Request.", True),
        ("Confirm Cancellation", True),
        # Exact match on the whole message, never a substring — ordinary
        # typed text that happens to contain the words is not a button press.
        ("please keep request open for now", False),
        ("cancel", False),
        ("", False),
    ])
    def test_button_sentinel_is_an_exact_match(self, text, expected):
        assert leave_action_service._is_cancel_card_button(text) is expected

    def test_a_button_press_never_discards_an_apply_draft(self):
        """Second line of defence: even with the cancel state expired, a late
        button press must not fall into the apply branch's discard check —
        that is what produced the wrong "I've cancelled that leave request"."""
        assert leave_action_service._is_declining_or_cancelling("Keep Request") is True
        assert leave_action_service._is_cancel_card_button("Keep Request") is True


class TestNumericDateIsVettedDeterministically:
    """QA P0: "08/09/2026" (8 Sep, future) came back as 09/08/2026 and was
    refused as already passed.

    All-numeric dates are the one input where the LLM can return a
    well-formed but WRONG answer that nothing downstream can detect — a
    month-first reading of a day-first date is still a valid date, just a
    different one, and when it lands in the past the request is refused.

    resolve_numeric_date_range is the deterministic guard against that, and
    it was present in hr_graph.py's original leave_action_node. When that
    pipeline was ported into leave_action_service it was the ONE resolver
    dropped (the port gained three weekday resolvers and lost this), leaving
    numeric dates riding entirely on the LLM — exactly what this module's own
    header forbids: "do not rely only on the LLM to calculate dates". It was
    dropped from BOTH _apply_deterministic_date_overrides and
    _resolve_deterministic_date_range, so both are covered here.

    `today` is passed explicitly rather than read from the clock, so these
    assertions are fixed in time and cannot rot.
    """

    TODAY = date(2026, 9, 7)

    @pytest.mark.parametrize("query,expected_from,expected_to", [
        # The QA case: day-first 8 Sep, not month-first 9 Aug (which is past).
        ("08/09/2026", "2026-09-08", "2026-09-08"),
        ("from 08/09/2026 to 08/09/2026", "2026-09-08", "2026-09-08"),
        ("apply casual leave on 08/09/2026", "2026-09-08", "2026-09-08"),
        # The historic 32-day bug named in the override's own comment.
        ("From 10/09/2026 to 11/09/2026", "2026-09-10", "2026-09-11"),
        # Dash and dot separators read day-first too.
        ("from 08-09-2026 to 10-09-2026", "2026-09-08", "2026-09-10"),
    ])
    def test_numeric_date_overrides_a_month_first_llm_guess(
        self, query, expected_from, expected_to,
    ):
        # The LLM deliberately returns the month-first (wrong) reading — the
        # deterministic override must replace it, not defer to it.
        swapped = {"from_date": "2026-08-09", "to_date": "2026-08-09"}
        slots = {"leave_type": "casual_leave", **swapped}
        matched = leave_action_service._apply_deterministic_date_overrides(
            query, slots, swapped, self.TODAY,
        )
        assert matched is True, "numeric dates must be vetted by tier 1, not left to the LLM"
        assert slots["from_date"] == expected_from
        assert slots["to_date"] == expected_to

    def test_a_corrected_future_date_is_no_longer_refused_as_past(self):
        """The user-visible half of the bug: once the date is read day-first
        it is in the future, so the past-date refusal must not fire."""
        swapped = {"from_date": "2026-08-09", "to_date": "2026-08-09"}
        slots = {"leave_type": "casual_leave", **swapped}
        matched = leave_action_service._apply_deterministic_date_overrides(
            "08/09/2026", slots, swapped, self.TODAY,
        )
        needs_confirmation = leave_action_service._llm_date_needs_confirmation(
            "08/09/2026", slots["from_date"], slots["to_date"], matched, self.TODAY,
        )
        assert needs_confirmation is None

    @pytest.mark.parametrize("query,expected", [
        ("show my leaves from 08/09/2026 to 10/09/2026", ("2026-09-08", "2026-09-10")),
        ("leaves on 08/09/2026", ("2026-09-08", "2026-09-08")),
    ])
    def test_leave_status_range_reads_numeric_dates_day_first_too(self, query, expected):
        # Same resolver, second call site — a leave-status query reads
        # "08/09/2026" exactly as an apply-leave one does.
        assert leave_action_service._resolve_deterministic_date_range(
            query, self.TODAY) == expected

    def test_non_numeric_phrasing_is_untouched(self):
        """Negative control: adding the numeric branch must not start
        claiming queries that name no numeric date at all."""
        slots = {"leave_type": "casual_leave", "from_date": None, "to_date": None}
        leave_action_service._apply_deterministic_date_overrides(
            "apply casual leave", slots, {}, self.TODAY,
        )
        assert slots["from_date"] is None
        assert slots["to_date"] is None


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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_a_duration_that_contradicts_the_explicit_range_is_asked_about(
        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_applied_leaves", _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"):
            _r = await hr_graph.leave_action_node(
                base_state("apply from 5th to 10th november for a week"), writer,
            )
        # The range no longer quietly wins. "5th to 10th" is 6 days and "a week"
        # is 7, and nothing here knows which half is the mistake - so it asks
        # (CEO review point 3: never guess when the request contradicts
        # itself). Letting one side win also reached the card as 0.0 / -1.0
        # day(s) once downstream resolvers moved only one end.
        assert _r["response_text"] == ("You mentioned 7 days, but the dates you gave cover 6. "
                                       "Could you tell me the exact dates you'd like to take off?")
        saved = fake_slots.get_slots(1, "conv-1")
        assert saved["from_date"] is None and saved["to_date"] is None
        assert saved["leave_type"] == "casual_leave"   # the rest of the request is kept
        assert writer.of_type("leave_confirmation") == []
        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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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)
        readback = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_applied_leaves", _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_asks_for_the_exact_days(self, monkeypatch, fake_slots):
        # No weekday named at all. This used to resolve to the whole week;
        # 288c5fa ("date clarification message") asks for the exact days
        # instead, because checking a speculative Mon..Sun span for clashes
        # rejected requests over one unrelated booked day inside 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_applied_leaves", _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"] is None and saved["to_date"] is None
        assert saved["leave_type"] == "casual_leave"   # the rest of the request is kept


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_states_the_month_it_inferred(
        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.

        Unlike every other branch of this safety net, this one DOES name a
        date (2026-09-09 follow-up). Only the MONTH was ever in doubt: the
        day number came from the user verbatim and _next_date_on_day_of_month
        is plain arithmetic, not the model's guess — so the inference is
        stated with its reason and a bare "yes" can take it, rather than
        making the user retype a day they already gave."""
        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)

        message = result["response_text"]
        # The inference is named, with the reason for it — the whole point
        # of the report was that it never was until the summary card.
        assert "already passed" in message.lower()
        assert "15 Sep 2026" in message
        saved = fake_slots.get_slots(1, "conv-1")
        # Offered, not taken: the slot stays empty until the user accepts,
        # and the suggestion is parked separately so a bare "yes" can.
        assert saved["from_date"] is None
        assert saved["to_date"] is None
        assert saved["suggested_from_date"] == next_month_15th
        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_applied_leaves", _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_applied_leaves", _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,
        )
        result = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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()
        result = await hr_graph.leave_action_node(
            base_state("please apply sick for last monday this month full day reason is fever"), writer,
        )
        result = await approve_reason_readback(monkeypatch, writer, result)

        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_applied_leaves", _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()
        result = await hr_graph.leave_action_node(
            base_state("apply sick leave for friday of current week full day reason is fever"), writer,
        )
        result = await approve_reason_readback(monkeypatch, writer, result)

        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, **kwargs):
            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, **kwargs):
            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 pending-only one (get_pending_leaves) —
        # 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()
        # The candidates go out as a STRUCTURED card now, not flattened into
        # one sentence ("Casual Leave (...) or Sick Leave (...) or ..."); see the
        # leave_cancellation_selection emission in the status-question branch.
        _cards = writer.of_type("leave_cancellation_selection")[0]["data"]["requests"]
        _names = [c["leave_type"] for c in _cards]
        assert "Casual Leave" in _names
        assert "Sick Leave" in _names
        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()
        # The candidates go out as a STRUCTURED card now, not flattened into
        # one sentence ("Casual Leave (...) or Sick Leave (...) or ..."); see the
        # leave_cancellation_selection emission in the status-question branch.
        _cards = writer.of_type("leave_cancellation_selection")[0]["data"]["requests"]
        _names = [c["leave_type"] for c in _cards]
        assert "Casual Leave" in _names
        assert "Sick Leave" in _names
        assert "Earned Leave" not in _names
        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.

        Mocks get_applied_leaves, not get_pending_leaves: the pending-requests
        branch fetches through get_applied_leaves. The other side of this
        merge conflict stubbed get_pending_leaves, which this path no longer
        calls — it serves only the apply flow's duplicate-date check now."""
        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("leave status", "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 TestDecisionReasonIsAlwaysUnderRejectionReason:
    """The frontend's Reason tab reads exactly one key for the decision-side
    note on a leave record — rejection_reason — no matter which decision it
    was. erp-api files a cancellation's note under cancel_reason instead, so
    a cancelled leave used to reach the tab with rejection_reason: null and
    the note the employee typed nowhere to be seen (live report, 2026-09-08).
    Pure card-level tests: no node, no LLM — the mapping is the whole
    behaviour under test."""

    def test_cancelled_leave_exposes_its_cancel_reason_as_rejection_reason(self):
        card = leave_action_service._build_applied_leave_card({
            **_pending_leave(254, "Casual Leave", "2026-09-25", "2026-09-26"),
            "status_name": "cancelled", "reason": "family function",
            "rejection_reason": None, "cancel_reason": "plans changed",
        })

        assert card["rejection_reason"] == "plans changed"
        # The un-merged field stays available, and the employee's ORIGINAL
        # reason for requesting the leave is untouched by any of this.
        assert card["cancel_reason"] == "plans changed"
        assert card["reason"] == "family function"

    def test_rejected_leave_still_uses_its_own_rejection_reason(self):
        card = leave_action_service._build_applied_leave_card({
            **_pending_leave(255, "Sick Leave", "2026-09-25", "2026-09-26"),
            "status_name": "rejected", "rejection_reason": "Team short-staffed",
        })

        assert card["rejection_reason"] == "Team short-staffed"

    def test_pending_leave_has_no_decision_reason(self):
        card = leave_action_service._build_applied_leave_card({
            **_pending_leave(256, "Casual Leave", "2026-09-25", "2026-09-26"),
            "reason": "afhkjasd", "rejection_reason": None,
        })

        assert card["rejection_reason"] is None
        assert card["reason"] == "afhkjasd"

    @pytest.mark.parametrize("key", [
        "cancel_reason", "cancellation_reason", "cancelled_reason",
    ])
    def test_every_erp_spelling_of_a_cancellation_note_is_accepted(self, key):
        card = leave_action_service._build_applied_leave_card({
            **_pending_leave(257, "Casual Leave", "2026-09-25", "2026-09-26"),
            "status_name": "cancelled", key: "emergency at home",
        })

        assert card["rejection_reason"] == "emergency at home"

    def test_blank_note_is_treated_as_no_note_not_an_empty_string(self):
        # erp-api sends "" as readily as null for "no note" — the frontend
        # would render an empty Reason row for one and nothing for the other.
        card = leave_action_service._build_applied_leave_card({
            **_pending_leave(258, "Casual Leave", "2026-09-25", "2026-09-26"),
            "status_name": "cancelled", "rejection_reason": "", "cancel_reason": "   ",
        })

        assert card["rejection_reason"] is None

    def test_cancelled_leave_message_names_the_reason_like_a_rejected_one_does(self):
        card = leave_action_service._build_applied_leave_card({
            **_pending_leave(259, "Casual Leave", "2026-09-25", "2026-09-26"),
            "status_name": "cancelled", "cancel_reason": "plans changed",
        })

        message = leave_action_service._single_applied_leave_message(card)

        assert "cancelled" in message
        assert "plans changed" in message


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, **kwargs):
            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, **kwargs):
            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, **kwargs):
            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, **kwargs):
            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_reference_match_against_a_cancelled_record_says_so_instead_of_previewing(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """The 2026-08-20 "simplified design" sent this to preview and let
        erp-api's own /leave/cancel be the sole authority on cancellability.
        A live bug report reversed that: confirming a request that was
        already cancelled looked like it had "worked" every time, because
        the preview simply reappeared.

        The record's status comes from the very /leave/applied fetch that
        built this candidate on this turn — it is known, not guessed — so
        this now short-circuits to the ALREADY_CANCELLED failure card with
        no preview and nothing to confirm. See _already_decided_cancel_card.

        Still narrow: it applies only to a SPECIFIC match (by reference,
        date or type). Ambiguous wording continues to go through the
        selection list, which excludes terminal records anyway."""
        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") == []
        assert writer.of_type("leave_cancellation_preview") == []
        card = writer.of_type("leave_failure")[0]["data"]
        assert card["failure"]["reason_code"] == ["ALREADY_CANCELLED"]
        assert "already been cancelled" in result["response_text"]
        # LR-52 is a still-pending request on the same date. The reference
        # picked the cancelled one out specifically, so the answer must be
        # about that one and must not quietly retarget the live request.
        assert "LR-52" not in result["response_text"]

    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, **kwargs):
            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.

        The query here is deliberately bare. "cancel my PENDING leave"
        would not do: a draft has never been pending, so
        _SUBMITTED_LEAVE_TARGET_PATTERNS reads that as naming an
        already-submitted request and interrupts on purpose — see
        TestClassifyNodeMidFlowInterruption's submitted-request test."""
        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 leave request"), 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_applied_leaves", _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_applied_leaves", _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_bare_number_matches_a_candidates_reference_without_the_lr_prefix(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Live bug report: the selection card prominently shows "Ref
        #LR-159", and typing just "159" (no "LR-"/"#"/"leave"/"request"
        prefix at all) is the single most natural reply to it — but it
        matched nothing: _extract_request_id needs one of those prefixes,
        and the ordinal-position regex only ever looks at 1-2 digit
        numbers, so a 3-digit reference like 159 fell through both and got
        a generic "couldn't quite tell" instead of the obvious match."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        candidates = [
            leave_action_service._build_applied_leave_card(_pending_leave(159, "Casual Leave", "2027-02-26", "2027-02-26")),
            leave_action_service._build_applied_leave_card(_pending_leave(158, "Sick Leave", "2026-09-03", "2026-09-03")),
        ]
        fake_cancel_state.set_state(1, "conv-1", {"step": "awaiting_selection", "candidates": candidates, "reason": None})

        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("159", "cancel_leave"), writer)

        preview = writer.of_type("leave_cancellation_preview")[0]["data"]
        assert preview["reference"] == "LR-159"

    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"]


# ═════════════════════════════════════════════════════════════════════════════
# classify_node — deterministic bare-leave-type-mention fast-path
# (turn-1-vs-turn-2 consistency fix)
# ═════════════════════════════════════════════════════════════════════════════

class TestBareLeaveTypeMentionConsistency:
    """Live bug report: 'sick leave' with no other wording gave a generic
    policy essay the first time in a conversation, but 'What type of leave
    would you like to apply for?' when the exact same message was repeated.
    Root cause: the clarifying-question feature (leave_type_clarify) used to
    be gated entirely on the REAL LLM classifier returning "leave_policy",
    and that classifier's own prompt changes shape once there's conversation
    history (a context_block + follow-up directive get added), so it could
    legitimately flip its answer turn-to-turn for identical text. The fix
    decides this from fast_classify alone — deterministic, never
    context-dependent — so the outcome must now be identical regardless of
    which turn asked."""

    async def test_bare_mention_on_a_fresh_conversation_asks_the_scoped_menu(self, fake_slots):
        writer = FakeWriter()
        result = await hr_graph.classify_node(base_state("sick leave", "general"), writer)

        assert result["intent"] == "leave_type_clarify"
        message = result["response_text"].lower()
        assert "balance" in message
        assert "applied" in message
        assert "eligibility" in message
        assert "apply" in message

    async def test_bare_mention_is_identical_when_repeated_with_conversation_history(self, fake_slots):
        """Same raw text, but simulating turn 2+ by asking again — must NOT
        depend on conversation context the way the old LLM-classifier-gated
        path did."""
        writer = FakeWriter()
        state = base_state("sick leave", "general")
        state["context"] = [
            {"role": "user", "content": "sick leave"},
            {"role": "assistant", "content": "Would you like to know your sick leave balance, "
                                              "view your applied sick leaves, check your sick leave "
                                              "eligibility, or apply for sick leave?"},
        ]

        result = await hr_graph.classify_node(state, writer)

        assert result["intent"] == "leave_type_clarify"
        assert "what type of leave would you like to apply for" not in result["response_text"].lower()

    async def test_genuine_policy_question_is_not_treated_as_a_bare_mention(self, fake_slots):
        """'what is the sick leave policy' carries a question marker
        (_looks_like_leave_policy_question) and must fall through to normal
        classification instead of the scoped menu."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "leave_policy", None, False
        import services.classify_node as classify_node_mod
        import unittest.mock
        with unittest.mock.patch.object(classify_node_mod, "classify_intent_structured", _fake_classify):
            writer = FakeWriter()
            result = await hr_graph.classify_node(base_state("what is the sick leave policy", "general"), writer)

        assert result["intent"] != "leave_type_clarify"

    async def test_explicit_leave_balance_query_is_not_treated_as_a_bare_mention(self, fake_slots):
        """'sick leave balance' names both the type AND the action — must
        NOT be caught by the new bare-mention fast-path (fast_classify
        recognizes 'balance' via its own leave_balance keyword list, not
        leave_policy), so it falls through to real classification as
        before."""
        async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
            return "leave_balance", None, False
        import unittest.mock
        with unittest.mock.patch.object(classify_node_mod, "classify_intent_structured", _fake_classify):
            writer = FakeWriter()
            result = await hr_graph.classify_node(base_state("sick leave balance", "general"), writer)

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


# ═════════════════════════════════════════════════════════════════════════════
# classify_node — interruption detection for the lighter pending-state
# fast-paths (disambiguation / history-clarify / leave-type-clarify)
# ═════════════════════════════════════════════════════════════════════════════

class FakeLeaveTypeClarifyStateStore:
    """In-memory stand-in for leave_type_clarify_state, same shape as
    FakeHistoryClarifyStateStore/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_leave_type_clarify_state(monkeypatch):
    store = FakeLeaveTypeClarifyStateStore()
    monkeypatch.setattr(classify_node_mod, "leave_type_clarify_state", store)
    monkeypatch.setattr(leave_action_service, "leave_type_clarify_state", store, raising=False)
    return store


class TestLighterFastPathsInterruptionDetection:
    """Fast-paths 0.2 (disambiguation), 0.3 (history-clarify) and 0.4
    (leave-type-clarify) used to have NO interruption detection at all —
    just a keyword match against the raw reply. An unrelated message that
    happened to contain one of those keywords while the state was still
    pending got silently misread as resolving the question instead of being
    answered on its own merits."""

    async def test_disambiguation_pending_but_message_is_a_confident_unrelated_query(
        self, fake_disambiguation_state,
    ):
        fake_disambiguation_state.set_candidates(1, "conv-1", [{"reference": "LR-1"}, {"reference": "LR-2"}])
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("what time do I punch in", "general"), writer)

        assert result["intent"] == "punch_details"
        # State is left untouched so the disambiguation can still resolve later.
        assert fake_disambiguation_state.get_candidates(1, "conv-1") is not None

    async def test_disambiguation_pending_and_a_genuine_reply_still_resolves_normally(
        self, fake_disambiguation_state,
    ):
        fake_disambiguation_state.set_candidates(1, "conv-1", [{"reference": "LR-1"}, {"reference": "LR-2"}])
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("the casual leave one", "general"), writer)

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

    async def test_history_clarify_pending_but_message_is_a_confident_unrelated_query(
        self, fake_history_clarify_state,
    ):
        fake_history_clarify_state.set_state(1, "conv-1", {"leave_type_slug": None, "from_date": None, "to_date": None})
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("regularize my attendance for yesterday", "general"), writer)

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

    async def test_history_clarify_pending_and_a_genuine_balance_reply_still_resolves(
        self, fake_history_clarify_state,
    ):
        fake_history_clarify_state.set_state(1, "conv-1", {"leave_type_slug": None, "from_date": None, "to_date": None})
        writer = FakeWriter()

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

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

    async def test_leave_type_clarify_pending_but_message_is_a_confident_unrelated_query(
        self, fake_leave_type_clarify_state,
    ):
        """Live bug scenario: the pending clarify state's own STATUS_WORDS
        list includes 'applied'/'pending' — a totally unrelated message that
        happens to contain one of those words (e.g. about a regularisation
        request) must not be misread as resolving the leave-type question."""
        fake_leave_type_clarify_state.set_state(1, "conv-1", {"leave_type_slug": "sick_leave"})
        writer = FakeWriter()

        result = await hr_graph.classify_node(
            base_state("what's the status of my applied regularisation request", "general"), writer
        )

        assert result["intent"] != "leave_status"
        assert fake_leave_type_clarify_state.get_state(1, "conv-1") is not None

    async def test_leave_type_clarify_pending_and_a_genuine_apply_reply_still_resolves(
        self, fake_leave_type_clarify_state,
    ):
        fake_leave_type_clarify_state.set_state(1, "conv-1", {"leave_type_slug": "sick_leave"})
        writer = FakeWriter()

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

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


# ═════════════════════════════════════════════════════════════════════════════
# leave_action_node — probation-eligibility pre-check (fail fast, before
# the rest of the apply-leave slot-filling flow)
# ═════════════════════════════════════════════════════════════════════════════

def probation_context(probation_end_date="2026-12-31"):
    async def _f(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {
            "is_manager": False, "is_confirmed": False, "probation_end_date": probation_end_date,
        }}}
    return _f


class TestApplyLeaveProbationPreCheck:

    async def test_probation_blocked_type_fails_immediately_after_leave_type_before_any_date_question(
        self, monkeypatch, fake_slots,
    ):
        """The whole point of this check: a probation-ineligible employee
        must find out the moment leave_type is known, not after answering
        dates/half-day/reason and finally hitting 'shall I submit?'."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", probation_context())

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

        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, {})

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("sick leave"), writer)

        assert "probation" in result["response_text"].lower()
        assert "what date" not in result["response_text"].lower()
        failures = writer.of_type("leave_failure")
        assert len(failures) == 1
        assert failures[0]["data"]["reason_code"] == "REQUIRES_CONFIRMATION"
        # Slots cleared entirely — no date could ever fix a probation block.
        assert fake_slots.get_slots(1, "conv-1") is None

    async def test_confirmed_employee_is_not_blocked_and_proceeds_to_the_date_question(
        self, monkeypatch, fake_slots,
    ):
        async def _confirmed_context(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "is_manager": False, "is_confirmed": True, "probation_end_date": None,
            }}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _confirmed_context)

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

        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, {})

        writer = FakeWriter()
        result = await hr_graph.leave_action_node(base_state("sick leave"), writer)

        assert writer.of_type("leave_failure") == []
        assert "what date" in result["response_text"].lower()

    async def test_leave_type_with_no_probation_gate_is_not_blocked(self, monkeypatch, fake_slots):
        """benefit_start == 'joining' — available from date of joining,
        never gated by probation — must sail straight through to the date
        question regardless of is_confirmed."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", probation_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", "benefit_start": "joining"},
                ]},
            }}}
        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("casual leave"), writer)

        assert writer.of_type("leave_failure") == []
        assert "what date" in result["response_text"].lower()
        assert "LR-2041" not in result["response_text"]


class TestCancelIntentIsSeparateFromApplyIntent:
    """Sprint-2 QA, 2026-09-08 — the word "cancel" was being routed by keyword
    alone, so the apply and cancel flows kept stealing each other's turns.

    Reported symptoms, all covered here:
      1. Typing (or pressing) "cancel" while APPLYING a leave started a
         cancel-leave SEARCH ("which submitted request do you want to
         cancel?") instead of discarding the draft on screen.
      2. Answering the cancel confirmation card with "cancel my all leaves"
         was read as a decline ("Leave Request Kept") — a request to cancel
         MORE leaves treated as a decision to cancel none.

    These drive hr_graph.classify_node — the classifier ACTUALLY wired into
    the graph (hr_graph.build_graph registers the module-local definition,
    which shadows the classify_node imported from services.classify_node).
    """

    APPLY_DRAFT = {"step": "collecting", "leave_type": "casual_leave",
                   "from_date": None, "to_date": None, "reason": None}
    APPLY_CONFIRM = {"step": "awaiting_confirmation", "leave_type": "casual_leave",
                     "from_date": "2027-09-10", "to_date": "2027-09-10", "reason": "personal"}
    CANCEL_PENDING = {"step": "awaiting_confirmation",
                      "selected": {"reference": "LR-69", "leave_type": "Casual Leave",
                                   "from_date": "2027-09-18", "to_date": "2027-09-18"}}

    @staticmethod
    async def _route(query, slots, cancel_state=None, llm_says="cancel_leave"):
        """`llm_says` defaults to the WORST case — the LLM fallback insisting
        on cancel_leave. Anything that must stay in the apply flow therefore
        has to be decided by the deterministic guards before the classifier is
        ever consulted, which is exactly the property under test: a bare
        "cancel" carries no keyword fast_classify recognises, so before the fix
        it reached the LLM and was guessed into the cancel flow."""
        state = {"query": query, "context": [], "company_id": 1,
                 "conversation_id": "conv-1", "bearer_token": "t",
                 "intent": "general", "usage_events": []}
        # Patched on classify_node, NOT hr_graph. hr_graph.classify_node IS
        # classify_node.classify_node (`hr_graph.classify_node is
        # classify_node_mod.classify_node` -> True), so it reads THAT
        # module's globals. Patching hr_graph's copies changed nothing the
        # function under test could see - and bare_verb_clarify_state is not
        # even an attribute of hr_graph any more, which is what turned a
        # silent no-op into an AttributeError.
        with patch.object(classify_node_mod.leave_slot_service, "get_slots", return_value=slots), \
             patch.object(classify_node_mod.leave_cancel_state, "get_state", return_value=cancel_state), \
             patch.object(classify_node_mod.leave_cancel_state, "clear_state", return_value=True), \
             patch.object(classify_node_mod.leave_history_clarify_state, "get_state", return_value=None), \
             patch.object(classify_node_mod.leave_disambiguation_state, "get_candidates", return_value=None), \
             patch.object(classify_node_mod.bare_verb_clarify_state, "get_state", return_value=None), \
             patch.object(classify_node_mod.bare_verb_clarify_state, "set_state", return_value=True), \
             patch.object(classify_node_mod.slot_store, "get_slots", return_value=None), \
             patch.object(classify_node_mod, "classify_intent_structured",
                          AsyncMock(return_value=(llm_says, None, False))), \
             patch.object(classify_node_mod, "_check_moderation", AsyncMock(return_value={})):
            return await hr_graph.classify_node(state, lambda e: None)

    # -- 1. "cancel" while an application is open means the DRAFT ------------
    @pytest.mark.parametrize("reply", [
        "cancel", "Cancel", "CANCEL", "cancel.", "cancel it", "cancel this",
        "cancel this leave", "cancel the request", "never mind", "forget it",
    ])
    async def test_ambiguous_cancel_mid_application_stays_in_the_apply_flow(self, reply):
        """None of these can name an already-submitted request, so they mean
        the draft — leave_action_service's discard check (which runs before
        slot extraction) then handles them deterministically."""
        result = await self._route(reply, self.APPLY_DRAFT)
        assert result["intent"] == "apply_leave"

    @pytest.mark.parametrize("reply", ["cancel", "Cancel", "never mind"])
    async def test_ambiguous_cancel_at_the_apply_confirmation_step_too(self, reply):
        """The guard applies at EVERY step of the apply flow, not only at the
        final confirmation — a "cancel" typed while still collecting dates used
        to fall through to the LLM and be guessed into the cancel flow."""
        result = await self._route(reply, self.APPLY_CONFIRM)
        assert result["intent"] == "apply_leave"

    # -- 2. ...unless it names something that CANNOT be the draft ------------
    @pytest.mark.parametrize("reply", [
        "cancel my leaves",          # plural — a draft is exactly one request
        "cancel my all leaves",      # the phrasing from the QA report
        "cancel all my leave",
        "cancel LR-2041",            # explicit reference
        "cancel leave 78",
        "cancel my pending leave",   # a status a draft has never had
        "withdraw my leave requests",
    ])
    async def test_an_explicit_submitted_request_still_starts_the_cancel_flow(self, reply):
        """A reply naming something the draft cannot be is read as a cancel of
        a SUBMITTED request - never as a discard of the draft on screen.

        Updated for 6cd64a4 (application flow fixes): with a half-filled draft
        open, every interruption is first asked about ("carry on with it, or
        discard it?") instead of leaving the draft silently orphaned - no
        exceptions, cancel included. What must still hold is the split this
        class is about: the draft is not thrown away by this reply."""
        assert leave_action_service.cancel_phrase_targets_submitted_request(reply)
        result = await self._route(reply, self.APPLY_DRAFT)
        assert result["intent"] == "clarify_needed"
        assert result["clarify_options"] == ["Carry on with it", "Discard it"]

    # -- 3. An open cancel card outranks a lingering apply draft -------------
    @pytest.mark.parametrize("button", ["Keep Request", "Confirm Cancellation"])
    async def test_cancel_card_buttons_reach_the_cancel_flow(self, button):
        result = await self._route(button, self.APPLY_DRAFT, self.CANCEL_PENDING)
        assert result["intent"] == "cancel_leave"

    async def test_plural_cancel_at_the_confirmation_card_reaches_the_cancel_flow(self):
        result = await self._route("cancel my all leaves", None, self.CANCEL_PENDING)
        assert result["intent"] == "cancel_leave"

    async def test_a_declined_cancel_state_does_not_stand_the_apply_flow_down(self):
        """A "declined" state is a passive short-lived memory (so a vague
        "cancel again" can resume), not a question awaiting an answer."""
        declined = {"step": "declined", "selected": self.CANCEL_PENDING["selected"]}
        result = await self._route("cancel", self.APPLY_DRAFT, declined)
        assert result["intent"] == "apply_leave"

    # -- The shared predicate itself -----------------------------------------
    @pytest.mark.parametrize("text,expected", [
        ("cancel", False), ("cancel it", False), ("cancel this leave", False),
        ("never mind", False), ("Keep Request", False), ("Confirm Cancellation", False),
        ("cancel my leave", False), ("cancel my sick leave", False),
        ("cancel my leaves", True), ("cancel my all leaves", True),
        ("cancel all my leave", True), ("cancel LR-2041", True),
        ("cancel leave 78", True), ("cancel my pending leave", True),
        ("cancel my approved leave", True), ("withdraw my leave requests", True),
    ])
    def test_cancel_phrase_targets_submitted_request(self, text, expected):
        assert leave_action_service.cancel_phrase_targets_submitted_request(text) is expected


class TestCancelSelectionCardIsNeverEmpty:
    """QA: "The AI displays a 'Cancel Leave Request' confirmation card when the
    user has no leave requests available to cancel."

    The no-match and already-decided paths both fall back to
    `matches = cancellable_cards` and set a lead_msg. The empty-result guard
    was `not matches AND not lead_msg`, so whenever that fallback list was
    ITSELF empty the turn fell through to the selection card with zero
    candidates — and parked an awaiting_selection state no reply could
    resolve."""

    @staticmethod
    def _decided(id_, leave_type, from_date, to_date, status_name="cancelled"):
        return {"id": id_, "leave_type": leave_type, "from_date": from_date,
                "to_date": to_date, "status_name": status_name}

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

        async def _applied(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                self._decided(1, "Casual Leave", "2026-08-01", "2026-08-01", "cancelled"),
                self._decided(2, "Sick Leave", "2026-08-05", "2026-08-05", "rejected"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)
        # A criterion that matches NOTHING on record, so the branch falls back
        # to `matches = cancellable_cards` — which is itself empty here, since
        # every request on file is already cancelled or rejected. That is the
        # exact combination that used to render an empty picker.
        mock_extraction(monkeypatch, _cancel_extraction(leave_type="earned_leave"))

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("cancel my earned leave", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection") == []
        assert "pending or approved leave requests to cancel" in result["response_text"].lower()
        assert fake_cancel_state.get_state(1, "conv-1") is None

    async def test_a_real_candidate_still_gets_the_picker(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Negative control — the guard must only fire on a genuinely empty
        list, never suppress a picker that has something to offer."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        async def _applied(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(11, "Casual Leave", "2027-08-01", "2027-08-01"),
                _pending_leave(12, "Casual Leave", "2027-08-09", "2027-08-09"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        await leave_action_service.leave_action_node(base_state("cancel my leave", "cancel_leave"), writer)

        selection = writer.of_type("leave_cancellation_selection")
        assert selection and len(selection[0]["data"]["requests"]) == 2


class TestPluralCancelAtTheConfirmationPromptReopensThePicker:
    """QA: with the confirm/keep card on screen, "cancel my all leaves" was
    answered "Leave Request Kept". Its bare "cancel" fell into
    _decide_cancel_confirmation's weak-decline fallback, because the
    new-request check only looked for a leave type / date / reference — none of
    which a plural ask carries. A plural object cannot be an answer to "would
    you like to cancel THIS one?", so it means "show me the others"."""

    async def test_cancel_all_my_leaves_shows_the_picker_instead_of_keeping(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        selected = 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": selected, "reason": None})

        async def _applied(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": [
                _pending_leave(2041, "Casual Leave", "2027-06-14", "2027-06-14"),
                _pending_leave(2042, "Sick Leave", "2027-06-20", "2027-06-20"),
            ]}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _applied)
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("cancel my all leaves", "cancel_leave"), writer)

        assert writer.of_type("leave_cancellation_selection")
        assert "kept" not in result["response_text"].lower()

    async def test_a_plain_decline_at_the_same_prompt_still_keeps_the_request(
        self, monkeypatch, fake_slots, fake_cancel_state,
    ):
        """Negative control — the plural allowance must not weaken an ordinary
        decline."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        selected = 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": selected, "reason": None})
        mock_extraction(monkeypatch, _cancel_extraction())

        writer = FakeWriter()
        result = await leave_action_service.leave_action_node(
            base_state("Keep Request", "cancel_leave"), writer)

        assert "kept" in result["response_text"].lower()
        assert fake_cancel_state.get_state(1, "conv-1")["step"] == "declined"


class TestMisspeltStatusWordIsNotALeaveType:
    """QA, 2026-09-08 — "cancel my peding leaves" answered:

        "Helix AI currently supports Casual Leave, Sick Leave, Earned Leave,
         and Short Leave. 'Peding Leave' is not supported in this portal."

    Two independent faults, both fixed:
      1. _STATUS_WORD_CANDIDATES matched exactly, so the misspelt "peding"
         slipped past it and the generic "<word> leaves" extractor handed the
         typo over as the NAME of an unconfigured leave type. "pending" is a
         STATUS; misspelling it must not turn it into a type.
      2. The intent came back leave_status, so even a correctly-spelt
         "cancel my pending leaves" would have LISTED leaves rather than
         offering to cancel them.
    """

    # -- 1. the status-word guard, now typo-tolerant -------------------------
    @pytest.mark.parametrize("word", [
        "pending", "peding", "pendig", "pendign", "penidng",
        "approved", "aproved", "approced", "rejected", "rejcted",
        "cancelled", "canceld", "applied", "aplied", "appled",
        "declined", "declind", "accepted", "acepted",
        "outstanding", "outstading", "upcoming", "upcomming",
        # short entries still match exactly; fuzzy matching is gated at 5
        # chars, where difflib scores stop separating a typo from an
        # unrelated word.
        "all", "new", "old", "past",
    ])
    def test_status_words_and_their_typos_are_recognised(self, word):
        assert leave_action_service._is_status_word(word) is True

    @pytest.mark.parametrize("word", [
        # Real leave-type names — including a misspelt one — must stay
        # types, so a genuinely unsupported type is still reported as
        # unsupported rather than silently swallowed as a "status".
        "medical", "maternity", "meternity", "paternity", "religious",
        "bereavement", "study", "sabbatical", "compensatory", "marriage",
        "casual", "sick", "earned", "short",
    ])
    def test_leave_type_names_are_not_mistaken_for_status_words(self, word):
        assert leave_action_service._is_status_word(word) is False

    def test_empty_input_is_not_a_status_word(self):
        assert leave_action_service._is_status_word(None) is False
        assert leave_action_service._is_status_word("") is False

    async def test_misspelt_status_query_does_not_claim_the_type_is_unsupported(
        self, monkeypatch, fake_slots,
    ):
        """End to end through the status branch: "show my peding leaves" must
        answer about leaves, never "'Peding Leave' is not supported"."""
        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": "5"}},
                "leave_settings": {"leave_type": [
                    {"name": "Casual Leave", "slug": "casual_leave", "benefit_start": "joining"},
                    {"name": "Sick Leave", "slug": "sick_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 leave_action_service.leave_action_node(
            base_state("show my peding leaves", "leave_status"), writer)

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

    async def test_a_genuinely_unsupported_type_is_still_reported(
        self, monkeypatch, fake_slots,
    ):
        """Negative control — widening the status-word guard must not stop a
        real unconfigured type from being named as unsupported."""
        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": "5"}},
                "leave_settings": {"leave_type": [
                    {"name": "Casual Leave", "slug": "casual_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 leave_action_service.leave_action_node(
            base_state("show my maternity leaves", "leave_status"), writer)

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


class TestCancelBeatsLeaveStatusOnDisagreement:
    """Second half of the same QA report: "cancel my peding leaves" came back
    from the LLM classifier as leave_status, so an explicit instruction to
    cancel was answered by listing leaves.

    cancel_leave and leave_status are the two intents that argue over the same
    words, and the boundary is an ACTION/VIEWING one fast_classify already
    decides deterministically — its cancel branch needs a cancel/withdraw/
    revoke verb next to a leave object AND no viewing verb anywhere. So that
    reading now wins over an LLM that says leave_status."""

    @staticmethod
    async def _route(query, llm_says):
        class _Empty:
            def get_slots(self, *a, **k): return None
            def get_state(self, *a, **k): return None
            def get_candidates(self, *a, **k): return None
            def set_state(self, *a, **k): return True
            def clear_state(self, *a, **k): return True

        state = {"query": query, "context": [], "company_id": 1,
                 "conversation_id": "conv-1", "bearer_token": "t",
                 "intent": "general", "usage_events": []}
        # classify_node, not hr_graph - see the note on the sibling helper
        # above: hr_graph.classify_node is classify_node's own function and
        # reads its globals, so patches on hr_graph never reached it.
        with patch.object(classify_node_mod, "leave_slot_service", _Empty()), \
             patch.object(classify_node_mod, "leave_cancel_state", _Empty()), \
             patch.object(classify_node_mod, "leave_history_clarify_state", _Empty()), \
             patch.object(classify_node_mod, "leave_disambiguation_state", _Empty()), \
             patch.object(classify_node_mod, "bare_verb_clarify_state", _Empty()), \
             patch.object(classify_node_mod, "slot_store", _Empty()), \
             patch.object(classify_node_mod, "classify_intent_structured",
                          AsyncMock(return_value=(llm_says, None, False))), \
             patch.object(classify_node_mod, "_check_moderation", AsyncMock(return_value={})):
            return (await hr_graph.classify_node(state, lambda e: None))["intent"]

    @pytest.mark.parametrize("query", [
        "cancel my peding leaves",   # the reported query, typo and all
        "cancel my pending leaves",
        "cancel my leave",
        "withdraw my leave request",
    ])
    async def test_an_explicit_cancel_instruction_beats_an_llm_leave_status(self, query):
        assert await self._route(query, "leave_status") == "cancel_leave"

    @pytest.mark.parametrize("query", [
        # A VIEWING verb is present, so fast_classify never says cancel_leave
        # and the override cannot fire — these stay status queries.
        "show my cancelled leaves",
        "show my peding leaves",
        "what leaves have I cancelled",
        "give me my cancelled leave requests",
        "is my leave approved",
    ])
    async def test_viewing_queries_are_left_alone(self, query):
        assert await self._route(query, "leave_status") == "leave_status"

    async def test_the_override_is_one_directional(self):
        """An LLM answer of cancel_leave is never rewritten to leave_status —
        only the leave_status -> cancel_leave direction is decided here."""
        assert await self._route("show my cancelled leaves", "cancel_leave") == "cancel_leave"

    @pytest.mark.parametrize("query,llm_says", [
        ("what is my leave balance", "leave_balance"),
        ("apply for casual leave tomorrow", "apply_leave"),
        ("am I eligible for sick leave", "leave_eligibility"),
    ])
    async def test_other_intents_are_untouched(self, query, llm_says):
        """The override is scoped to one ordered pair; every other
        disagreement still lets the LLM's answer stand."""
        assert await self._route(query, llm_says) == llm_says


# ═════════════════════════════════════════════════════════════════════════════
# requires_date_input on failure cards — the frontend's calendar-picker signal
# ═════════════════════════════════════════════════════════════════════════════

class TestFailureCardsSignalRequiresDateInput:
    """Live bug: the calendar picker never appeared on the "already applied
    for this date" / blocked-holiday / not-enough-balance rejections, so the
    card said "What dates would you like to try instead?" with no way to pick
    one. The frontend renders that picker off `requires_date_input`, which was
    only being set on a handful of the plain re-ask responses.

    Every failure whose stated next action is "give me different dates" must
    carry it — on the card itself, so it reaches both the streamed
    `leave_failure` event and the `done` payload — and every failure that is
    NOT about the dates must still leave it off.

    Calls leave_action_service.leave_action_node directly rather than
    hr_graph.leave_action_node: hr_graph carries a stale shadow copy of this
    node (its own `async def leave_action_node`, unrelated to the
    `leave_action_node_impl` that build_hr_graph actually registers), so
    going through hr_graph here would test dead code.
    """

    @staticmethod
    def _flags(writer):
        """(leave_failure event data, done data) for the turn."""
        events = writer.of_type("leave_failure")
        return (events[0]["data"] if events else None), writer.of_type("done")[0]["data"]

    async def test_duplicate_application_card_asks_for_a_date(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": [
                {"id": 52, "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_applied_leaves", _status)

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

        card, done = self._flags(writer)
        assert card["failure"]["reason_code"] == ["DUPLICATE_APPLICATION"]
        assert card["requires_date_input"] is True
        assert done["requires_date_input"] is True

    async def test_blocked_holiday_card_asks_for_a_date(self, monkeypatch, fake_slots):
        """The regression that started this: BLOCKED_DATE was the one
        date-fixable pre-check that never set the flag."""
        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)
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _no_conflicting_leaves)

        mock_extraction(monkeypatch, {"from_date": "2026-12-20", "to_date": "2026-12-20"})
        writer = FakeWriter()
        await leave_action_service.leave_action_node(
            base_state("apply leave for 20 dec", "apply_leave"), writer)

        card, done = self._flags(writer)
        assert card["failure"]["reason_code"] == ["BLOCKED_DATE"]
        assert card["requires_date_input"] is True
        assert done["requires_date_input"] is True

    async def test_insufficient_balance_card_asks_for_a_date(self, monkeypatch, fake_slots):
        """A shorter range genuinely could fix this one, so the picker
        belongs here — unlike the zero-balance case below."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _no_conflicting_leaves)

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

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2030-06-04", "to_date": "2030-06-06",
            "session_type_slug": "full_day", "reason": "surgery recovery",
        })
        writer = FakeWriter()
        await leave_action_service.leave_action_node(
            base_state("apply sick leave 2030-06-04 to 2030-06-06"), writer)

        card, done = self._flags(writer)
        assert card["failure"]["reason_code"] == ["INSUFFICIENT_BALANCE"]
        assert card["requires_date_input"] is True
        assert done["requires_date_input"] is True

    async def test_zero_balance_card_does_not_ask_for_a_date(self, monkeypatch, fake_slots):
        """Negative control: a zero-total type is a wrong-TYPE problem. No
        date could fix it, so no calendar — on either payload."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_applied_leaves", _no_conflicting_leaves)

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

        mock_extraction(monkeypatch, {
            "leave_type": "sick_leave", "from_date": "2030-06-04", "to_date": "2030-06-04",
            "session_type_slug": "full_day", "reason": "fever",
        })
        writer = FakeWriter()
        await leave_action_service.leave_action_node(
            base_state("apply sick leave on 2030-06-04"), writer)

        card, done = self._flags(writer)
        assert "requires_date_input" not in card
        assert "requires_date_input" not in done

    async def test_date_related_erp_api_rejection_card_asks_for_a_date(self, monkeypatch, fake_slots):
        """The same signal has to survive the OTHER failure path — a card
        built from erp-api's own rejection, not from a local pre-check."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "_pending_submit": True, "leave_type": "casual_leave",
            "from_date": "2026-09-01", "to_date": "2026-09-01",
            "session_type_slug": "full_day", "reason": "personal work",
        })

        async def _apply_fails(token, *a, **kw):
            return {"http_status": 400, "body": {
                "success": False, "message": "You have already applied leave for this date."}}
        monkeypatch.setattr(hr_graph.erp_client, "apply_leave", _apply_fails)

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

        card, done = self._flags(writer)
        assert card["requires_date_input"] is True
        assert done["requires_date_input"] is True
        assert fake_slots.get_slots(1, "conv-1")["from_date"] is None

    async def test_reason_related_erp_api_rejection_card_does_not_ask_for_a_date(
        self, monkeypatch, fake_slots,
    ):
        """Negative control on the erp-api path: this branch re-collects the
        reason and deliberately leaves the dates alone, so a calendar would
        be the wrong input to offer."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        fake_slots.set_slots(1, "conv-1", {
            "step": "awaiting_confirmation", "_pending_submit": True, "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()
        await leave_action_service.leave_action_node(base_state("yes"), writer)

        card, done = self._flags(writer)
        assert "requires_date_input" not in card
        assert "requires_date_input" not in done
        assert fake_slots.get_slots(1, "conv-1")["from_date"] == "2026-09-01"
