"""
Tests for Conversational Leave Approval (FR-07.4 / FR-08.3, Sprint 4):
  - services/erp_client.py::approve_leave_request (POST
    /api/v1/ai/leave/requests/{id}/approve — the confirmed-live contract,
    including its team-scope refusal body)
  - services/leave_approval.py::leave_approval_node (manager gate, target
    resolution, the confirmation step, execution, refusals)
  - services/audit_log_service.py (the four fields Section 10's NFR names)
  - the graph/classifier wiring that gets a manager's instruction here

leave_approval_node is exercised directly with a fake StreamWriter and a
mocked erp_client, the same pattern as TestIndividualReportNode in
test_individual_report.py.

The response shapes below are the payloads the story supplied from real
calls (leave request 58, employee "B Geo"), not invented ones — including
leave_count arriving as the STRING "1", which is why _impacted_days renders
rather than computes it.

The property most of this file exists to pin down is FR-08.3's: no path
through this node reaches erp-api's approve endpoint without a confirmation
turn that a PREVIOUS turn armed. Every test that asserts "nothing was
approved" checks the recorded approve calls list is empty, never just that
the wording looks harmless.
"""

import httpx
import pytest

import services.erp_client as erp_client
import services.leave_approval as leave_approval
import services.audit_log_service as audit_log_service
from services.erp_client import ErpApiTimeout, ErpApiUnavailable
from services.leave_approval import (
    BULK_MESSAGE,
    NOT_A_MANAGER_MESSAGE,
    NOT_IN_YOUR_TEAM_MESSAGE,
    leave_approval_node,
)


# Captured before the autouse fixture below swaps it out, so the one test
# that needs the genuine database write path can put it back.
REAL_WRITE = audit_log_service._write


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]

    def done(self):
        events = self.of_type("done")
        assert events, "node finished without emitting a done event"
        return events[-1]

    def answer(self):
        return self.done()["data"]["answer"]


def base_state(query: str, is_manager=True) -> dict:
    return {
        "query": query, "intent": leave_approval.APPROVAL_INTENT, "usage_events": [],
        "bearer_token": "caller-token", "company_id": 7, "conversation_id": "conv-1",
        "is_manager_jwt": True, "is_manager": is_manager,
    }


# -- Fixtures ----------------------------------------------------------------

@pytest.fixture(autouse=True)
def _fake_action_store(monkeypatch):
    """In-memory stand-in for the Redis-backed pending-action state, keyed
    the same way the real one is."""
    store = {}

    def _get(company_id, conversation_id):
        return store.get((str(company_id), conversation_id))

    def _set(company_id, conversation_id, action):
        store[(str(company_id), conversation_id)] = action
        return True

    def _clear(company_id, conversation_id):
        store.pop((str(company_id), conversation_id), None)
        return True

    monkeypatch.setattr(leave_approval.leave_slot_service, "get_manager_action", _get)
    monkeypatch.setattr(leave_approval.leave_slot_service, "set_manager_action", _set)
    monkeypatch.setattr(leave_approval.leave_slot_service, "clear_manager_action", _clear)
    return store


@pytest.fixture(autouse=True)
def _fake_report_store(monkeypatch):
    """The FR-07.3 lookup state this feature reads "approve it" against."""
    store = {}

    def _get(company_id, conversation_id):
        return store.get((str(company_id), conversation_id))

    def _set(company_id, conversation_id, state):
        store[(str(company_id), conversation_id)] = state
        return True

    monkeypatch.setattr(leave_approval.leave_slot_service, "get_report_state", _get)
    monkeypatch.setattr(leave_approval.leave_slot_service, "set_report_state", _set)
    return store


@pytest.fixture(autouse=True)
def _audit_rows(monkeypatch):
    """Captures what audit_log_service would have written. The real
    log_leave_approval still runs — only the database write is replaced — so
    these rows prove the NFR fields are assembled, not just passed along."""
    rows = []
    monkeypatch.setattr(audit_log_service, "_write", lambda **fields: rows.append(fields))
    return rows


def mock_extraction(monkeypatch, action="approve", leave_request_id=None,
                    employee_id=None, employee_name=None, uses_pronoun=False,
                    targets_multiple=False):
    async def _extract(query, today):
        return {
            "action": action, "leave_request_id": leave_request_id,
            "employee_id": employee_id, "employee_name": employee_name,
            "uses_pronoun": uses_pronoun, "targets_multiple": targets_multiple,
        }, None

    monkeypatch.setattr(leave_approval.ai_service, "extract_leave_approval_fields", _extract)


PENDING_LEAVE_58 = {
    "id": 58,
    "employee_id": 3735,
    "employee_number": "geo3",
    "employee_name": "B Geo",
    "leave_type": "Sick Leave",
    "leave_type_slug": "sick_leave",
    "session_type": "Full Day",
    "session_type_slug": "full_day",
    "from_date": "2026-08-25",
    "to_date": "2026-08-25",
    "leave_count": "1",
    "status": 0,
    "status_name": "pending",
    "reason": "test here reasone 1 applied by GEO3",
    "applied_date": "2026-08-24",
}

PENDING_LEAVE_61 = {
    **PENDING_LEAVE_58,
    "id": 61,
    "leave_type": "Casual Leave",
    "from_date": "2026-09-01",
    "to_date": "2026-09-03",
    "leave_count": "3",
}


def pending_response(leaves=(PENDING_LEAVE_58,), employee=None):
    data = {"access_scope": "direct_reports", "total_pending_leaves": len(leaves),
            "leaves": list(leaves)}
    if employee:
        data["employee"] = employee
    return {"http_status": 200, "body": {"success": True, "data": data}}


def name_match_response(candidates, search_matched=True):
    return {"http_status": 200, "body": {"success": True, "data": {
        "action_required": "select_employee",
        "search_matched": search_matched,
        "employees": candidates,
    }}}


APPROVED_BODY = {
    "success": True,
    "message": "Leave request approved successfully.",
    "data": {
        "leave_request_id": 58, "employee_id": 3735, "employee_number": "geo3",
        "employee_name": "B Geo", "leave_type": "Sick Leave",
        "leave_type_slug": "sick_leave", "session_type": "Full Day",
        "session_type_slug": "full_day", "from_date": "2026-08-25",
        "to_date": "2026-08-25", "leave_count": "1",
        "reason": "test here reasone 1 applied by GEO3",
        "status": 1, "status_name": "approved", "applied_date": "2026-08-24",
        "approved_by": {"id": 704, "employee_number": "geo1", "name": "A GeoFencing"},
    },
}

OUT_OF_TEAM_BODY = {"success": False, "message": "Pending leave request was not found in your team."}

# erp-api's AI MANAGER controller answers a business rule with 422, not the
# 400 the older employee routes use. This exact body reached a manager as
# "I'm unable to reach the HR system right now" because the client only
# opted 400 in, so the rule the manager had to act on never got surfaced.
QUOTA_EXCEEDED_MESSAGE = "Cannot approve this as leave count exceed remaining leave for this user"
QUOTA_EXCEEDED_BODY = {
    "success": False,
    "message": QUOTA_EXCEEDED_MESSAGE,
    "data": {"error": QUOTA_EXCEEDED_MESSAGE},
}


def patch_erp(monkeypatch, *, pending=None, approve=None):
    """Stubs both erp-api calls and records what was asked of each. The
    approve list is what every "nothing was executed" assertion checks."""
    pending_responses = list(pending or [])
    approve_calls = []

    async def _pending(token, company_id=None, conversation_id=None,
                       employee_id=None, employee_name=None):
        if not pending_responses:
            raise AssertionError("unexpected extra get_team_pending_leaves call")
        response = pending_responses.pop(0)
        if isinstance(response, Exception):
            raise response
        return response

    async def _approve(token, leave_request_id, company_id=None, conversation_id=None):
        approve_calls.append(leave_request_id)
        if isinstance(approve, Exception):
            raise approve
        return approve

    monkeypatch.setattr(leave_approval.erp_client, "get_team_pending_leaves", _pending)
    monkeypatch.setattr(leave_approval.erp_client, "approve_leave_request", _approve)
    return approve_calls


def _raiser(exc):
    async def _approve(token, leave_request_id, company_id=None, conversation_id=None):
        raise exc
    return _approve


async def arm_confirmation(monkeypatch, query="approve B Geo's leave request",
                           leaves=(PENDING_LEAVE_58,)):
    """Runs the first turn — the one that shows the card — and returns
    (writer, approve_calls) so a test can assert on it before confirming."""
    mock_extraction(monkeypatch, employee_id=3735)
    approve_calls = patch_erp(monkeypatch, pending=[pending_response(leaves)])
    writer = FakeWriter()
    await leave_approval_node(base_state(query), writer)
    return writer, approve_calls


# -- AC1: approval executed on confirmation ----------------------------------

