# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-its-aaif-trust-root-before-accepting-a-federated-peer-s-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-its-aaif-trust-root-before-accepting-a-federated-peer-s-attestation.warrant.json
# Markdown SHA-256:   6f540444b0f2cc41f9e77bbc296450c8522e0af59ffe72c30db181dab4f320c9
# Code AST SHA-256:   7e5a7b920739d4d159417383deede4573ff9ce19a31c0368be9feeb9d09116cc
# Verified Classes:   StaleAnchorError, AnchorSet, CachedChain, FederatedVerifier
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Set


class StaleAnchorError(RuntimeError):
    """Raised when a chain's terminal AAIF root is no longer authoritative."""
    pass


@dataclass
class AnchorSet:
    roots: Set[str]
    revoked: Dict[str, float]      # root_id -> effective revocation timestamp
    fetched_at: float
    propagation_bound: float       # max seconds anchor state may be stale


@dataclass
class CachedChain:
    terminal_root: str
    issuers: Set[str]
    verified_at: float


class FederatedVerifier:
    def __init__(self, anchor_fetch_fn):
        self._fetch_anchor = anchor_fetch_fn
        self._chain_cache: Dict[str, CachedChain] = {}
        self._anchor: AnchorSet | None = None

    def _current_anchor(self, now: float) -> AnchorSet:
        if self._anchor is None or (now - self._anchor.fetched_at) > self._anchor.propagation_bound:
            self._anchor = self._fetch_anchor()
        return self._anchor

    def accept_peer(self, peer_id: str, chain: CachedChain, now: float | None = None) -> bool:
        now = now if now is not None else time.time()
        anchor = self._current_anchor(now)

        root = chain.terminal_root
        # Anchor validity is re-derived on EVERY decision, never cached with the chain.
        if root not in anchor.roots:
            raise StaleAnchorError(
                f"peer {peer_id}: terminal root {root} absent from current AAIF anchor set"
            )
        revoked_at = anchor.revoked.get(root)
        if revoked_at is not None and now >= revoked_at:
            # Transitive invalidation: drop every chain anchored at this root.
            for pid, cached in list(self._chain_cache.items()):
                if cached.terminal_root == root:
                    del self._chain_cache[pid]
            raise StaleAnchorError(
                f"peer {peer_id}: root {root} revoked at {revoked_at}, now {now}; "
                f"transitively invalidated {len(self._chain_cache)} cached identities"
            )

        self._chain_cache[peer_id] = chain
        return True
