"""R-T1-12B (survivability §2.5, Tier-1 #12) — the `recover` wire op:
run the reset-escalation ladder on a quarantined URN.

The ladder mechanism (FLR → bus → quarantine, with per-rung verification
and the escalated `reset_unverified` reason) is pinned at the lease-engine
layer in `core_test.zig` against a FakeBackend with per-level reset
control. What the wire test adds is the op surface end-to-end: the
`steal`-right gate and the safe no-op on a healthy URN (the broker's
seeded test backend never auto-quarantines, so a real recovered_flr/bus
isn't wire-observable here — that's the Zig pin's job).
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from tests.contract.conftest import rt

if TYPE_CHECKING:
    import socket

pytestmark = pytest.mark.contract


def test_recover_healthy_urn_is_a_noop(
    raw_broker_with_cap: tuple[socket.socket, int],
) -> None:
    """Recovery never force-resets a device in service: a non-quarantined
    URN returns `not_quarantined` (the ladder does nothing)."""
    sock, root_cap = raw_broker_with_cap
    resp = rt(sock, {"op": "recover", "urn": "hw:/test/dev0", "cap_id": root_cap})
    assert resp.get("ok") is True, f"recover should succeed; got {resp!r}"
    assert resp.get("outcome") == "not_quarantined", f"a healthy URN must be a no-op; got {resp!r}"


def test_recover_is_steal_gated(
    raw_broker_with_cap: tuple[socket.socket, int],
) -> None:
    """Recovery is a forceful hardware repair — gated by the `steal` right
    (like revoke). A sub-cap minted WITHOUT steal cannot recover."""
    sock, root_cap = raw_broker_with_cap
    # Mint an observe-only sub-cap (drops steal). Root carries steal.
    sub = rt(sock, {"op": "attenuate", "cap_id": root_cap, "rights": ["observe"]})
    assert sub.get("ok") is True
    sub_cap = int(sub["cap_id"])
    denied = rt(sock, {"op": "recover", "urn": "hw:/test/dev0", "cap_id": sub_cap})
    assert denied.get("ok") is False
    assert denied.get("err") == "NotPermitted", (
        f"recovery without the steal right must be refused; got {denied!r}"
    )


def test_recover_unknown_urn_is_a_noop(
    raw_broker_with_cap: tuple[socket.socket, int],
) -> None:
    """An unrouted / nonexistent URN has nothing to recover — the honest
    answer is the no-op outcome, not an error."""
    sock, root_cap = raw_broker_with_cap
    resp = rt(sock, {"op": "recover", "urn": "hw:/test/nope-9999", "cap_id": root_cap})
    assert resp.get("ok") is True
    assert resp.get("outcome") == "not_quarantined"
