"""
Tests for manager attendance-regularization review and approval:
  - services/erp_client.py::get_pending_regularizations (GET
    /api/v1/ai/regularizations) and ::approve_regularization (POST
    /api/v1/ai/regularization/approve)
  - services/regularisation_approval.py::regularisation_approval_node
    (manager gate, team scope, the view, target resolution, the confirmation
    step, execution, refusals)
  - the classifier/graph wiring that gets a manager's instruction here, and
    the kind tag that keeps it from landing in leave_approval_node instead

regularisation_approval_node is exercised directly with a fake StreamWriter
and a mocked erp_client, the same pattern test_leave_approval.py uses.

The response shapes below are the payloads from the story's own real calls
(regularization 54/56, employees "Ayush Jio" / "A Emp"), not invented ones.

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.audit_log_service as audit_log_service
import services.classify_node as classify_node
import services.erp_client as erp_client
import services.leave_approval as leave_approval
import services.regularisation_approval as regularisation_approval
from services.erp_client import ErpApiTimeout, ErpApiUnavailable
from services.regularisation_approval import (
    BULK_MESSAGE,
    NOT_A_MANAGER_MESSAGE,
    NOT_IN_YOUR_TEAM_MESSAGE,
    regularisation_approval_node,
)


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, intent=None, is_manager=True) -> dict:
    return {
        "query": query,
        "intent": intent or regularisation_approval.APPROVAL_INTENT,
        "usage_events": [],
        "bearer_token": "caller-token",
        "company_id": 26,
        "conversation_id": "conv-reg-1",
        "is_manager_jwt": True,
        "is_manager": is_manager,
    }


# The story's own payloads.
REG_54 = {
    "regularization_id": 54, "employee_id": 3735, "employee_number": "geo3",
    "employee_name": "Ayush Jio", "apply_date": "2026-09-08",
    "from_time": "09:00:00", "to_time": "18:30:00",
    "reason": "When I select Apply Regularization and then enter yesterday's date, "
              "the system is unable to recognize the selected date.",
    "status": 0, "status_name": "pending",
}
REG_18 = {
    "regularization_id": 18, "employee_id": 3735, "employee_number": "geo3",
    "employee_name": "Ayush Jio", "apply_date": "2026-08-14",
    "from_time": "10:05:00", "to_time": "19:00:00",
    "reason": "missed punch issue", "status": 0, "status_name": "pending",
}
REG_56 = {
    "regularization_id": 56, "employee_id": 3759, "employee_number": "geo6",
    "employee_name": "A Emp", "apply_date": "2026-09-03",
    "from_time": "10:24:00", "to_time": "16:15:00",
    "reason": "punch missing", "status": 0, "status_name": "pending",
}

TEAM_MEMBERS = [
    {"employee_id": 3735, "employee_number": "geo3", "employee_name": "Ayush Jio"},
    {"employee_id": 3759, "employee_number": "geo6", "employee_name": "A Emp"},
]


def list_body(rows):
    return {
        "http_status": 200,
        "body": {
            "success": True,
            "data": {
                "total_pending_regularizations": len(rows),
                "regularizations": rows,
            },
            "message": "success",
        },
    }


def approve_body(reg_id=54, employee_id=3735):
    return {
        "http_status": 200,
        "body": {
            "success": True,
            "data": {
                "regularization_id": reg_id, "employee_id": employee_id,
                "status": 1, "status_name": "approved",
            },
            "message": "Regularization request approved successfully.",
        },
    }


# -- 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. Shared by both approval features, exactly
    like the real one."""
    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

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


@pytest.fixture(autouse=True)
def _no_audit_db(monkeypatch):
    """The audit write is a database call; capture the rows instead."""
    rows = []
    monkeypatch.setattr(audit_log_service, "_write", lambda **fields: rows.append(fields))
    return rows