class TestAC1ApprovalExecutedOnConfirmation:
    @pytest.mark.asyncio
    async def test_first_turn_shows_the_card_and_approves_nothing(self, monkeypatch):
        writer, approve_calls = await arm_confirmation(monkeypatch)

        assert approve_calls == [], "an approval ran before the manager confirmed"
        assert writer.of_type("leave_approval_confirmation"), "no confirmation card was emitted"

    @pytest.mark.asyncio
    async def test_confirmation_arms_the_pending_action(self, monkeypatch, _fake_action_store):
        await arm_confirmation(monkeypatch)

        pending = _fake_action_store[("7", "conv-1")]
        assert pending["step"] == "awaiting_confirmation"
        assert pending["leave_request_id"] == 58
        assert pending["action"] == "approve"

    @pytest.mark.asyncio
    async def test_yes_executes_the_approval_for_that_request(self, monkeypatch):
        await arm_confirmation(monkeypatch)
        approve_calls = patch_erp(monkeypatch, approve={"http_status": 200, "body": APPROVED_BODY})

        writer = FakeWriter()
        await leave_approval_node(base_state("yes"), writer)

        assert approve_calls == [58]
        assert writer.of_type("leave_approval_success")
        answer = writer.answer()
        assert "B Geo" in answer and "approved" in answer.lower()

    @pytest.mark.asyncio
    async def test_the_pending_action_is_consumed_so_a_second_yes_cannot_repeat_it(
            self, monkeypatch, _fake_action_store):
        await arm_confirmation(monkeypatch)
        approve_calls = patch_erp(monkeypatch, approve={"http_status": 200, "body": APPROVED_BODY})
        await leave_approval_node(base_state("yes"), FakeWriter())

        assert ("7", "conv-1") not in _fake_action_store

        # A second "yes" now has nothing armed. It must not re-approve.
        patch_erp(monkeypatch, pending=[pending_response()])
        mock_extraction(monkeypatch, action=None)
        await leave_approval_node(base_state("yes"), FakeWriter())
        assert approve_calls == [58]

    @pytest.mark.asyncio
    async def test_approve_it_resolves_against_the_request_just_looked_up(
            self, monkeypatch, _fake_report_store):
        """The story this one follows (FR-07.3) is what put a request on
        screen; "it" names nothing, so the remembered lookup is what the
        action resolves against."""
        _fake_report_store[("7", "conv-1")] = {
            "step": "resolved",
            "last_employee": {"employee_id": 3735, "employee_name": "B Geo"},
            "last_leave_requests": [PENDING_LEAVE_58],
        }
        mock_extraction(monkeypatch, uses_pronoun=True)
        approve_calls = patch_erp(monkeypatch)

        writer = FakeWriter()
        await leave_approval_node(base_state("approve it"), writer)

        assert approve_calls == []
        card = writer.of_type("leave_approval_confirmation")[0]["data"]
        assert card["leave_request_id"] == 58


# -- AC2: the confirmation summary is complete -------------------------------

class TestAC2ConfirmationSummaryIsComplete:
    @pytest.mark.asyncio
    async def test_card_carries_every_required_field(self, monkeypatch):
        writer, _ = await arm_confirmation(monkeypatch)
        card = writer.of_type("leave_approval_confirmation")[0]["data"]

        assert card["employee_name"] == "B Geo"
        assert card["request_type"] == "Leave"
        assert card["date_range"] == "2026-08-25"
        assert card["impacted_days"] == "1"
        assert card["action_type"] == "Approve"

    @pytest.mark.asyncio
    async def test_text_reply_carries_the_same_fields(self, monkeypatch):
        """The structured event is for a UI; a plain-text client has to be
        able to read the same five things."""
        writer, _ = await arm_confirmation(monkeypatch)
        answer = writer.answer()

        assert "Employee: B Geo" in answer
        assert "Request Type: Leave" in answer
        assert "Date Range: 2026-08-25" in answer
        assert "Impacted Days: 1" in answer
        assert "Action: Approve" in answer

    @pytest.mark.asyncio
    async def test_multi_day_request_renders_a_range(self, monkeypatch):
        writer, _ = await arm_confirmation(monkeypatch, leaves=(PENDING_LEAVE_61,))
        card = writer.of_type("leave_approval_confirmation")[0]["data"]

        assert card["date_range"] == "2026-09-01 to 2026-09-03"
        assert card["impacted_days"] == "3"

    @pytest.mark.asyncio
    async def test_card_is_also_on_the_done_payload(self, monkeypatch):
        """A client that only reads the final payload still gets the card."""
        writer, _ = await arm_confirmation(monkeypatch)
        data = writer.done()["data"]
        assert data["leave_request_id"] == 58
        assert data["requires_confirmation"] is True


# -- AC3: no silent execution ------------------------------------------------

