# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-attest-a-federated-peer-whose-hardware-root-of-trust-rotated-during-credential-renewal.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-attest-a-federated-peer-whose-hardware-root-of-trust-rotated-during-credential-renewal.warrant.json
# Markdown SHA-256:   13b7b7465b7e04d1f712b29c36a535aea3d7b06eaa487151d9d953f08940797a
# Code AST SHA-256:   6b3ddc177e6feae2ec38a4ad8ce86da2850655b886b8ff6b200e645474e2e8fd
# Verified Classes:   UnauthorizedRootRotationError, RootRotationDecision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnauthorizedRootRotationError(RuntimeError):
    """Raised when a peer presents a valid attestation quote whose hardware
    root of trust does not match the pinned root and no rotation
    authorization is on file. Refusing renewal is the safe branch; do not
    catch this to implement a grace renewal that updates the pin."""
    pass


class RootRotationDecision:
    RENEW = "renew"
    RENEW_AND_REPIN = "renew_and_repin"
    REFUSE = "refuse"


def evaluate_renewal(
    agent_id: str,
    presented_leaf_fingerprint: str,
    pinned_fingerprint: str,
    rotation_authorization: dict | None,
    authorization_service_available: bool,
) -> str:
    if presented_leaf_fingerprint == pinned_fingerprint:
        return RootRotationDecision.RENEW

    # Root changed. We may only re-pin with an explicit, verifiable
    # authorization that references the OLD root. Absence of the
    # authorization service is NOT authorization.
    if not authorization_service_available:
        raise UnauthorizedRootRotationError(
            f"root rotation for {agent_id}: authorization service "
            f"unreachable; refusing renewal (safe branch)"
        )

    if (
        rotation_authorization is not None
        and rotation_authorization.get("old_root_fingerprint") == pinned_fingerprint
        and rotation_authorization.get("new_root_fingerprint")
        == presented_leaf_fingerprint
        and rotation_authorization.get("signature_verified") is True
    ):
        return RootRotationDecision.RENEW_AND_REPIN

    raise UnauthorizedRootRotationError(
        f"root rotation for {agent_id} lacks valid authorization: "
        f"pinned={pinned_fingerprint} presented={presented_leaf_fingerprint}"
    )
