# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-an-agent-card-after-a-key-rotation-but-the-verifiable-presentation-still-anchors-to-the-retired-key.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-an-agent-card-after-a-key-rotation-but-the-verifiable-presentation-still-anchors-to-the-retired-key.warrant.json
# Markdown SHA-256:   3679a130dedf0a191c5429a50968a189f953d9f3763d0a3c0482d36b915d622d
# Code AST SHA-256:   ef6318e25ebb92823acd6a0628a07a62a92d7b451aaf50a66b8ef257b8b7ae24
# Verified Classes:   FederationTrustError, ProofDisposition, AgentCard, VerifiablePresentation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class FederationTrustError(RuntimeError):
    """Raised when a verifiable presentation cannot be bound to a live subject."""


class ProofDisposition(Enum):
    LIVE = "live"              # kid resolves in current card key set
    STALE_AUTHENTIC = "stale"  # kid resolves only in issuer historical JWKS
    UNBOUND = "unbound"        # kid resolves nowhere under this subject


@dataclass
class AgentCard:
    subject: str
    active_kids: set[str]


@dataclass
class VerifiablePresentation:
    subject: str
    proof_kid: str


def resolve_proof(
    vp: VerifiablePresentation,
    card: AgentCard,
    issuer_historical_jwks: dict[str, set[str]],
) -> ProofDisposition:
    if vp.subject != card.subject:
        raise FederationTrustError(
            f"subject mismatch: vp={vp.subject} card={card.subject}"
        )
    if vp.proof_kid in card.active_kids:
        return ProofDisposition.LIVE
    historical = issuer_historical_jwks.get(card.subject, set())
    if vp.proof_kid in historical:
        return ProofDisposition.STALE_AUTHENTIC
    raise FederationTrustError(
        f"unbound proof kid={vp.proof_kid} for subject={card.subject}; "
        f"not in active {card.active_kids} nor historical {historical}"
    )


def admit_presentation(
    vp: VerifiablePresentation,
    card: AgentCard,
    issuer_historical_jwks: dict[str, set[str]],
) -> ProofDisposition:
    disposition = resolve_proof(vp, card, issuer_historical_jwks)
    if disposition is ProofDisposition.UNBOUND:
        # unreachable given resolve_proof raises, but kept as explicit guard
        raise FederationTrustError("unbound presentation admitted")
    if disposition is ProofDisposition.STALE_AUTHENTIC:
        # caller must schedule VP refresh before next handoff
        pass
    return disposition