class TestAC3NoSilentExecution:
    @pytest.mark.asyncio
    async def test_requesting_the_action_changes_nothing(self, monkeypatch):
        _, approve_calls = await arm_confirmation(monkeypatch)
        assert approve_calls == []

    @pytest.mark.asyncio
    async def test_declining_leaves_the_request_pending(self, monkeypatch, _fake_action_store):
        await arm_confirmation(monkeypatch)
        approve_calls = patch_erp(monkeypatch)

        writer = FakeWriter()
        await leave_approval_node(base_state("no"), writer)

        assert approve_calls == []
        assert ("7", "conv-1") not in _fake_action_store
        assert "Nothing has been changed" in writer.answer()

    @pytest.mark.asyncio
    @pytest.mark.parametrize("reply", ["not yet", "hold off", "cancel", "don't approve it"])
    async def test_declining_wordings_never_execute(self, monkeypatch, reply):
        await arm_confirmation(monkeypatch)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])
        mock_extraction(monkeypatch, employee_id=3735)

        await leave_approval_node(base_state(reply), FakeWriter())
        assert approve_calls == []

    @pytest.mark.asyncio
    @pytest.mark.parametrize("reply", [
        "no", "cancel", "not yet", "hold off", "never mind", "stop",
        "don't approve it", "dont approve it", "no, don't approve it",
        "don't approve this request",
    ])
    async def test_a_decline_is_ANSWERED_as_a_decline_not_re_asked(
            self, monkeypatch, _fake_action_store, reply):
        """Not executing is only half of it - the manager has to be TOLD
        nothing happened, and the card must not survive.

        "don't approve it" used to fail this: the branch was gated on
        `not mentions_action(query)`, which matched the bare verb "approve"
        inside the refusal, so an explicit no was re-read as a fresh
        instruction and answered with the SAME confirmation card, re-armed.
        Nothing executed, but the manager said don't and was asked to
        confirm again."""
        await arm_confirmation(monkeypatch)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])
        mock_extraction(monkeypatch, employee_id=3735)

        writer = FakeWriter()
        await leave_approval_node(base_state(reply), writer)

        assert approve_calls == []
        assert not writer.of_type("leave_approval_confirmation"), \
            "a decline was answered by re-showing the confirmation card"
        assert "Nothing has been changed" in writer.answer()
        assert ("7", "conv-1") not in _fake_action_store, "the card stayed armed after a decline"

    @pytest.mark.asyncio
    @pytest.mark.parametrize("reply", [
        "no, approve Priya's instead",
        "cancel and approve request 61",
    ])
    async def test_a_decline_that_names_a_new_target_still_re_aims(self, monkeypatch, reply):
        """The other side of the same rule: a message that declines AND names
        a request of its own is a re-aim - the new target is the part that
        needs acting on - so it must produce a fresh card, not a bare
        "nothing changed"."""
        await arm_confirmation(monkeypatch)
        other = {**PENDING_LEAVE_58, "id": 61, "employee_id": 3736, "employee_name": "C Geo"}
        mock_extraction(monkeypatch, employee_id=3736)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response((other,))])

        writer = FakeWriter()
        await leave_approval_node(base_state(reply), writer)

        assert approve_calls == []
        card = writer.of_type("leave_approval_confirmation")[0]["data"]
        assert card["leave_request_id"] == 61

    @pytest.mark.asyncio
    async def test_an_unclear_reply_re_asks_instead_of_executing(self, monkeypatch):
        """Neither a yes nor a no. It is re-read as a fresh instruction,
        which can only ever produce another card."""
        await arm_confirmation(monkeypatch)
        mock_extraction(monkeypatch, employee_id=3735)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])

        writer = FakeWriter()
        await leave_approval_node(base_state("what's his leave balance again"), writer)

        assert approve_calls == []
        assert writer.of_type("leave_approval_confirmation")

    @pytest.mark.asyncio
    async def test_a_confirm_word_with_a_new_name_re_aims_instead_of_executing(self, monkeypatch):
        """Live repro (wrong-employee approval): with B Geo's card armed,
        "go ahead and approve C Geo's leave request" executed B GEO's
        request 58 and reported it as a success naming B Geo - the newly
        named employee was never read. "go ahead" matches
        _EXPLICIT_CONFIRM_PATTERNS ANYWHERE in the message, so the confirm
        word beat the re-aim. A reply that names a request of its own must
        build a NEW card, never execute the armed one."""
        await arm_confirmation(monkeypatch)  # arms request 58 / B Geo

        other = {**PENDING_LEAVE_58, "id": 61, "employee_id": 3736, "employee_name": "C Geo"}
        mock_extraction(monkeypatch, employee_id=3736)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response((other,))])

        writer = FakeWriter()
        await leave_approval_node(
            base_state("go ahead and approve C Geo's leave request"), writer)

        assert approve_calls == [], "the ARMED request was executed on a re-aimed instruction"
        card = writer.of_type("leave_approval_confirmation")[0]["data"]
        assert card["leave_request_id"] == 61
        assert card["employee_name"] == "C Geo"

    @pytest.mark.asyncio
    @pytest.mark.parametrize("reply", [
        "go ahead and approve C Geo's leave request",
        "proceed with C Geo's request",
        "confirm approving C Geo's leave",
        "go ahead and approve request 61",
    ])
    async def test_no_confirm_wording_can_execute_while_naming_someone_else(
            self, monkeypatch, reply):
        """Every phrasing that pairs an instruction word with a target of its
        own. None may reach erp-api's approve endpoint."""
        await arm_confirmation(monkeypatch)

        other = {**PENDING_LEAVE_58, "id": 61, "employee_id": 3736, "employee_name": "C Geo"}
        mock_extraction(monkeypatch, employee_id=3736)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response((other,))])

        await leave_approval_node(base_state(reply), FakeWriter())
        assert approve_calls == []

    @pytest.mark.asyncio
    async def test_a_yes_with_nothing_armed_never_approves(self, monkeypatch):
        """No prior card in this conversation — "yes" is not an instruction
        to approve anything."""
        mock_extraction(monkeypatch, action=None)
        approve_calls = patch_erp(monkeypatch)

        writer = FakeWriter()
        await leave_approval_node(base_state("yes"), writer)

        assert approve_calls == []
        assert "Which request" in writer.answer()

    @pytest.mark.asyncio
    async def test_ambiguous_target_asks_which_request(self, monkeypatch):
        """Two pending requests for the same person and nothing says which.
        Guessing here approves the wrong one."""
        mock_extraction(monkeypatch, employee_id=3735)
        approve_calls = patch_erp(
            monkeypatch, pending=[pending_response((PENDING_LEAVE_58, PENDING_LEAVE_61))])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave"), writer)

        assert approve_calls == []
        assert not writer.of_type("leave_approval_confirmation")
        answer = writer.answer()
        assert "#58" in answer and "#61" in answer

    @pytest.mark.asyncio
    async def test_the_shortlist_is_a_table_a_manager_can_compare_dates_in(
            self, monkeypatch):
        """The point of the table is comparison: one row per request, the
        same four columns every time, so dates line up instead of having to
        be read out of prose."""
        mock_extraction(monkeypatch, employee_id=3735)
        patch_erp(monkeypatch, pending=[pending_response((PENDING_LEAVE_58, PENDING_LEAVE_61))])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave"), writer)

        lines = writer.answer().splitlines()
        assert "| Request | Leave Type | Dates | Days |" in lines
        assert "| --- | --- | --- | --- |" in lines
        assert "| #58 | Sick Leave | 2026-08-25 | 1 |" in lines
        assert "| #61 | Casual Leave | 2026-09-01 to 2026-09-03 | 3 |" in lines
        # Every row carries the same column count, or the table renders ragged.
        rows = [ln for ln in lines if ln.startswith("|")]
        # Escaped pipes are content, not column separators - count only the
        # separators, or a correctly escaped value looks like a ragged row.
        assert len({ln.replace("\\|", "").count("|") for ln in rows}) == 1

    @pytest.mark.asyncio
    async def test_the_shortlist_says_how_to_pick_one(self, monkeypatch):
        """Naming an ID is the only reply that resolves this unambiguously,
        so the table has to show what that looks like."""
        mock_extraction(monkeypatch, employee_id=3735)
        patch_erp(monkeypatch, pending=[pending_response((PENDING_LEAVE_58, PENDING_LEAVE_61))])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave"), writer)

        assert 'approve request 58' in writer.answer()

    @pytest.mark.asyncio
    async def test_the_shortlist_also_comes_back_as_structured_rows(self, monkeypatch):
        """So a client can draw its own table rather than parse markdown."""
        mock_extraction(monkeypatch, employee_id=3735)
        patch_erp(monkeypatch, pending=[pending_response((PENDING_LEAVE_58, PENDING_LEAVE_61))])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave"), writer)

        data = writer.done()["data"]
        assert data["action_required"] == "select_leave_request"
        assert [lv["leave_request_id"] for lv in data["leaves"]] == [58, 61]
        assert data["leaves"][1]["date_range"] == "2026-09-01 to 2026-09-03"

    @pytest.mark.asyncio
    async def test_a_pipe_in_erp_data_cannot_break_the_table(self, monkeypatch):
        """leave_type is free-form text from erp-api; an unescaped pipe would
        end the column early and misalign every row after it."""
        mock_extraction(monkeypatch, employee_id=3735)
        odd = {**PENDING_LEAVE_61, "leave_type": "Casual | Unpaid"}
        patch_erp(monkeypatch, pending=[pending_response((PENDING_LEAVE_58, odd))])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave"), writer)

        rows = [ln for ln in writer.answer().splitlines() if ln.startswith("|")]
        # Escaped pipes are content, not column separators - count only the
        # separators, or a correctly escaped value looks like a ragged row.
        assert len({ln.replace("\\|", "").count("|") for ln in rows}) == 1
        assert "Casual \\| Unpaid" in writer.answer()

    @pytest.mark.asyncio
    async def test_no_card_is_shown_when_the_pending_action_cannot_be_stored(self, monkeypatch):
        """A card whose "yes" has nowhere to resolve against is worse than
        no card: it invites a confirmation that would silently do nothing."""
        mock_extraction(monkeypatch, employee_id=3735)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])
        monkeypatch.setattr(leave_approval.leave_slot_service, "set_manager_action",
                            lambda *a, **k: False)

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave"), writer)

        assert approve_calls == []
        assert not writer.of_type("leave_approval_confirmation")
        assert "HR portal" in writer.answer()

    @pytest.mark.asyncio
    async def test_execution_is_refused_when_the_pending_action_cannot_be_cleared(
            self, monkeypatch):
        """Clearing first is what stops a repeatable approval; if it can't
        be cleared, the approval doesn't run at all."""
        await arm_confirmation(monkeypatch)
        approve_calls = patch_erp(monkeypatch, approve={"http_status": 200, "body": APPROVED_BODY})
        monkeypatch.setattr(leave_approval.leave_slot_service, "clear_manager_action",
                            lambda *a, **k: False)

        writer = FakeWriter()
        await leave_approval_node(base_state("yes"), writer)

        assert approve_calls == []
        assert "Nothing has been changed" in writer.answer()


# -- AC4: the approval is logged ---------------------------------------------

