# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-attestation-chain-silently-collapse-when-a-hardware-backed-key-is-re-wrapped-under-a-rotated-endorsement-root.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-attestation-chain-silently-collapse-when-a-hardware-backed-key-is-re-wrapped-under-a-rotated-endorsement-root.warrant.json
# Markdown SHA-256:   f4e11a0473629ff24e7f719162abce2a8ff9119c91fead63216110edbf2043a7
# Code AST SHA-256:   8fc419e78c311a4258e0d7f802613969d98252c501861f0ffa48bcd0576160e0
# Verified Classes:   AttestationError, RetiredRootError, TrustState, VerifiableCredential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class AttestationError(RuntimeError):
    """Base for attestation-chain validation failures."""


class RetiredRootError(AttestationError):
    """Chain terminates at a root the verifier has retired.

    Carries enough context for the instance's policy engine to distinguish
    re-attestation from transient auth failure.
    """

    def __init__(self, terminus_fp: str, pinned: frozenset[str], re_endorsable: bool):
        self.terminus_fp = terminus_fp
        self.pinned = pinned
        self.re_endorsable = re_endorsable
        super().__init__(
            f"chain terminates at retired root {terminus_fp}; "
            f"pinned={sorted(pinned)}; re_endorsable={re_endorsable}"
        )


class TrustState(Enum):
    TRUSTED = "trusted"
    REATTEST_REQUIRED = "reattest_required"
    REJECT = "reject"


@dataclass(frozen=True)
class VerifiableCredential:
    body: bytes
    chain: tuple[bytes, ...]  # leaf -> ... -> root, each DER-encoded
    not_after: int


def _fingerprint(cert_der: bytes) -> str:
    return hashlib.sha256(cert_der).hexdigest()


def evaluate_chain(
    vc: VerifiableCredential,
    pinned_roots: frozenset[str],
    retired_roots: frozenset[str],
    re_endorsable: bool,
) -> TrustState:
    if not vc.chain:
        raise AttestationError("empty chain")
    terminus = _fingerprint(vc.chain[-1])

    if terminus in pinned_roots:
        return TrustState.TRUSTED

    if terminus in retired_roots:
        if re_endorsable:
            return TrustState.REATTEST_REQUIRED
        raise RetiredRootError(terminus, pinned_roots, re_endorsable=False)

    # Unknown root: neither pinned nor known-retired. Fail closed.
    raise RetiredRootError(terminus, pinned_roots, re_endorsable=re_endorsable)


def peer_cache_lookup(
    cached_vc: VerifiableCredential,
    pinned_roots: frozenset[str],
    retired_roots: frozenset[str],
    re_endorsable: bool,
) -> TrustState:
    """Re-validate chain terminus on every cache hit, not just cache miss."""
    state = evaluate_chain(cached_vc, pinned_roots, retired_roots, re_endorsable)
    if state is TrustState.REATTEST_REQUIRED:
        # Peer must not accept messages from an instance the authority
        # has flagged for re-attestation; the split-brain window is
        # exactly the interval in which this branch is skipped.
        raise RetiredRootError(
            _fingerprint(cached_vc.chain[-1]), pinned_roots, re_endorsable=True
        )
    return state
