# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-revoked-peer-when-its-own-issuer-rotates-keys-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-revoked-peer-when-its-own-issuer-rotates-keys-mid-handoff.warrant.json
# Markdown SHA-256:   6cdc533785ac28cabbbdc68425514ee533a62bc6e15ede0f9a8b00051ff6785b
# Code AST SHA-256:   0ebc89ecef241fac62da4d980e2ddbc062d96fba540fbace39d664bbe64f8a65
# Verified Classes:   RevocationScopeError, RevocationRecord, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class RevocationScopeError(RuntimeError):
    """Raised when a peer would be admitted despite a subject-scoped revocation
    from a trusted issuer, or when a rotation chain is subject-rooted."""


@dataclass(frozen=True)
class RevocationRecord:
    issuer: str
    subject: str
    reason_class: str  # 'key_compromise' | 'subject_compromise' | 'delegation_revoked'
    epoch: int


@dataclass(frozen=True)
class Attestation:
    issuer: str
    subject: str
    key_id: str
    issued_at_epoch: int
    rotation_chain_root: str  # issuer id that roots the rotation chain, if any


def admit_peer(
    att: Attestation,
    trust_set: Iterable[str],
    revocations: Iterable[RevocationRecord],
    issuer_epochs: dict[str, int],
) -> bool:
    trust = set(trust_set)
    if att.issuer not in trust:
        raise RevocationScopeError(f"attestation issuer {att.issuer} not in trust set")

    # Step 2: subject-scoped revocation union across ALL trusted issuers.
    for rev in revocations:
        if rev.issuer not in trust:
            continue
        if rev.subject != att.subject:
            continue
        if rev.reason_class in ("subject_compromise", "delegation_revoked"):
            raise RevocationScopeError(
                f"subject {att.subject} revoked by {rev.issuer} "
                f"(reason={rev.reason_class}); attestation from {att.issuer} cannot override"
            )

    # Step 3: rotation chain must be issuer-rooted, not subject-rooted.
    if att.rotation_chain_root and att.rotation_chain_root == att.subject:
        raise RevocationScopeError(
            f"subject {att.subject} presented a self-rooted rotation chain; "
            f"rotation authority is not identity authority"
        )

    # Step 4: monotonic epoch check against each issuer's latest transition for subject.
    for issuer in trust:
        latest = issuer_epochs.get(issuer, 0)
        if att.issued_at_epoch < latest:
            raise RevocationScopeError(
                f"attestation epoch {att.issued_at_epoch} precedes {issuer} "
                f"latest revocation epoch {latest} for subject {att.subject}"
            )

    return True