class TestAC4ApprovalIsLogged:
    @pytest.mark.asyncio
    async def test_executed_approval_writes_every_nfr_field(self, monkeypatch, _audit_rows):
        await arm_confirmation(monkeypatch)
        patch_erp(monkeypatch, approve={"http_status": 200, "body": APPROVED_BODY})
        await leave_approval_node(base_state("yes"), FakeWriter())

        assert len(_audit_rows) == 1
        row = _audit_rows[0]
        assert row["created_at"] is not None                 # timestamp
        assert row["decision_basis"]                          # decision basis
        assert row["rule_version"] == audit_log_service.RULE_VERSION
        assert row["source"] == "AI Assistant"

    @pytest.mark.asyncio
    async def test_the_row_identifies_what_was_approved_and_by_whom(self, monkeypatch, _audit_rows):
        await arm_confirmation(monkeypatch)
        patch_erp(monkeypatch, approve={"http_status": 200, "body": APPROVED_BODY})
        await leave_approval_node(base_state("yes"), FakeWriter())

        row = _audit_rows[0]
        assert row["action"] == "approve"
        assert row["resource_type"] == "leave_request"
        assert row["resource_id"] == 58
        assert row["employee_name"] == "B Geo"
        assert row["approver_id"] == 704
        assert row["approver_name"] == "A GeoFencing"
        assert row["executed"] is True

    @pytest.mark.asyncio
    async def test_decision_basis_quotes_both_turns(self, monkeypatch, _audit_rows):
        """An auditor has to be able to see what was asked and what was
        confirmed, not just that something was."""
        await arm_confirmation(monkeypatch, query="approve B Geo's leave request")
        patch_erp(monkeypatch, approve={"http_status": 200, "body": APPROVED_BODY})
        await leave_approval_node(base_state("yes, go ahead"), FakeWriter())

        basis = _audit_rows[0]["decision_basis"]
        assert "approve B Geo's leave request" in basis
        assert "yes, go ahead" in basis
        assert "FR-08.3" in basis

    @pytest.mark.asyncio
    async def test_a_refused_approval_is_logged_as_not_executed(self, monkeypatch, _audit_rows):
        await arm_confirmation(monkeypatch)
        patch_erp(monkeypatch, approve={"http_status": 400, "body": OUT_OF_TEAM_BODY})

        writer = FakeWriter()
        await leave_approval_node(base_state("yes"), writer)

        assert len(_audit_rows) == 1
        row = _audit_rows[0]
        assert row["executed"] is False
        assert row["erp_message"] == OUT_OF_TEAM_BODY["message"]
        assert NOT_IN_YOUR_TEAM_MESSAGE in writer.answer()

    @pytest.mark.asyncio
    async def test_a_422_quota_refusal_reaches_the_manager_verbatim(
            self, monkeypatch, _audit_rows):
        """The whole point of the 422 opt-in: the manager is told the balance
        is short, not that the HR system is unreachable."""
        await arm_confirmation(monkeypatch)
        patch_erp(monkeypatch, approve={"http_status": 422, "body": QUOTA_EXCEEDED_BODY})

        writer = FakeWriter()
        await leave_approval_node(base_state("yes"), writer)

        answer = writer.answer()
        assert QUOTA_EXCEEDED_MESSAGE in answer
        assert "unable to reach the HR system" not in answer
        assert "Nothing has been changed." in answer
        # The rule arrives unpunctuated, so it must not run into the next
        # sentence: "...for this user Nothing has been changed."
        assert f"{QUOTA_EXCEEDED_MESSAGE}. Nothing" in answer

        row = _audit_rows[0]
        assert row["executed"] is False
        assert row["erp_status"] == 422
        assert row["erp_message"] == QUOTA_EXCEEDED_MESSAGE

    @pytest.mark.asyncio
    async def test_a_timeout_is_logged_as_an_attempt_with_an_unknown_outcome(
            self, monkeypatch, _audit_rows):
        await arm_confirmation(monkeypatch)
        patch_erp(monkeypatch, approve=ErpApiTimeout("boom"))

        writer = FakeWriter()
        await leave_approval_node(base_state("yes"), writer)

        row = _audit_rows[0]
        assert row["executed"] is False
        assert "unknown" in (row["erp_message"] or "")
        assert "HR portal" in writer.answer()

    @pytest.mark.asyncio
    async def test_nothing_is_logged_for_a_turn_that_only_showed_a_card(
            self, monkeypatch, _audit_rows):
        await arm_confirmation(monkeypatch)
        assert _audit_rows == []

    @pytest.mark.asyncio
    async def test_a_failed_log_write_does_not_break_the_approval(self, monkeypatch):
        """The approval already happened at erp-api; a logging failure must
        not tell the manager otherwise."""
        def _boom(**fields):
            raise RuntimeError("db down")

        await arm_confirmation(monkeypatch)
        patch_erp(monkeypatch, approve={"http_status": 200, "body": APPROVED_BODY})
        monkeypatch.setattr(audit_log_service, "_write", _boom)

        writer = FakeWriter()
        await leave_approval_node(base_state("yes"), writer)
        assert writer.of_type("leave_approval_success")


class TestAuditLogServiceDirectly:
    @pytest.mark.asyncio
    async def test_source_and_rule_version_are_not_caller_supplied(self, _audit_rows):
        await audit_log_service.log_leave_approval(
            action="approve", leave_request_id=58, executed=True,
            confirmation_query="yes", requested_query="approve it",
        )
        row = _audit_rows[0]
        assert row["source"] == "AI Assistant"
        assert row["rule_version"] == audit_log_service.RULE_VERSION

    @pytest.mark.asyncio
    async def test_a_database_failure_is_swallowed(self, monkeypatch):
        """The real _write, against a session factory that fails the way a
        down database does — the autouse capture fixture is put back so this
        exercises the actual write path rather than the stand-in."""
        monkeypatch.setattr(audit_log_service, "_write", REAL_WRITE)
        monkeypatch.setattr(audit_log_service, "SessionLocal",
                            lambda: (_ for _ in ()).throw(RuntimeError("no db")))
        # Must not raise.
        await audit_log_service.log_leave_approval(
            action="approve", leave_request_id=58, executed=True, confirmation_query="yes")


# -- AC5: rejection/disapproval is out of scope ------------------------------

class TestRejection:
    """Rejection used to be refused outright because erp-api had no route for
    it. It now has POST .../reject, so these assert the SAFETY properties the
    old refusal was standing in for, against the real path:

      * a reject instruction never runs the APPROVE endpoint;
      * the proposing turn executes nothing at all (FR-08.3, same as approve);
      * a reject re-aim replaces an armed approve card rather than leaving it
        live for a later bare "yes".

    The path is gated OFF by default now (LEAVE_REJECTION_ENABLED — the story
    this flow was built against says approve is the only action the assistant
    offers). These tests turn it on, so the capability stays covered and
    re-enabling it is a verified one-line change rather than a leap of faith.
    TestRejectionDisabled below covers the shipped default.
    """

    @pytest.fixture(autouse=True)
    def _rejection_enabled(self, monkeypatch):
        monkeypatch.setattr(leave_approval, "LEAVE_REJECTION_ENABLED", True)

    @pytest.mark.asyncio
    async def test_a_rejection_is_never_treated_as_an_approval(self, monkeypatch):
        mock_extraction(monkeypatch, action="reject", employee_id=3735)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])

        writer = FakeWriter()
        await leave_approval_node(base_state("reject B Geo's leave request"), writer)

        assert approve_calls == [], "the approve endpoint ran for a rejection"
        card = writer.of_type("leave_approval_confirmation")[0]["data"]
        assert card["action"] == "reject"
        assert card["action_type"] == "Reject"

    @pytest.mark.asyncio
    async def test_the_proposing_turn_executes_nothing_and_asks_for_a_reason(
            self, monkeypatch):
        """erp-api requires a rejection_reason, and the employee reads it, so
        it is the one field this flow must not invent."""
        mock_extraction(monkeypatch, action="reject", employee_id=3735)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])

        writer = FakeWriter()
        await leave_approval_node(base_state("reject B Geo's leave request"), writer)

        assert approve_calls == []
        answer = writer.answer()
        assert "reason for rejecting" in answer
        assert "Action: Reject" in answer

    @pytest.mark.asyncio
    async def test_the_reason_turn_rejects_and_records_the_reason(
            self, monkeypatch, _audit_rows):
        mock_extraction(monkeypatch, action="reject", employee_id=3735)
        reject_calls = []

        async def _reject(token, leave_request_id, rejection_reason,
                          company_id=None, conversation_id=None):
            reject_calls.append((leave_request_id, rejection_reason))
            return {"http_status": 200, "body": {"success": True, "data": {
                **PENDING_LEAVE_58, "status_name": "rejected",
                "rejection_reason": rejection_reason}}}

        patch_erp(monkeypatch, pending=[pending_response()])
        monkeypatch.setattr(leave_approval.erp_client, "reject_leave_request", _reject)

        await leave_approval_node(base_state("reject B Geo's leave request"), FakeWriter())

        writer = FakeWriter()
        await leave_approval_node(base_state("Team is short-staffed that week"), writer)

        assert reject_calls == [(58, "Team is short-staffed that week")]
        assert "Rejected" in writer.answer()
        assert _audit_rows[-1]["action"] == "reject"
        assert _audit_rows[-1]["executed"] is True

    @pytest.mark.asyncio
    async def test_a_one_word_reason_is_asked_again_before_any_call(self, monkeypatch):
        """erp-api validates 3-500 chars; asking here keeps the card armed
        instead of spending a call to be told the same thing."""
        mock_extraction(monkeypatch, action="reject", employee_id=3735)

        async def _must_not_run(*a, **k):
            raise AssertionError("erp-api was called for a too-short reason")

        patch_erp(monkeypatch, pending=[pending_response()])
        monkeypatch.setattr(leave_approval.erp_client, "reject_leave_request", _must_not_run)

        await leave_approval_node(base_state("reject B Geo's leave request"), FakeWriter())

        writer = FakeWriter()
        await leave_approval_node(base_state("no"), writer)  # decline still wins
        assert "pending" in writer.answer().lower()

    @pytest.mark.asyncio
    async def test_declining_the_reason_turn_changes_nothing(
            self, monkeypatch, _fake_action_store):
        mock_extraction(monkeypatch, action="reject", employee_id=3735)

        async def _must_not_run(*a, **k):
            raise AssertionError("a rejection ran after the manager declined")

        patch_erp(monkeypatch, pending=[pending_response()])
        monkeypatch.setattr(leave_approval.erp_client, "reject_leave_request", _must_not_run)

        await leave_approval_node(base_state("reject B Geo's leave request"), FakeWriter())

        writer = FakeWriter()
        await leave_approval_node(base_state("no"), writer)

        assert "Nothing has been changed" in writer.answer()
        assert _fake_action_store == {}, "the reject card was left armed after a decline"

    @pytest.mark.asyncio
    async def test_a_reject_re_aim_replaces_an_armed_approve_card(
            self, monkeypatch, _fake_action_store):
        """Otherwise a later bare "yes" would APPROVE a request the manager
        had just asked to reject - the original reason this case was tested."""
        await arm_confirmation(monkeypatch)
        mock_extraction(monkeypatch, action="reject", employee_id=3735)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])

        writer = FakeWriter()
        await leave_approval_node(base_state("actually reject it instead"), writer)

        assert approve_calls == []
        armed = _fake_action_store[("7", "conv-1")]
        assert armed["action"] == "reject"
        assert armed["step"] == "awaiting_rejection_reason"


