# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-rotated-peer-key-revocation-lag-across-federated-aaif-trust-anchors.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-rotated-peer-key-revocation-lag-across-federated-aaif-trust-anchors.warrant.json
# Markdown SHA-256:   b521f6470cff746bb104ce97739c8336190862d1cebc009d2e94fe9fc3634dcb
# Code AST SHA-256:   e283c5efcc47922a5a5e31cec358aca89505f71e39b3f8bdb45cba0680cad10c
# Verified Classes:   ChainPrunedRevocationError, RotationNode, PeerChain, FederatedResolver
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ChainPrunedRevocationError(RuntimeError):
    """Raised when a revocation targets a key no longer present in the retained rotation chain."""
    pass


@dataclass
class RotationNode:
    key_id: str
    signed_by: Optional[str]  # predecessor key_id; None for anchor root
    minted_at: float


@dataclass
class PeerChain:
    principal: str
    nodes: list = field(default_factory=list)  # oldest -> newest
    retained_until: float = 0.0

    def leaf(self) -> RotationNode:
        return self.nodes[-1]

    def contains(self, key_id: str) -> bool:
        return any(n.key_id == key_id for n in self.nodes)


class FederatedResolver:
    def __init__(self, federation_retention_bound_s: float):
        # MUST be max over all trusted anchors' worst-case gossip+heal bounds,
        # not the local anchor's bound.
        self.retention_bound = federation_retention_bound_s
        self.chains: dict[str, PeerChain] = {}
        self.revocations: set[str] = set()

    def register_root(self, principal: str, key_id: str, now: float) -> None:
        self.chains[principal] = PeerChain(
            principal=principal,
            nodes=[RotationNode(key_id=key_id, signed_by=None, minted_at=now)],
            retained_until=now + self.retention_bound,
        )

    def apply_rotation(self, principal: str, new_key_id: str,
                       signed_by: str, now: float) -> None:
        chain = self.chains[principal]
        if not chain.contains(signed_by):
            raise ChainPrunedRevocationError(
                f"rotation for {principal} signed by unknown predecessor {signed_by}"
            )
        # Retain the predecessor; do NOT prune to leaf-only.
        chain.nodes.append(RotationNode(new_key_id, signed_by, now))
        chain.retained_until = max(chain.retained_until, now + self.retention_bound)

    def apply_revocation(self, principal: str, revoked_key_id: str, now: float) -> None:
        chain = self.chains[principal]
        if now > chain.retained_until:
            # Retention window exceeded: cannot prove chain state. Fail closed.
            raise ChainPrunedRevocationError(
                f"revocation for {principal}:{revoked_key_id} arrived after "
                f"retention bound; chain state unprovable, force quorum re-validation"
            )
        if not chain.contains(revoked_key_id):
            # Unknown key inside a live retention window is NOT a stale no-op;
            # it means we pruned a node we should have kept.
            raise ChainPrunedRevocationError(
                f"revocation for {principal}:{revoked_key_id} not in retained chain"
            )
        self.revocations.add(revoked_key_id)

    def session_trusted(self, principal: str) -> bool:
        chain = self.chains[principal]
        # Trust is a function of the full chain, not the leaf.
        return not any(n.key_id in self.revocations for n in chain.nodes)
