# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-agent-passport-whose-trust-anchor-was-rotated-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-agent-passport-whose-trust-anchor-was-rotated-mid-handshake.warrant.json
# Markdown SHA-256:   153276e55801faa2e5bc07dceeac058d137ff01a5a457fccad8fa0c7f7ea4397
# Code AST SHA-256:   350fdbf61bc9f2043e6c73ce96dd74b82568512cc7499f6c11fd6f7c763bba4d
# Verified Classes:   AnchorContinuityError, Anchor, PinnedAnchor, Passport
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class AnchorContinuityError(RuntimeError):
    """Raised when a federated passport cannot be anchored to a trusted key."""
    pass


@dataclass(frozen=True)
class Anchor:
    federation_id: str
    key_id: str
    public_key: bytes
    valid_from: float
    valid_until: Optional[float]
    continuity_signed_by: Optional[str]  # key_id that signed the bridge, if any


@dataclass(frozen=True)
class PinnedAnchor:
    anchor: Anchor
    observed_at: float
    document_hash: str


@dataclass(frozen=True)
class Passport:
    federation_id: str
    issuer_key_id: str
    chain_anchor_key_id: str
    issued_at: float


def validate_federated_passport(
    passport: Passport,
    current: Anchor,
    pinned: Optional[PinnedAnchor],
) -> None:
    if passport.federation_id != current.federation_id:
        raise AnchorContinuityError(
            f"federation mismatch: passport={passport.federation_id} "
            f"anchor={current.federation_id}"
        )

    # First contact: no pinned anchor, accept only if the passport chains to
    # the current anchor and was issued inside its window.
    if pinned is None:
        if passport.chain_anchor_key_id != current.key_id:
            raise AnchorContinuityError(
                "first-contact passport does not chain to current anchor"
            )
        if not _within(passport.issued_at, current):
            raise AnchorContinuityError("passport issued outside anchor window")
        return

    old = pinned.anchor

    # No rotation: normal validation.
    if old.key_id == current.key_id:
        if passport.chain_anchor_key_id != current.key_id:
            raise AnchorContinuityError("passport chains to unknown anchor key")
        if not _within(passport.issued_at, current):
            raise AnchorContinuityError("passport issued outside anchor window")
        return

    # Rotation observed. Require a continuity statement signed by the pinned key.
    if current.continuity_signed_by != old.key_id:
        raise AnchorContinuityError(
            f"anchor rotation for {current.federation_id} lacks continuity "
            f"signed by pinned key {old.key_id}; possible anchor substitution"
        )

    # Continuity proven: select anchor by issuance time.
    if passport.issued_at < current.valid_from:
        selected = old
    else:
        selected = current

    if passport.chain_anchor_key_id != selected.key_id:
        raise AnchorContinuityError(
            f"passport chains to {passport.chain_anchor_key_id}, "
            f"expected {selected.key_id} for issuance time"
        )
    if not _within(passport.issued_at, selected):
        raise AnchorContinuityError("passport issued outside selected anchor window")


def _within(t: float, anchor: Anchor) -> bool:
    if t < anchor.valid_from:
        return False
    if anchor.valid_until is not None and t >= anchor.valid_until:
        return False
    return True