# -- Bulk (FR-07.5) ----------------------------------------------------------

class TestBulkIsRoutedElsewhere:
    @pytest.mark.asyncio
    async def test_multiple_requests_are_routed_to_the_bulk_approvals_page(self, monkeypatch):
        """Bulk is not attempted here, and no longer answered with a bare
        "I can only do one at a time" either - the manager is handed the
        Bulk Approvals page instead of a dead end. What must NOT change is
        that nothing was approved."""
        mock_extraction(monkeypatch, targets_multiple=True)
        approve_calls = patch_erp(monkeypatch)

        writer = FakeWriter()
        await leave_approval_node(base_state("approve these two requests"), writer)

        assert approve_calls == []

        done = writer.done()
        assert done["intent"] == "bulk_approvals"
        navigation = done["data"]["navigation"]
        assert navigation["category"] == "bulk_approvals"
        assert navigation["button"]["path"]
        assert writer.answer() == navigation["message"]

    @pytest.mark.asyncio
    async def test_bulk_clears_an_armed_approval_too(self, monkeypatch, _fake_action_store):
        await arm_confirmation(monkeypatch)
        mock_extraction(monkeypatch, targets_multiple=True)
        patch_erp(monkeypatch)

        await leave_approval_node(base_state("approve all of them"), FakeWriter())
        assert ("7", "conv-1") not in _fake_action_store


# -- Permission -------------------------------------------------------------

class TestManagerGate:
    @pytest.mark.asyncio
    async def test_a_non_manager_is_refused(self, monkeypatch):
        mock_extraction(monkeypatch, employee_id=3735)
        approve_calls = patch_erp(monkeypatch)

        writer = FakeWriter()
        await leave_approval_node(
            {**base_state("approve B Geo's leave"), "is_manager": False,
             "is_manager_jwt": False}, writer)

        assert approve_calls == []
        assert writer.answer() == NOT_A_MANAGER_MESSAGE
        assert writer.done()["intent"] == "team_attendance_restricted"

    @pytest.mark.asyncio
    async def test_an_unverifiable_role_refuses_rather_than_guessing(self, monkeypatch):
        mock_extraction(monkeypatch, employee_id=3735)
        approve_calls = patch_erp(monkeypatch)

        writer = FakeWriter()
        await leave_approval_node(
            {**base_state("approve B Geo's leave"),
             "is_manager": leave_approval.MANAGER_UNKNOWN}, writer)

        assert approve_calls == []
        assert "couldn't verify your access" in writer.answer()

    @pytest.mark.asyncio
    async def test_a_non_manager_cannot_execute_an_armed_approval(self, monkeypatch):
        """The gate is ahead of the confirmation branch, so a role that
        changed between the two turns cannot ride an armed card through."""
        await arm_confirmation(monkeypatch)
        approve_calls = patch_erp(monkeypatch)

        writer = FakeWriter()
        await leave_approval_node(
            {**base_state("yes"), "is_manager": False, "is_manager_jwt": False}, writer)

        assert approve_calls == []
        assert writer.answer() == NOT_A_MANAGER_MESSAGE

    @pytest.mark.asyncio
    async def test_the_gate_falls_back_to_erp_when_it_has_not_run(self, monkeypatch):
        async def _context(token, company_id=None, conversation_id=None):
            return {"http_status": 200, "body": {"success": True, "data": {"is_manager": False}}}

        monkeypatch.setattr(leave_approval.erp_client, "get_leave_context", _context)
        mock_extraction(monkeypatch, employee_id=3735)
        approve_calls = patch_erp(monkeypatch)

        writer = FakeWriter()
        await leave_approval_node(
            {**base_state("approve B Geo's leave"), "is_manager": None,
             "is_manager_jwt": False}, writer)

        assert approve_calls == []
        assert writer.answer() == NOT_A_MANAGER_MESSAGE


