# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-federated-peer-s-capability-manifest-before-verifying-the-issuer-s-key-warrant-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-federated-peer-s-capability-manifest-before-verifying-the-issuer-s-key-warrant-chain.warrant.json
# Markdown SHA-256:   12a30375e4a6aa2319ea704544da1f77c4dfac747feedfe28d0dbdc5e421da40
# Code AST SHA-256:   65760934a2f497aa5543cc92f72256bec85e1e7b54dff239dd0a7c1de7f18e5d
# Verified Classes:   FederationTrustError, Warrant, Manifest, PeerState
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class FederationTrustError(RuntimeError):
    """Raised when a federated peer cannot be atomically admitted."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    expires_at: float
    parent: Optional["Warrant"] = None


@dataclass(frozen=True)
class Manifest:
    issuer_key: str
    signature_valid: bool
    warrant: Optional[Warrant]
    capabilities: FrozenSet[str] = field(default_factory=frozenset)


@dataclass
class PeerState:
    admitted: bool = False
    capabilities: FrozenSet[str] = field(default_factory=frozenset)


def _walk_to_local_root(warrant: Optional[Warrant], local_roots: FrozenSet[str]) -> str:
    """Walk a warrant chain to a locally-held root. Self-rooted chains are rejected."""
    if warrant is None:
        raise FederationTrustError("no warrant supplied; cannot establish issuer authority")
    seen: set[str] = set()
    node = warrant
    while True:
        if node.issuer in seen:
            raise FederationTrustError(f"warrant chain cycles at issuer {node.issuer!r}")
        seen.add(node.issuer)
        if node.issuer in local_roots:
            return node.issuer
        if node.parent is None:
            # Reached a parentless key that is NOT a local root: self-rooted or
            # unwarranted. This is the boundary the naive walker gets wrong.
            raise FederationTrustError(
                f"warrant chain terminates at {node.issuer!r}, not a local root"
            )
        node = node.parent


def admit_peer(
    manifest: Manifest,
    local_roots: FrozenSet[str],
    now: float,
) -> PeerState:
    """Atomically admit a federated peer, or raise without committing any state."""
    if not manifest.signature_valid:
        raise FederationTrustError("manifest signature invalid")

    # Root independence: a self-rooted chain must fail even if it "terminates".
    if manifest.warrant is not None and manifest.warrant.issuer == manifest.issuer_key:
        raise FederationTrustError(
            "manifest issuer is its own warrant root; refusing self-signed authority"
        )

    root = _walk_to_local_root(manifest.warrant, local_roots)

    # Warrant validity is evaluated at admission time, not signing time.
    node = manifest.warrant
    while node is not None:
        if node.expires_at <= now:
            raise FederationTrustError(
                f"warrant from {node.issuer!r} expired at {node.expires_at}; "
                f"admission time {now}"
            )
        node = node.parent

    # Only now, after warrant resolution, is manifest-derived state committed.
    return PeerState(admitted=True, capabilities=manifest.capabilities)


def bootstrap(
    manifest: Manifest,
    local_roots: FrozenSet[str],
    now: float,
) -> PeerState:
    try:
        return admit_peer(manifest, local_roots, now)
    except FederationTrustError:
        # Quarantine: retain bytes, commit no capability state, write no memory.
        raise
