# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-signed-capability-manifest-whose-revocation-proof-is-newer-than-the-manifest-s-own-signature-without-collapsing-provena.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-signed-capability-manifest-whose-revocation-proof-is-newer-than-the-manifest-s-own-signature-without-collapsing-provena.warrant.json
# Markdown SHA-256:   12ed09be88943845822873a9d6746d615da80c15d5c06c89fb1ffb1571da2d9f
# Code AST SHA-256:   4bd25a0ea36f9bb697d4c9640fe001669fa8d0dc2e1070272998588f86e7b9d8
# Verified Classes:   RevocationVerificationError, Manifest, Revocation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class RevocationVerificationError(RuntimeError):
    """Raised when a manifest cannot be admitted under epoch-authoritative revocation rules."""


@dataclass(frozen=True)
class Manifest:
    identity: str
    grant_epoch: int
    signed_at: datetime
    validity_window: timedelta
    scopes: frozenset


@dataclass(frozen=True)
class Revocation:
    identity: str
    revoked_epoch: int
    scope: frozenset
    signed_at: datetime
    key_compromise: bool = False


def admit(
    manifest: Manifest,
    revocations: list,
    revocation_fetched_at: datetime,
    max_revocation_staleness: timedelta,
    now: datetime,
) -> bool:
    if now - revocation_fetched_at > max_revocation_staleness:
        raise RevocationVerificationError(
            f"revocation set stale by {now - revocation_fetched_at}; failing closed"
        )

    seen_epochs: dict = {}
    for r in revocations:
        if r.identity != manifest.identity:
            continue
        prior = seen_epochs.get(r.revoked_epoch)
        if prior is not None and prior.scope != r.scope:
            raise RevocationVerificationError(
                f"epoch fork at epoch {r.revoked_epoch} for {r.identity}; failing closed"
            )
        seen_epochs[r.revoked_epoch] = r

    window_end = manifest.signed_at + manifest.validity_window
    for r in seen_epochs.values():
        if r.key_compromise and r.signed_at >= manifest.signed_at:
            raise RevocationVerificationError(
                f"identity {manifest.identity} compromised at {r.signed_at}; "
                f"manifest signed {manifest.signed_at} is inadmissible"
            )
        in_window = manifest.signed_at <= r.signed_at <= window_end
        if in_window and r.revoked_epoch >= manifest.grant_epoch:
            raise RevocationVerificationError(
                f"manifest epoch {manifest.grant_epoch} superseded by revoked "
                f"epoch {r.revoked_epoch} for {manifest.identity}"
            )
    return True