class TestTeamScope:
    @pytest.mark.asyncio
    async def test_a_request_id_outside_the_team_is_refused_with_erps_own_wording(
            self, monkeypatch):
        mock_extraction(monkeypatch, leave_request_id=999)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve request 999"), writer)

        assert approve_calls == []
        assert writer.answer() == NOT_IN_YOUR_TEAM_MESSAGE

    @pytest.mark.asyncio
    async def test_a_name_matching_nobody_in_the_team_offers_the_team(
            self, monkeypatch):
        """erp-api answers an unknown name with search_matched=false plus the
        FULL team roster, and that roster is now offered to pick from.

        This used to answer NOT_IN_YOUR_TEAM_MESSAGE and stop, on the
        reasoning that showing the roster leaks who reports to whom. It does
        not: erp-api returns the same search_matched=false WITH the same
        roster for gibberish, for a typo, and for a real employee on another
        manager's team, so all three still look identical from outside - and
        the roster is the caller's own reports, which they may already list.
        individual_report.py's read path made this call first; the approve
        path now matches it instead of dead-ending on a typo.

        What must still hold is below: nothing is approved, and nothing is
        said about whether "Someone Else" exists.
        """
        mock_extraction(monkeypatch, employee_name="Someone Else")
        roster = [{"employee_id": 3735, "employee_name": "B Geo", "employee_number": "geo3"},
                  {"employee_id": 3736, "employee_name": "C Geo", "employee_number": "geo4"}]
        approve_calls = patch_erp(
            monkeypatch, pending=[name_match_response(roster, search_matched=False)])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve Someone Else's leave"), writer)

        answer = writer.answer()
        assert approve_calls == [], "an unmatched name must approve nothing"
        assert "No employee matched that name" in answer
        assert "B Geo" in answer and "C Geo" in answer
        # Nothing is revealed about the person who was actually named.
        assert "Someone Else" not in answer

    @pytest.mark.asyncio
    async def test_an_employee_number_resolves_from_the_roster_erp_could_not_match(
            self, monkeypatch):
        """erp-api searches the NAME field only, so "geo3" comes back
        search_matched=false with the full roster - even though geo3 is on
        the team. The number is matched against that roster instead of being
        refused as out-of-team."""
        mock_extraction(monkeypatch, employee_name="geo3")
        roster = [{"employee_id": 3735, "employee_name": "B Geo", "employee_number": "geo3"},
                  {"employee_id": 3736, "employee_name": "C Geo", "employee_number": "geo4"}]
        approve_calls = patch_erp(monkeypatch, pending=[
            name_match_response(roster, search_matched=False),
            pending_response(),
        ])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve geo3 leave request"), writer)

        assert approve_calls == [], "an approval ran before the manager confirmed"
        card = writer.of_type("leave_approval_confirmation")[0]["data"]
        assert card["leave_request_id"] == 58
        assert card["employee_name"] == "B Geo"

    @pytest.mark.asyncio
    async def test_the_resolved_person_is_shown_with_the_number_that_was_typed(
            self, monkeypatch):
        """A manager who typed "geo3" and is answered about "Ayush Jio" must
        be able to see WHY - the roster swap from number to name is ours, so
        both are carried in every label the manager reads."""
        mock_extraction(monkeypatch, employee_name="geo3")
        roster = [{"employee_id": 3735, "employee_name": "Ayush Jio", "employee_number": "geo3"},
                  {"employee_id": 3736, "employee_name": "C Geo", "employee_number": "geo4"}]
        two_pending = [
            {**PENDING_LEAVE_58, "employee_name": "Ayush Jio"},
            {**PENDING_LEAVE_58, "id": 61, "employee_name": "Ayush Jio"},
        ]
        patch_erp(monkeypatch, pending=[
            name_match_response(roster, search_matched=False),
            pending_response(two_pending),
        ])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve geo3 leave request"), writer)

        assert "Ayush Jio (geo3)" in writer.answer()

    @pytest.mark.asyncio
    async def test_the_confirmation_card_names_the_employee_number_too(self, monkeypatch):
        """The same rule on the text a state change is confirmed from."""
        mock_extraction(monkeypatch, employee_name="geo3")
        roster = [{"employee_id": 3735, "employee_name": "B Geo", "employee_number": "geo3"},
                  {"employee_id": 3736, "employee_name": "C Geo", "employee_number": "geo4"}]
        patch_erp(monkeypatch, pending=[
            name_match_response(roster, search_matched=False),
            pending_response(),
        ])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve geo3 leave request"), writer)

        assert "- Employee: B Geo (geo3)" in writer.answer()

    @pytest.mark.asyncio
    async def test_an_employee_number_is_matched_exactly_not_as_a_prefix(self, monkeypatch):
        """"geo1" must not also pull in "geo11" - a precise reference stays
        precise, and the near-miss is never silently approved."""
        mock_extraction(monkeypatch, employee_name="geo1")
        roster = [{"employee_id": 3735, "employee_name": "B Geo", "employee_number": "geo1"},
                  {"employee_id": 3772, "employee_name": "Akash geo A", "employee_number": "geo11"}]
        approve_calls = patch_erp(monkeypatch, pending=[
            name_match_response(roster, search_matched=False),
            pending_response(),
        ])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve geo1 leave request"), writer)

        assert approve_calls == []
        card = writer.of_type("leave_approval_confirmation")[0]["data"]
        assert card["leave_request_id"] == 58

    @pytest.mark.asyncio
    async def test_a_roster_term_matching_several_offers_a_selection_not_the_roster(
            self, monkeypatch):
        """A term that narrows the roster to more than one asks which - and
        only the narrowed rows are shown, never the whole team."""
        mock_extraction(monkeypatch, employee_name="Geo")
        roster = [{"employee_id": 3735, "employee_name": "B Geo", "employee_number": "geo3"},
                  {"employee_id": 3736, "employee_name": "C Geo", "employee_number": "geo4"},
                  {"employee_id": 3777, "employee_name": "Ayush Chandra",
                   "employee_number": "EMP-578"}]
        approve_calls = patch_erp(monkeypatch, pending=[
            name_match_response(roster, search_matched=False)])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve Geo's leave request"), writer)

        assert approve_calls == []
        offered = writer.of_type("employee_selection")[0]["data"]["employees"]
        assert [e["employee_id"] for e in offered] == [3735, 3736]

    @pytest.mark.asyncio
    async def test_a_single_name_match_is_re_resolved_by_id(self, monkeypatch):
        """erp-api returns the select_employee shape even for one hit."""
        mock_extraction(monkeypatch, employee_name="B Geo")
        one = [{"employee_id": 3735, "employee_name": "B Geo", "employee_number": "geo3"}]
        patch_erp(monkeypatch, pending=[name_match_response(one), pending_response()])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave"), writer)

        card = writer.of_type("leave_approval_confirmation")[0]["data"]
        assert card["leave_request_id"] == 58

    @pytest.mark.asyncio
    async def test_ambiguous_name_offers_a_selection_and_approves_nothing(self, monkeypatch):
        mock_extraction(monkeypatch, employee_name="Geo")
        two = [{"employee_id": 3735, "employee_name": "B Geo", "employee_number": "geo3"},
               {"employee_id": 3736, "employee_name": "C Geo", "employee_number": "geo4"}]
        approve_calls = patch_erp(monkeypatch, pending=[name_match_response(two)])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve Geo's leave"), writer)

        assert approve_calls == []
        assert writer.of_type("employee_selection")

    @pytest.mark.asyncio
    async def test_an_employee_with_nothing_pending_is_told_so(self, monkeypatch):
        mock_extraction(monkeypatch, employee_id=3735)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response(())])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave"), writer)

        assert approve_calls == []
        assert "no pending leave requests" in writer.answer()


class TestErpFailures:
    @pytest.mark.asyncio
    @pytest.mark.parametrize("error,expected", [
        (ErpApiTimeout("t"), "couldn't reach the HR system in time"),
        (ErpApiUnavailable("u"), "unable to reach the HR system"),
    ])
    async def test_lookup_failures_are_reported_not_raised(self, monkeypatch, error, expected):
        mock_extraction(monkeypatch, employee_id=3735)
        patch_erp(monkeypatch, pending=[error])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave"), writer)
        assert expected in writer.answer()


# -- Mid-flow routing -------------------------------------------------------

class TestPendingApprovalRouting:
    def test_a_bare_yes_routes_here_while_a_card_is_armed(self, _fake_action_store):
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        assert leave_approval.resolve_pending_approval_intent(7, "conv-1", "yes") == \
            leave_approval.APPROVAL_INTENT

    def test_a_no_routes_here_too(self, _fake_action_store):
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        assert leave_approval.resolve_pending_approval_intent(7, "conv-1", "no thanks") == \
            leave_approval.APPROVAL_INTENT

    def test_an_unrelated_question_is_left_to_normal_classification(self, _fake_action_store):
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        assert leave_approval.resolve_pending_approval_intent(
            7, "conv-1", "what is the sick leave policy") is None

    def test_a_question_using_the_same_verb_is_left_alone_too(self, _fake_action_store):
        """The card keeps waiting; the question gets a normal answer."""
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        assert leave_approval.resolve_pending_approval_intent(
            7, "conv-1", "what is the leave approval process?") is None

    def test_a_re_aimed_instruction_routes_here(self, _fake_action_store):
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        assert leave_approval.resolve_pending_approval_intent(
            7, "conv-1", "actually approve Priya's request instead") == \
            leave_approval.APPROVAL_INTENT

    @pytest.mark.parametrize("reply", [
        "proceed with Priya's request",
        "go ahead with request 61",
    ])
    def test_a_re_aim_carrying_no_action_verb_still_routes_here(
            self, _fake_action_store, reply):
        """"proceed with Priya's request" names a target but contains no
        approve/reject verb, so mentions_action alone missed it and the
        re-aim fell through to normal classification - answered as some
        other kind of question while the armed card sat waiting."""
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        assert leave_approval.resolve_pending_approval_intent(7, "conv-1", reply) == \
            leave_approval.APPROVAL_INTENT

    def test_nothing_armed_means_no_hijack(self):
        assert leave_approval.resolve_pending_approval_intent(7, "conv-1", "yes") is None

    def test_a_selection_reply_routes_here(self, _fake_action_store):
        _fake_action_store[("7", "conv-1")] = {
            "step": "awaiting_employee_selection",
            "candidates": [{"employee_id": 3735, "employee_name": "B Geo",
                            "employee_number": "geo3"}],
        }
        assert leave_approval.resolve_pending_approval_intent(7, "conv-1", "B Geo") == \
            leave_approval.APPROVAL_INTENT


class TestConfirmationWordRecognition:
    @pytest.mark.parametrize("reply", ["yes", "Yes please", "confirm", "go ahead",
                                       "yep", "ok", "approve it"])
    def test_affirmatives(self, reply):
        assert leave_approval._is_affirmative(reply)

    @pytest.mark.parametrize("reply", ["no", "cancel", "not yet", "hold off",
                                       "don't approve it", "never mind"])
    def test_declines(self, reply):
        assert not leave_approval._is_affirmative(reply)
        assert leave_approval._is_declining(reply)

    @pytest.mark.parametrize("reply", ["thanks", "sounds good", "great", "hmm"])
    def test_politeness_is_not_a_confirmation(self, reply):
        """An approval is not something to infer from agreeable noise."""
        assert not leave_approval._is_affirmative(reply)

    @pytest.mark.parametrize("reply", [
        "okay but first, what's his leave balance?",
        "yes I saw that, now show me Priya's request",
        "sure, what about the other one",
    ])
    def test_a_yes_word_opening_a_different_ask_is_not_a_confirmation(self, reply):
        """A bare yes-word only counts when it is the whole message —
        otherwise "okay but first..." would approve a request while
        answering a different question."""
        assert not leave_approval._is_affirmative(reply)

    def test_a_negated_approval_is_a_decline(self):
        assert not leave_approval._is_affirmative("no, don't approve it")

    @pytest.mark.parametrize("reply", [
        "go ahead and approve Priya's leave request",
        "proceed with Priya's request",
        "confirm approving geo4's leave",
        "go ahead and approve request 61",
        "proceed with request 61",
        "do it for Priya's leave request",
        "approve employee 3736",
        "go ahead, approve #61",
        "actually approve John's leave",
    ])
    def test_a_confirm_word_plus_a_named_target_is_not_a_confirmation(self, reply):
        """The instruction word says "act"; the target says WHAT to act on.
        When a message carries both, the target is the part that decides -
        so this is a re-aim to be re-read, not a yes to the card on screen.
        Treating it as a yes approved the previously armed request while
        ignoring the person actually named."""
        assert leave_approval.names_a_target(reply)
        assert not leave_approval._is_affirmative(reply)

    @pytest.mark.parametrize("reply", [
        "yes", "confirm", "go ahead", "proceed", "approve it",
        "approve this", "approve that", "approve this request",
        "yes, go ahead", "ok confirm", "yep, approve it",
    ])
    def test_a_confirmation_naming_nothing_new_still_confirms(self, reply):
        """Guard against over-blocking: a pronoun object ("approve it",
        "approve this request") names nothing new and IS a confirmation of
        what is on screen."""
        assert not leave_approval.names_a_target(reply)
        assert leave_approval._is_affirmative(reply)

    @pytest.mark.parametrize("reply", [
        "did you approve it already?",
        "should I approve it?",
        "what happens if I approve it",
    ])
    def test_a_question_is_never_a_confirmation(self, reply):
        """"did you approve it already?" contains the instruction wording but
        asks for nothing — executing on it is silent execution arrived at
        from a message that gave no instruction."""
        assert not leave_approval._is_affirmative(reply)


