# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-peer-s-attestation-during-cross-org-trust-bootstrap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-peer-s-attestation-during-cross-org-trust-bootstrap.warrant.json
# Markdown SHA-256:   a4426fc3309c30aba831b0b873af88930842032fb088f9d440a63959e8a0037a
# Code AST SHA-256:   17a08c2f4e43ea6c2b0d7ab849222e10e7565aa0798634cd854c5de9b80331d1
# Verified Classes:   RevocationEpochUnconfirmed, StaleRevocationSnapshot, Attestation, RevocationSnapshot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class RevocationEpochUnconfirmed(RuntimeError):
    """Raised when the verifier cannot establish a revocation epoch fresh enough
    to safely evaluate an attestation at presentation time."""
    pass


class StaleRevocationSnapshot(RuntimeError):
    """Raised when the local revocation snapshot is older than the attestation's
    declared max_staleness bound."""
    pass


@dataclass
class Attestation:
    attestation_id: str
    issuer: str
    subject: str
    capability: str
    t_issue: float
    expiry: float
    max_staleness: float  # seconds; verifier MUST enforce
    signature_valid: bool = True


@dataclass
class RevocationSnapshot:
    epoch: float                      # time this snapshot was fetched
    revoked_ids: set = field(default_factory=set)


def verify_attestation(
    att: Attestation,
    t_present: float,
    snapshot: Optional[RevocationSnapshot],
    trusted_issuers: set,
    issuer_reachable: bool,
) -> str:
    if not att.signature_valid:
        return "REJECT: bad signature"
    if t_present >= att.expiry:
        return "REJECT: expired"
    if att.issuer not in trusted_issuers:
        return "REJECT: untrusted issuer"

    # The non-obvious boundary: revocation is a separate proof over a later epoch.
    if snapshot is None:
        raise RevocationEpochUnconfirmed(
            f"no revocation snapshot for issuer {att.issuer}; "
            f"cannot evaluate attestation {att.attestation_id} at t={t_present}"
        )

    snapshot_age = t_present - snapshot.epoch
    if snapshot_age > att.max_staleness:
        raise StaleRevocationSnapshot(
            f"revocation snapshot age {snapshot_age:.1f}s exceeds "
            f"max_staleness {att.max_staleness:.1f}s for {att.attestation_id}"
        )

    if att.attestation_id in snapshot.revoked_ids:
        return "REJECT: revoked"

    # If the issuer is unreachable AND the attestation was issued inside the
    # unconfirmable window, defer rather than accept.
    if not issuer_reachable and (t_present - att.t_issue) <= att.max_staleness:
        raise RevocationEpochUnconfirmed(
            f"issuer {att.issuer} unreachable and attestation {att.attestation_id} "
            f"issued within max_staleness window; refusing to accept on stale epoch"
        )

    return "ACCEPT"


def handoff_guard(att: Attestation, t_present: float, snapshot, trusted, reachable) -> None:
    decision = verify_attestation(att, t_present, snapshot, trusted, reachable)
    if decision != "ACCEPT":
        raise RevocationEpochUnconfirmed(
            f"handoff blocked: {decision} for {att.attestation_id}"
        )
