"""Contract: the broker's ``irq_scan`` wire op + ``Client.irq_scan`` (Tier-2
defense-in-depth, survivability D7 — interrupt-rate containment).

The interrupt-rate POLICY and the facade scan → revoke + quarantine are pinned
in Zig (``irq_monitor.zig`` policy pins; ``facade_test.zig`` end-to-end with an
injected counter source). Here we pin the wire op end-to-end + its authority
gate. Per-device interrupt-counter attribution is substrate-specific, so the
production source reports nothing yet (``contained`` stays 0) — the op, the
lease enumeration, and the steal-gate are what's exercised against the real
broker; the containment behaviour is proven in the Zig facade test.

The ``broker`` fixture is function-scoped (a fresh broker per test).
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from mgf.hrb.exceptions import MgfHrbError

if TYPE_CHECKING:
    from mgf.hrb import Client


def test_irq_scan_sweeps_granted_devices(broker: Client) -> None:
    """A scan enumerates every granted device and returns the accounting. With
    the production counter source (no per-device attribution yet) nothing is
    contained, but the sweep sees the live lease."""
    lease = broker.claim("hw:/test/dev0")
    try:
        res = broker.irq_scan()
        assert res["ok"] is True
        assert res["scanned"] >= 1  # the device we hold is swept
        assert res["contained"] == 0  # null production source → nothing flagged
    finally:
        lease.release()


def test_irq_scan_on_idle_broker_is_a_clean_noop(broker: Client) -> None:
    """No granted devices → nothing scanned, nothing contained, still ok."""
    res = broker.irq_scan()
    assert res["ok"] is True
    assert res["scanned"] == 0
    assert res["contained"] == 0


def test_irq_scan_requires_operator_authority(broker: Client) -> None:
    """The op is steal-gated on ``hw:/**`` — a cap attenuated to a narrow scope
    cannot trigger a broker-wide containment sweep (the same operator-class gate
    as ``reconcile``/``recover``)."""
    narrow = broker.attenuate(scope="hw:/test/dev0")
    try:
        with pytest.raises(MgfHrbError):
            narrow.irq_scan()
    finally:
        narrow.close()