# -- Classifier + graph wiring ----------------------------------------------

class TestClassifierShortcut:
    @pytest.mark.parametrize("query", [
        "approve john's leave request", "approve request 58", "approve it",
        "please approve b geo's leave", "reject priya's leave request",
        "deny that request",
    ])
    def test_instructions_are_recognised(self, query):
        import services.hr_graph as hr_graph
        assert hr_graph._is_leave_approval_query(query)

    @pytest.mark.parametrize("query", [
        "is my leave approved", "was my leave request approved",
        "what is the leave approval process", "who approves leave requests",
        "how long does leave approval take", "show john's leave request",
    ])
    def test_questions_are_not_instructions(self, query):
        import services.hr_graph as hr_graph
        assert not hr_graph._is_leave_approval_query(query)

    @pytest.mark.parametrize("query", [
        "reject this candidate", "approve the expense claim",
        "decline the applicant's offer letter",
    ])
    def test_the_same_verbs_aimed_elsewhere_are_left_alone(self, query):
        """Answering a recruitment question with "I can't reject leave
        requests" is worse than letting the classifier read it properly."""
        import services.hr_graph as hr_graph
        assert not hr_graph._is_leave_approval_query(query)


class TestUnexpectedErrorDuringExecution:
    """The card is cleared BEFORE the erp-api write, so an exception from
    that call costs the manager the card as well as the answer. It must come
    back as an honest "outcome unknown", never as a dead stream."""

    async def _arm_and_confirm(self, monkeypatch, exc):
        writer, approve_calls = await arm_confirmation(monkeypatch)
        monkeypatch.setattr(leave_approval.erp_client, "approve_leave_request",
                            _raiser(exc))
        writer = FakeWriter()
        await leave_approval_node(base_state("yes"), writer)
        return writer

    @pytest.mark.asyncio
    async def test_an_unexpected_exception_is_answered_not_propagated(
            self, monkeypatch, _audit_rows):
        """The live failure: approve_leave_request passed a kwarg _request
        did not accept, so every confirmation raised TypeError and reached
        the manager as a blank blocked frame."""
        writer = await self._arm_and_confirm(
            monkeypatch, TypeError("_request() got an unexpected keyword argument"))

        answer = writer.answer()
        assert "can't tell whether it went through" in answer
        assert "HR portal" in answer

    @pytest.mark.asyncio
    async def test_the_attempt_is_audited_as_outcome_unknown(
            self, monkeypatch, _audit_rows):
        """An approval erp-api may or may not have applied must leave a row
        that asserts neither."""
        await self._arm_and_confirm(monkeypatch, TypeError("boom"))

        assert len(_audit_rows) == 1
        row = _audit_rows[0]
        assert row["executed"] is False
        assert "outcome unknown" in row["erp_message"]
        assert row["resource_id"] == 58

    @pytest.mark.asyncio
    async def test_the_card_is_not_left_armed_for_a_second_yes(
            self, monkeypatch, _fake_action_store):
        """Cleared before the write by design - a crash must not resurrect
        it, or a follow-up "yes" re-runs an approval that may already have
        applied."""
        await self._arm_and_confirm(monkeypatch, TypeError("boom"))
        assert _fake_action_store == {}


class TestPendingCardFastPath:
    """classify_node must route a reply to an armed manager card by READING
    the armed state, not by asking the LLM to infer it from history.

    resolve_pending_approval_intent and resolve_pending_selection_intent both
    document themselves as "classify_node's single entry point into this
    feature's state" - and for a while neither was called from there at all,
    so a bare "yes" landed on the armed approval card only when the general
    classifier happened to guess right.

    Every test here turns on whether the LLM classifier was reached. That is
    the property worth pinning: a turn that confirms a state change must be
    decided by the stored card, and a turn that does NOT match one must still
    get a real answer rather than being swallowed by this fast-path.
    """

    @pytest.fixture
    def classify(self, monkeypatch):
        import services.classify_node as classify_node

        # Every mid-flow state checked BEFORE the manager-card fast-path,
        # emptied so this exercises one branch rather than Redis.
        monkeypatch.setattr(classify_node.leave_disambiguation_state,
                            "get_candidates", lambda *a, **k: None)
        monkeypatch.setattr(classify_node.leave_history_clarify_state,
                            "get_state", lambda *a, **k: None)
        monkeypatch.setattr(classify_node.leave_type_clarify_state,
                            "get_state", lambda *a, **k: None)
        monkeypatch.setattr(classify_node.leave_cancel_state,
                            "get_state", lambda *a, **k: None)
        monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda *a, **k: {})
        monkeypatch.setattr(classify_node.leave_slot_service, "get_slots", lambda *a, **k: {})

        # Records rather than raises: classify_node wraps this call in its own
        # try/except, so an exception here would be swallowed and prove
        # nothing either way.
        reached = []

        async def _classifier(*a, **k):
            reached.append(True)
            return "general_hr", None, False

        monkeypatch.setattr(classify_node, "classify_intent_structured", _classifier)

        async def _moderate(*a, **k):
            return {}

        monkeypatch.setattr(classify_node, "_check_moderation", _moderate)

        async def _run(query, is_manager=True):
            writer = FakeWriter()
            result = await classify_node.classify_node(
                {"query": query, "context": [], "intent": "general", "usage_events": [],
                 "company_id": 7, "conversation_id": "conv-1", "is_manager": is_manager},
                writer,
            )
            return result, writer, reached

        return _run

    @pytest.mark.asyncio
    async def test_a_bare_yes_routes_to_the_approval_node(self, classify, _fake_action_store):
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        result, writer, reached = await classify("yes")

        assert result["intent"] == leave_approval.APPROVAL_INTENT
        assert writer.of_type("intent")[0]["intent"] == leave_approval.APPROVAL_INTENT
        assert not reached, "the armed card should have settled this without the LLM"

    @pytest.mark.asyncio
    async def test_a_bare_no_routes_there_too(self, classify, _fake_action_store):
        """A decline has to reach the node that CLEARS the card - left to the
        classifier it becomes a generic answer and the card stays armed."""
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        result, _, reached = await classify("no")
        assert result["intent"] == leave_approval.APPROVAL_INTENT
        assert not reached

    @pytest.mark.asyncio
    async def test_an_employee_selection_reply_routes_to_the_report_node(
            self, classify, _fake_report_store):
        _fake_report_store[("7", "conv-1")] = {
            "step": "awaiting_employee_selection",
            "intent": "manager_leave_request_lookup",
            "candidates": [{"employee_id": 3735, "employee_name": "Ayush Jio",
                            "employee_number": "geo3"}],
        }
        result, _, reached = await classify("geo3")
        assert result["intent"] == "manager_leave_request_lookup"
        assert not reached

    @pytest.mark.asyncio
    async def test_a_non_manager_never_takes_this_path(self, classify, _fake_action_store):
        """Same permission ordering as the approval shortcut: a non-manager
        falls through to normal classification, never routed by an armed
        card."""
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        result, _, reached = await classify("yes", is_manager=False)
        assert result["intent"] != leave_approval.APPROVAL_INTENT
        assert reached

    @pytest.mark.asyncio
    async def test_nothing_armed_falls_through_to_normal_classification(self, classify):
        result, _, reached = await classify("yes")
        assert result["intent"] != leave_approval.APPROVAL_INTENT
        assert reached

    @pytest.mark.asyncio
    async def test_an_unrelated_question_is_left_to_the_classifier(
            self, classify, _fake_action_store):
        """The card keeps waiting; the question gets a real answer."""
        _fake_action_store[("7", "conv-1")] = {"step": "awaiting_confirmation",
                                               "leave_request_id": 58}
        result, _, reached = await classify("what is the sick leave policy")
        assert result["intent"] != leave_approval.APPROVAL_INTENT
        assert reached


