# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-trust-anchor-during-cross-org-agent-federation-when-policy-attestations-are-cached-beyond-the-anchor-s-validity.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-trust-anchor-during-cross-org-agent-federation-when-policy-attestations-are-cached-beyond-the-anchor-s-validity.warrant.json
# Markdown SHA-256:   466721b46eccef75f06222c462be6d3f2b3e1608504dae94ae84e1e74f10464d
# Code AST SHA-256:   8a17e47ccd0c78fc0edab4f4375209eb1f82435ad194ca4d23cceb770e3b916b
# Verified Classes:   StaleTrustAnchorError, CachedAttestation, FederationCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class StaleTrustAnchorError(RuntimeError):
    """Raised when a cached policy attestation is honored past the issuer's liveness bound."""


@dataclass
class CachedAttestation:
    peer_id: str
    attestation_hash: str
    issuer_anchor_id: str
    issued_at: datetime
    not_after: datetime
    last_anchor_check: datetime
    delegation_depth: int


class FederationCache:
    def __init__(self, max_revocation_age: timedelta):
        self.max_revocation_age = max_revocation_age
        self._by_peer: dict[str, CachedAttestation] = {}
        self._by_anchor: dict[str, set[str]] = {}

    def store(self, att: CachedAttestation) -> None:
        self._by_peer[att.peer_id] = att
        self._by_anchor.setdefault(att.issuer_anchor_id, set()).add(att.peer_id)

    def revoke_anchor(self, anchor_id: str) -> None:
        # Reverse-index eviction: drop every attestation transitively signed by the anchor.
        for peer_id in self._by_anchor.pop(anchor_id, set()):
            self._by_peer.pop(peer_id, None)

    def authorize(self, peer_id: str, required_depth: int, now: datetime) -> CachedAttestation:
        att = self._by_peer.get(peer_id)
        if att is None:
            raise StaleTrustAnchorError(f"no cached attestation for {peer_id}")
        if now >= att.not_after:
            raise StaleTrustAnchorError(f"attestation for {peer_id} expired at {att.not_after}")
        # The critical invariant: issuer liveness must be re-underwritten within the bound.
        if now - att.last_anchor_check > self.max_revocation_age:
            raise StaleTrustAnchorError(
                f"issuer {att.issuer_anchor_id} liveness unverified since "
                f"{att.last_anchor_check}; cache age {now - att.last_anchor_check} "
                f"exceeds max {self.max_revocation_age}"
            )
        if att.delegation_depth < required_depth:
            raise StaleTrustAnchorError(
                f"cached depth {att.delegation_depth} < required {required_depth}"
            )
        return att