@pytest.fixture
def erp(monkeypatch):
    """Records every erp-api call the node makes and replays canned answers."""
    class Fake:
        def __init__(self):
            self.list_calls = []
            self.approve_calls = []
            self.member_calls = []
            self.list_result = list_body([REG_54, REG_18, REG_56])
            self.approve_result = approve_body()
            self.members_result = {
                "http_status": 200,
                "body": {"success": True, "data": {"members": TEAM_MEMBERS}},
            }
            self.list_raises = None
            self.approve_raises = None

        async def get_pending_regularizations(self, token, employee_id=None,
                                              company_id=None, conversation_id=None):
            self.list_calls.append({"employee_id": employee_id})
            if self.list_raises:
                raise self.list_raises
            return self.list_result

        async def approve_regularization(self, token, regularization_id,
                                         company_id=None, conversation_id=None):
            self.approve_calls.append(regularization_id)
            if self.approve_raises:
                raise self.approve_raises
            return self.approve_result

        async def get_team_members(self, token, company_id=None, conversation_id=None):
            self.member_calls.append(True)
            return self.members_result

    fake = Fake()
    monkeypatch.setattr(erp_client, "get_pending_regularizations", fake.get_pending_regularizations)
    monkeypatch.setattr(erp_client, "approve_regularization", fake.approve_regularization)
    monkeypatch.setattr(erp_client, "get_team_members", fake.get_team_members)
    return fake


async def run(query, erp, intent=None, is_manager=True, state_extra=None):
    writer = FakeWriter()
    state = base_state(query, intent=intent, is_manager=is_manager)
    if state_extra:
        state.update(state_extra)
    await regularisation_approval_node(state, writer)
    return writer


# -- erp_client contract -----------------------------------------------------