class TestGraphWiring:
    def test_the_intent_routes_to_its_own_node(self):
        import services.hr_graph as hr_graph
        assert hr_graph._route_after_classify(
            {"intent": "manager_leave_approval", "is_hr": True}) == "leave_approval_node"

    def test_the_node_is_registered(self):
        import services.hr_graph as hr_graph
        assert "leave_approval_node" in set(hr_graph.hr_graph.get_graph().nodes)

    def test_the_manager_gate_still_runs_first(self):
        import services.hr_graph as hr_graph
        edges = [(e.source, e.target) for e in hr_graph.hr_graph.get_graph().edges]
        assert ("__start__", "manager_gate_node") in edges
        # Reaches classification via the ownership guard now — both
        # pre-classification checks are chained rather than either/or. The
        # gate still runs first, which is what this test is about.
        assert ("manager_gate_node", "ownership_guard_node") in edges
        # The safety step sits between the guard and classification (Phase 3, 29 Oct).
        assert ("ownership_guard_node", "safety_node") in edges
        assert ("safety_node", "classify_node") in edges

    def test_the_intent_is_a_valid_classifier_label(self):
        import services.hr_graph as hr_graph
        assert "manager_leave_approval" in hr_graph._VALID_INTENT_LABELS

    def test_the_intent_is_excluded_from_the_query_cache(self):
        """The only state-CHANGING intent — a replayed card would arm
        nothing, and a replayed "Approved" would be a lie."""
        import main
        assert "manager_leave_approval" in main._STATEFUL_QUERY_INTENTS


# -- erp_client -------------------------------------------------------------

class TestErpClientApprove:
    """Driven through the REAL _request, against a stubbed HTTP layer.

    These tests used to monkeypatch _request itself with a hand-written
    signature — which silently invented the very parameter under test. The
    real _request had no allow_404_body at all, so every live approval died
    with TypeError the moment a manager said "yes", and the suite stayed
    green because the stub accepted the kwarg the real function rejected.
    Stubbing the transport instead is what makes the call contract real.
    """

    @pytest.fixture(autouse=True)
    def _erp(self, monkeypatch):
        monkeypatch.setattr(erp_client, "ERP_API_URL", "https://erp.test")
        monkeypatch.setattr(erp_client, "_log_call_background", lambda **kw: None)

    def _respond(self, monkeypatch, status_code, json_body):
        seen = {}

        async def _http_request(method, url, **kwargs):
            seen.update(method=method, url=url)
            return httpx.Response(status_code=status_code, json=json_body,
                                  request=httpx.Request(method, url))

        monkeypatch.setattr(erp_client._http, "request", _http_request)
        return seen

    @pytest.mark.asyncio
    async def test_posts_to_the_request_scoped_route(self, monkeypatch):
        seen = self._respond(monkeypatch, 200, APPROVED_BODY)

        result = await erp_client.approve_leave_request("tok", 58, company_id=7)

        assert seen["method"] == "POST"
        assert seen["url"] == "https://erp.test/api/v1/ai/leave/requests/58/approve"
        assert result["body"]["success"] is True

    @pytest.mark.asyncio
    async def test_the_out_of_team_body_comes_back_as_data_not_an_exception(self, monkeypatch):
        self._respond(monkeypatch, 400, OUT_OF_TEAM_BODY)
        result = await erp_client.approve_leave_request("tok", 58)
        assert result["body"]["success"] is False

    @pytest.mark.asyncio
    async def test_a_404_on_this_id_bearing_route_is_a_body_not_an_outage(self, monkeypatch):
        """A 404 here is erp-api answering about ONE request id - no such
        pending request, or not the caller's - which _execute_approval
        surfaces. Raising ErpApiUnavailable instead would tell the manager
        the HR system is down when it answered them perfectly well."""
        self._respond(monkeypatch, 404, OUT_OF_TEAM_BODY)
        result = await erp_client.approve_leave_request("tok", 58)
        assert result["http_status"] == 404
        assert result["body"]["success"] is False

    @pytest.mark.asyncio
    async def test_a_422_business_rule_is_a_body_not_an_outage(self, monkeypatch):
        """The quota/monthly-max/attendance-lock refusals come back 422 from
        this controller. Raising instead told the manager the HR system was
        unreachable and hid the rule they had to act on."""
        self._respond(monkeypatch, 422, QUOTA_EXCEEDED_BODY)
        result = await erp_client.approve_leave_request("tok", 58)
        assert result["http_status"] == 422
        assert result["body"]["message"] == QUOTA_EXCEEDED_MESSAGE

    @pytest.mark.asyncio
    async def test_a_422_on_a_route_that_did_not_opt_in_still_raises(self, monkeypatch):
        """The opt-in is per route. A 422 from a route that never asked for
        it keeps meaning erp-api could not serve the call."""
        self._respond(monkeypatch, 422, {"success": False})
        with pytest.raises(ErpApiUnavailable):
            await erp_client.ping("tok")

    @pytest.mark.asyncio
    async def test_a_500_still_raises(self, monkeypatch):
        """The opt-in widens 404 only - a real outage must not arrive as a
        business answer."""
        self._respond(monkeypatch, 500, {"success": False})
        with pytest.raises(ErpApiUnavailable):
            await erp_client.approve_leave_request("tok", 58)

    @pytest.mark.asyncio
    async def test_a_404_on_a_route_that_did_not_opt_in_still_raises(self, monkeypatch):
        """The no-ID AI routes keep the old meaning: a 404 there is the route
        being unreachable, and swallowing it would report a deploy gap as an
        answer."""
        self._respond(monkeypatch, 404, {"success": False})
        with pytest.raises(ErpApiUnavailable):
            await erp_client.ping("tok")


class TestRejectionDisabled:
    """The shipped default: approve is the only action the assistant offers.

    QA raised the reject option as a defect against the user story. The reject
    implementation is real and kept (see TestRejection), but gated off, so
    these cover what a manager actually gets today.
    """

    @pytest.fixture(autouse=True)
    def _rejection_disabled(self, monkeypatch):
        monkeypatch.setattr(leave_approval, "LEAVE_REJECTION_ENABLED", False)

    @pytest.mark.asyncio
    async def test_a_reject_instruction_is_declined_and_points_somewhere_real(
            self, monkeypatch, _fake_action_store):
        mock_extraction(monkeypatch, action="reject", employee_id=3735)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])

        writer = FakeWriter()
        result = await leave_approval_node(base_state("reject B Geo's leave request"), writer)

        answer = result["response_text"]
        assert answer == leave_approval.REJECTION_UNAVAILABLE_MESSAGE
        # Named a destination rather than dead-ending.
        assert "Leave Approvals" in answer
        assert approve_calls == [], "a declined rejection must not approve anything"

    @pytest.mark.asyncio
    async def test_no_confirmation_card_is_armed_for_a_declined_rejection(
            self, monkeypatch, _fake_action_store):
        """A card left armed is how a later bare 'yes' acts on something the
        manager was just told could not be done here."""
        mock_extraction(monkeypatch, action="reject", employee_id=3735)
        patch_erp(monkeypatch, pending=[pending_response()])

        writer = FakeWriter()
        await leave_approval_node(base_state("reject B Geo's leave request"), writer)

        assert writer.of_type("leave_approval_confirmation") == []
        assert _fake_action_store == {}

    @pytest.mark.asyncio
    async def test_a_reject_re_aim_clears_an_armed_approve_card(
            self, monkeypatch, _fake_action_store):
        """The dangerous ordering: an approve card is already armed and the
        manager says "reject it instead". Declining must still CLEAR the armed
        approve, or a following "yes" approves what they tried to reject."""
        await arm_confirmation(monkeypatch)
        assert _fake_action_store, "precondition: an approve card is armed"

        mock_extraction(monkeypatch, action="reject", employee_id=3735)
        approve_calls = patch_erp(monkeypatch, pending=[pending_response()])

        writer = FakeWriter()
        await leave_approval_node(base_state("actually reject it instead"), writer)

        assert _fake_action_store == {}, "the armed approve card survived a declined rejection"
        assert approve_calls == []

    @pytest.mark.asyncio
    async def test_approval_is_unaffected_by_the_gate(self, monkeypatch, _fake_action_store):
        """The gate must not touch the action that IS available."""
        mock_extraction(monkeypatch, action="approve", employee_id=3735)
        patch_erp(monkeypatch, pending=[pending_response()])

        writer = FakeWriter()
        await leave_approval_node(base_state("approve B Geo's leave request"), writer)

        assert writer.of_type("leave_approval_confirmation"), "approve must still arm its card"