class TestErpClientContract:
    async def test_list_asks_for_the_team_pending_queue(self, monkeypatch):
        seen = {}

        async def fake_request(method, path, token, **kwargs):
            seen.update({"method": method, "path": path, **kwargs})
            return {"http_status": 200, "body": {"success": True, "data": {}}}

        monkeypatch.setattr(erp_client, "_request", fake_request)
        await erp_client.get_pending_regularizations("tok", company_id=26)

        assert seen["method"] == "GET"
        assert seen["path"] == "/api/v1/ai/regularizations"
        # Since HA-697 the bare route is the caller's OWN requests. type=all is
        # erp-api's team switch (still role-gated there) and status=pending
        # keeps approved/cancelled rows out of an approval queue.
        assert seen["params"] == {"type": "all", "status": "pending"}

    async def test_employee_id_is_not_sent_since_erp_api_ignores_it(self, monkeypatch):
        seen = {}

        async def fake_request(method, path, token, **kwargs):
            seen.update(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": {}}}

        monkeypatch.setattr(erp_client, "_request", fake_request)
        await erp_client.get_pending_regularizations("tok", employee_id="3759")

        # type=all is always the whole team on erp-api's side; narrowing to
        # one report happens over the returned rows (_same_employee).
        assert seen["params"] == {"type": "all", "status": "pending"}

    async def test_approve_puts_the_id_in_the_body(self, monkeypatch):
        seen = {}

        async def fake_request(method, path, token, **kwargs):
            seen.update({"method": method, "path": path, **kwargs})
            return {"http_status": 200, "body": {"success": True, "data": {}}}

        monkeypatch.setattr(erp_client, "_request", fake_request)
        await erp_client.approve_regularization("tok", "55", company_id=26)

        assert seen["method"] == "POST"
        # The id travels in the BODY on this route, unlike the leave approve
        # route which takes it as a path segment.
        assert seen["path"] == "/api/v1/ai/regularization/approve"
        # browser_id is required by erp-api's validator even though nothing
        # downstream reads it. Without it every approval was refused with
        # "The browser id field is required." and nothing could be approved.
        assert seen["json_body"] == {"regularization_id": 55,
                                     "browser_id": "helixta-ai-assistant"}
        # A refusal here is erp-api answering, not failing.
        assert seen["allow_business_error_body"] is True
        assert seen["allow_404_body"] is True
        # This controller answers its own rules ("Attendance is locked for
        # this date. Contact HR.") with 422, so that body is an answer too.
        assert seen["allow_422_body"] is True

    async def test_business_error_body_is_returned_not_raised(self, monkeypatch):
        """erp-api's 400 refusal must reach the node as data - otherwise the
        'erp-api refused' branch is unreachable and a manager is told the HR
        system is down when it has in fact declined them."""
        request = httpx.Request("POST", "http://erp/api/v1/ai/regularization/approve")
        response = httpx.Response(
            400, json={"success": False, "message": "Pending regularization request "
                                                    "was not found in your team."},
            request=request,
        )

        async def fake_request(*args, **kwargs):
            return response

        # erp_client holds ONE shared client (_http) rather than opening one
        # per call, so that is what a transport-level stub has to replace.
        monkeypatch.setattr(erp_client._http, "request", fake_request)
        monkeypatch.setattr(erp_client, "_log_call_background", lambda **kwargs: None)
        result = await erp_client.approve_regularization("tok", 55)

        assert result["http_status"] == 400
        assert result["body"]["success"] is False


# -- Manager gate ------------------------------------------------------------

class TestManagerGate:
    async def test_non_manager_is_refused_and_nothing_is_fetched(self, erp):
        writer = await run("approve A Emp's regularization request", erp, is_manager=False)

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

    async def test_unknown_manager_status_does_not_pass_the_gate(self, erp):
        writer = await run("show pending regularization requests", erp,
                           is_manager=regularisation_approval.MANAGER_UNKNOWN)

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

    async def test_erp_403_on_the_list_is_a_role_refusal(self, erp):
        """A caller who manages nobody is refused by erp-api rather than
        shown an empty list - and a role change between the gate and the call
        lands here too."""
        erp.list_result = {"http_status": 403, "body": {"success": False}}
        writer = await run("show pending regularization requests", erp,
                           intent=regularisation_approval.VIEW_INTENT)

        # erp-api's own sentence when it sends one (see
        # test_regularisation_team_view_refusal.py); this 403 carries none, so
        # the same sentence comes from the constant.
        assert writer.answer() == regularisation_approval.VIEW_NOT_ALLOWED_MESSAGE
        assert erp.approve_calls == []


# -- View --------------------------------------------------------------------

class TestView:
    async def test_lists_the_team_and_caps_the_reply(self, erp):
        erp.list_result = list_body([REG_54, REG_18, REG_56, dict(REG_56, regularization_id=99)])
        writer = await run("show pending regularization requests", erp,
                           intent=regularisation_approval.VIEW_INTENT)

        answer = writer.answer()
        assert "pending regularization requests" in answer
        assert "1 more pending request(s) not shown" in answer
        # The event carries the FULL list even though the sentence is capped.
        event = writer.of_type("team_pending_regularization")[0]
        assert len(event["data"]["regularizations"]) == 4
        assert event["data"]["has_more"] is True
        assert erp.approve_calls == []

    async def test_empty_team_list(self, erp):
        erp.list_result = list_body([])
        writer = await run("any pending regularization requests?", erp,
                           intent=regularisation_approval.VIEW_INTENT)

        assert "no pending regularization requests for your team" in writer.answer()

    async def test_named_employee_narrows_by_id(self, erp):
        erp.list_result = list_body([REG_56])
        writer = await run("show regularization requests for A Emp", erp,
                           intent=regularisation_approval.VIEW_INTENT)

        # Resolved from the pending rows themselves, then narrowed by id -
        # never by a name sent to erp-api. The roster call is a FALLBACK now,
        # reached only when nobody with a pending request matches, because
        # erp-api's roster route answers 404 on the deployed instance and a
        # by-name lookup must not depend on it.
        assert erp.member_calls == []
        # One unnarrowed read, then the narrowing applied locally - the rows
        # are already in hand and already scoped to this manager's team, so
        # re-asking erp-api for a subset of what it just sent would be a
        # second round trip for nothing. An employee_id given OUTRIGHT still
        # goes to erp-api as its own parameter (see the explicit-id test).
        assert erp.list_calls == [{"employee_id": None}]
        assert "A Emp's pending regularization requests" in writer.answer()

    async def test_name_outside_the_team_gets_the_not_found_answer(self, erp):
        """The scope promise: somebody another manager owns is answered with
        the SAME sentence as a request that is no longer pending, so the
        reply cannot be used to probe another team's roster."""
        writer = await run("show regularization requests for Priya Sharma", erp,
                           intent=regularisation_approval.VIEW_INTENT)

        assert writer.answer() == NOT_IN_YOUR_TEAM_MESSAGE
        # The team list is read first (that is where names are resolved), but
        # it is never re-read narrowed to somebody who did not resolve.
        assert erp.list_calls == [{"employee_id": None}]
        assert all(c["employee_id"] is None for c in erp.list_calls)

    async def test_employee_with_no_pending_requests(self, erp):
        erp.list_result = list_body([])
        writer = await run("any regularization requests from A Emp?", erp,
                           intent=regularisation_approval.VIEW_INTENT)

        assert "A Emp has no pending regularization requests" in writer.answer()


# -- The confirmation step (FR-08.3) -----------------------------------------

class TestConfirmationStep:
    async def test_approval_instruction_shows_a_card_and_approves_nothing(self, erp, _fake_action_store):
        erp.list_result = list_body([REG_56])
        writer = await run("approve A Emp's regularization request", erp)

        # THE property this module exists to guarantee.
        assert erp.approve_calls == []

        card = writer.of_type("regularisation_approval_confirmation")[0]["data"]
        assert card["regularization_id"] == 56
        assert card["employee_name"] == "A Emp"
        assert card["request_type"] == "Regularization"
        assert card["time_span"] == "10:24 to 16:15"
        answer = writer.answer()
        # The design's "Approve this request?" card.
        assert answer.startswith("Approve this request?")
        assert "- Date: 03-Sep-2026 – 03-Sep-2026" in answer
        assert "- In-time: 10:24 AM" in answer and "- Out-time: 4:15 PM" in answer

        stored = _fake_action_store[("26", "conv-reg-1")]
        assert stored["step"] == "awaiting_confirmation"
        assert stored["kind"] == "regularization"
        assert stored["regularization_id"] == 56

    async def test_yes_on_the_next_turn_executes(self, erp, _fake_action_store, _no_audit_db):
        erp.list_result = list_body([REG_56])
        erp.approve_result = approve_body(reg_id=56, employee_id=3759)
        await run("approve A Emp's regularization request", erp)
        writer = await run("yes", erp)

        assert erp.approve_calls == [56]
        assert "Approved" in writer.answer()
        assert "A Emp" in writer.answer()
        assert "approved" in writer.answer()
        # The card is gone, so a second "yes" cannot re-approve.
        assert ("26", "conv-reg-1") not in _fake_action_store

        assert len(_no_audit_db) == 1
        row = _no_audit_db[0]
        assert row["resource_type"] == "regularization_request"
        assert row["resource_id"] == 56
        assert row["executed"] is True
        assert row["source"] == "AI Assistant"
        assert row["rule_version"]
        assert "explicit in-chat confirmation" in row["decision_basis"]

    async def test_no_leaves_it_pending(self, erp, _fake_action_store):
        erp.list_result = list_body([REG_56])
        await run("approve A Emp's regularization request", erp)
        writer = await run("no", erp)

        assert erp.approve_calls == []
        assert "left A Emp's regularization request pending" in writer.answer()
        assert ("26", "conv-reg-1") not in _fake_action_store

    async def test_a_second_yes_after_execution_approves_nothing_again(self, erp):
        erp.list_result = list_body([REG_56])
        erp.approve_result = approve_body(reg_id=56, employee_id=3759)
        await run("approve A Emp's regularization request", erp)
        await run("yes", erp)
        erp.list_result = list_body([])
        await run("yes", erp)

        assert erp.approve_calls == [56]

    async def test_card_is_not_shown_when_it_cannot_be_stored(self, erp, monkeypatch):
        """Without stored state there is nothing for a "yes" to resolve
        against, and re-deriving it from the confirming message is what
        FR-08.3 forbids."""
        import services.leave_slot_service as leave_slot_service
        monkeypatch.setattr(leave_slot_service, "set_manager_action",
                            lambda *a, **k: False)
        erp.list_result = list_body([REG_56])
        writer = await run("approve A Emp's regularization request", erp)

        assert erp.approve_calls == []
        assert writer.done()["intent"] == "regularisation_approval_unavailable"
        assert "HR portal" in writer.answer()
        assert writer.of_type("regularisation_approval_confirmation") == []


# -- Target resolution -------------------------------------------------------

class TestTargetResolution:
    async def test_explicit_request_id(self, erp):
        writer = await run("approve regularization 18", erp)

        card = writer.of_type("regularisation_approval_confirmation")[0]["data"]
        assert card["regularization_id"] == 18
        assert erp.approve_calls == []

    async def test_unknown_id_gets_the_not_found_answer(self, erp):
        """An id that is real to the manager but absent from THEIR pending
        list is answered exactly like an out-of-team one."""
        writer = await run("approve regularization 999", erp)

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

    async def test_ambiguous_instruction_asks_instead_of_guessing(self, erp):
        writer = await run("approve the regularization request", erp)

        assert erp.approve_calls == []
        assert writer.of_type("regularisation_approval_confirmation") == []
        answer = writer.answer()
        assert "more than one pending regularization request" in answer
        assert "haven't changed anything" in answer

    async def test_single_candidate_needs_no_disambiguation(self, erp):
        erp.list_result = list_body([REG_56])
        writer = await run("approve the regularization request", erp)

        card = writer.of_type("regularisation_approval_confirmation")[0]["data"]
        assert card["regularization_id"] == 56
        # Still a card, never a write.
        assert erp.approve_calls == []

    async def test_bulk_is_refused_by_name(self, erp):
        writer = await run("approve all the pending regularization requests", erp)

        assert writer.answer() == BULK_MESSAGE
        assert erp.approve_calls == []
        assert erp.list_calls == []

    async def test_rejection_arms_a_reason_card_and_writes_nothing(self, erp):
        """erp-api has a reject route now (2026-10-05): the instruction arms a
        card that waits for the REASON - full flow in
        test_regularisation_reject_and_cancel.py."""
        erp.list_result = list_body([REG_56])
        writer = await run("reject A Emp's regularization request", erp)

        card = writer.of_type("regularisation_approval_confirmation")[0]["data"]
        assert card["action"] == "reject" and card["regularization_id"] == 56
        assert writer.answer().startswith("Reject this request?")
        assert "Rejection reason:" in writer.answer()
        assert erp.approve_calls == []


# -- erp-api failures --------------------------------------------------------

class TestErpFailures:
    async def test_refusal_is_surfaced_verbatim(self, erp, _no_audit_db):
        erp.list_result = list_body([REG_56])
        await run("approve A Emp's regularization request", erp)
        erp.approve_result = {
            "http_status": 400,
            "body": {"success": False,
                     "message": "Pending regularization request was not found in your team."},
        }
        writer = await run("yes", erp)

        assert "was not found in your team" in writer.answer()
        assert "Nothing has been changed" in writer.answer()
        assert writer.done()["intent"] == "regularisation_approval_failed"
        # A refused approval is still an auditable action.
        assert len(_no_audit_db) == 1
        assert _no_audit_db[0]["executed"] is False
        assert _no_audit_db[0]["erp_status"] == 400

    async def test_a_422_rule_refusal_is_surfaced_verbatim(self, erp, _no_audit_db):
        """erp-api answers the rules it enforces inside the approval with 422,
        not 400. Before the client opted that status in it raised, and the
        manager was told the HR system was unreachable."""
        erp.list_result = list_body([REG_56])
        await run("approve A Emp's regularization request", erp)
        erp.approve_result = {
            "http_status": 422,
            "body": {"success": False,
                     "message": "Attendance is locked for this date. Contact HR."},
        }
        writer = await run("yes", erp)

        answer = writer.answer()
        assert "Attendance is locked for this date. Contact HR." in answer
        assert "unable to reach the HR system" not in answer
        assert "Nothing has been changed" in answer
        assert _no_audit_db[0]["executed"] is False
        assert _no_audit_db[0]["erp_status"] == 422

    async def test_a_validator_complaint_is_not_read_back_to_the_manager(self, erp, _no_audit_db):
        """erp-api validates browser_id on this route even though nothing reads
        it. If a field ever goes missing again the manager must be told the
        approval did not happen - not handed the field name, which is a bug in
        this service and nothing they can act on."""
        erp.list_result = list_body([REG_56])
        await run("approve A Emp's regularization request", erp)
        erp.approve_result = {
            "http_status": 422,
            "body": {"success": False, "message": "The browser id field is required."},
        }
        writer = await run("yes", erp)

        answer = writer.answer()
        assert "browser id" not in answer.lower()
        assert "HR portal" in answer
        assert "Nothing has been changed" in answer
        # Still an auditable non-execution, with erp-api's own wording on the row.
        assert _no_audit_db[0]["executed"] is False
        assert _no_audit_db[0]["erp_message"] == "The browser id field is required."

    async def test_timeout_during_execution_reports_an_unknown_outcome(self, erp, _no_audit_db):
        erp.list_result = list_body([REG_56])
        await run("approve A Emp's regularization request", erp)
        erp.approve_raises = ErpApiTimeout("timed out")
        writer = await run("yes", erp)

        answer = writer.answer()
        assert "couldn't reach the HR system in time" in answer
        # Never claims either outcome.
        assert "Approved" not in answer
        assert len(_no_audit_db) == 1
        assert _no_audit_db[0]["executed"] is False
        assert "outcome unknown" in _no_audit_db[0]["erp_message"]

    async def test_unexpected_error_never_escapes_the_node(self, erp, _no_audit_db):
        erp.list_result = list_body([REG_56])
        await run("approve A Emp's regularization request", erp)
        erp.approve_raises = TypeError("unexpected kwarg")
        writer = await run("yes", erp)

        assert "can't tell whether it went through" in writer.answer()
        assert writer.done()["intent"] == "regularisation_approval_failed"
        assert _no_audit_db[0]["executed"] is False

    @pytest.mark.parametrize("error", [ErpApiTimeout("timed out"), ErpApiUnavailable("down")])
    async def test_list_failure_offers_retry_or_the_approvals_page(self, erp, error):
        """Design: "Couldn't load pending requests" - Try again / Open Approvals page."""
        erp.list_raises = error
        writer = await run("show pending regularization requests", erp,
                           intent=regularisation_approval.VIEW_INTENT)

        assert writer.answer() == regularisation_approval.LIST_UNAVAILABLE_MESSAGE
        data = writer.done()["data"]
        assert data["retry_available"] is True and data["fallback_page"] == "approvals"


# -- Wiring ------------------------------------------------------------------

class TestWiring:
    @pytest.mark.parametrize("query,expected", [
        ("show pending regularization requests", "manager_regularisation_view"),
        ("show me the team's regularisation requests", "manager_regularisation_view"),
        ("any pending regularization requests?", "manager_regularisation_view"),
        ("approve A Emp's regularization request", "manager_regularisation_approval"),
        ("approve regularization 55", "manager_regularisation_approval"),
        ("reject the regularization request for geo3", "manager_regularisation_approval"),
    ])
    def test_manager_regularisation_queries_route_here(self, query, expected):
        assert classify_node._regularisation_manager_intent(query.lower()) == expected

    @pytest.mark.parametrize("query", [
        # Employee-side flows this must never take over.
        "apply regularization for yesterday",
        "i want to regularize my attendance",
        "show my regularization requests",
        "what is the regularization policy",
        "how do i apply for regularisation",
        # Not a regularization query at all.
        "approve John's leave request",
        "show my team's pending leave requests",
    ])
    def test_other_queries_are_left_alone(self, query):
        assert classify_node._regularisation_manager_intent(query.lower()) is None

    def test_regularisation_approval_never_reads_as_a_leave_approval(self):
        """"approve this regularization request" matches the leave-approval
        action patterns too ("approve this"). The non-leave marker is what
        stops it going looking for a leave request the manager never named."""
        assert classify_node._is_leave_approval_query(
            "approve this regularization request") is False
        assert classify_node._is_leave_approval_query(
            "approve this regularisation request") is False

    def test_node_is_in_the_graph(self):
        import services.hr_graph as hr_graph
        assert "regularisation_approval_node" in hr_graph.hr_graph.get_graph().nodes
        for intent in ("manager_regularisation_view", "manager_regularisation_approval"):
            assert hr_graph._route_after_classify(
                {"intent": intent}) == "regularisation_approval_node"


# -- The two approval features share one card slot ---------------------------

class TestCardKindIsolation:
    """Both features store their pending confirmation under the same
    manager-action key. The kind tag is what keeps a bare "yes" resolving
    against the card that is actually showing."""

    async def test_leave_resolver_ignores_a_regularization_card(self, erp, _fake_action_store):
        erp.list_result = list_body([REG_56])
        await run("approve A Emp's regularization request", erp)

        assert leave_approval.resolve_pending_approval_intent(
            26, "conv-reg-1", "yes") is None
        assert regularisation_approval.resolve_pending_regularisation_intent(
            26, "conv-reg-1", "yes") == regularisation_approval.APPROVAL_INTENT

    def test_regularisation_resolver_ignores_a_leave_card(self, _fake_action_store):
        import services.leave_slot_service as leave_slot_service
        leave_slot_service.set_manager_action(26, "conv-reg-1", {
            "kind": "leave", "step": "awaiting_confirmation",
            "action": "approve", "leave_request_id": 58, "card": {},
        })

        assert regularisation_approval.resolve_pending_regularisation_intent(
            26, "conv-reg-1", "yes") is None
        assert leave_approval.resolve_pending_approval_intent(
            26, "conv-reg-1", "yes") == leave_approval.APPROVAL_INTENT

    def test_an_untagged_card_still_belongs_to_the_leave_flow(self, _fake_action_store):
        """Cards written before the kind tag existed must keep working."""
        import services.leave_slot_service as leave_slot_service
        leave_slot_service.set_manager_action(26, "conv-reg-1", {
            "step": "awaiting_confirmation", "action": "approve",
            "leave_request_id": 58, "card": {},
        })

        assert leave_approval.resolve_pending_approval_intent(
            26, "conv-reg-1", "yes") == leave_approval.APPROVAL_INTENT
        assert regularisation_approval.resolve_pending_regularisation_intent(
            26, "conv-reg-1", "yes") is None

    async def test_a_regularization_yes_does_not_approve_a_leave(self, erp, _fake_action_store,
                                                                monkeypatch):
        """The end-to-end version of the two tests above: with a leave card
        showing, a regularization confirmation must not reach the leave
        approve endpoint."""
        approved_leaves = []

        async def fake_approve_leave(*args, **kwargs):
            approved_leaves.append(args)
            return {"http_status": 200, "body": {"success": True, "data": {}}}

        monkeypatch.setattr(erp_client, "approve_leave_request", fake_approve_leave)

        erp.list_result = list_body([REG_56])
        erp.approve_result = approve_body(reg_id=56, employee_id=3759)
        await run("approve A Emp's regularization request", erp)
        await run("yes", erp)

        assert erp.approve_calls == [56]
        assert approved_leaves == []
