# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-a2a-peer-s-verifiable-credential-whose-issuer-trust-anchor-rotated-between-the-peer-s-last-attestati.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-a2a-peer-s-verifiable-credential-whose-issuer-trust-anchor-rotated-between-the-peer-s-last-attestati.warrant.json
# Markdown SHA-256:   dc1ec217f73b528c11abaf5745a1f2d7d72c07afe216ce43f31e9949c858fb06
# Code AST SHA-256:   5fef7e60e2852e3c2c9781211833c869deed7fd172c3844d7cab5e2e1286cf97
# Verified Classes:   AnchorContinuityError, AnchorGeneration, VerifiableCredential, FederatedHandoffGate
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class AnchorContinuityError(RuntimeError):
    """Raised when a federated VC verifies cryptographically but its issuer
    trust anchor is stale, superseded, or revoked at the moment of handoff."""


@dataclass(frozen=True)
class AnchorGeneration:
    issuer: str
    generation: int
    not_before: float
    valid_until: float
    revoked_for_compromise: bool = False

    def covers(self, t_issue: float) -> bool:
        return self.not_before <= t_issue < self.valid_until


@dataclass(frozen=True)
class VerifiableCredential:
    issuer: str
    subject: str
    issued_at: float          # issuer-committed iat; NOT receiver arrival time
    signature_valid: bool     # result of crypto check against *some* generation


class FederatedHandoffGate:
    def __init__(self, staleness_budget_s: float = 300.0):
        self._anchors: dict[str, list[AnchorGeneration]] = {}
        self._last_refresh: dict[str, float] = {}
        self._staleness_budget = staleness_budget_s

    def current_generation(self, issuer: str) -> AnchorGeneration:
        gens = self._anchors.get(issuer)
        if not gens:
            raise AnchorContinuityError(f"no anchor pinned for issuer {issuer}")
        return max(gens, key=lambda g: g.generation)

    def refresh(self, issuer: str, gens: list[AnchorGeneration]) -> None:
        self._anchors[issuer] = gens
        self._last_refresh[issuer] = time.time()

    def _anchor_is_fresh(self, issuer: str, now: float) -> bool:
        last = self._last_refresh.get(issuer)
        return last is not None and (now - last) < self._staleness_budget

    def accept_handoff(self, vc: VerifiableCredential, now: float) -> AnchorGeneration:
        # 1. Cryptographic layer: signature must verify.
        if not vc.signature_valid:
            raise AnchorContinuityError(f"signature invalid for {vc.subject}")

        # 2. Continuity layer: anchor freshness must be within budget.
        if not self._anchor_is_fresh(vc.issuer, now):
            # Fail closed: do NOT fall back to a cached pin.
            raise AnchorContinuityError(
                f"anchor for {vc.issuer} stale beyond budget; refusing to "
                f"accept {vc.subject} on a cached trust decision"
            )

        current = self.current_generation(vc.issuer)

        # 3. Issuance must fall inside the *current* generation window.
        if not current.covers(vc.issued_at):
            # Find which generation actually signed it, if any.
            superseded = next(
                (g for g in self._anchors[vc.issuer] if g.covers(vc.issued_at)),
                None,
            )
            if superseded is not None and superseded.revoked_for_compromise:
                raise AnchorContinuityError(
                    f"VC for {vc.subject} issued under generation "
                    f"{superseded.generation}, revoked for compromise; "
                    f"retroactive distrust required"
                )
            raise AnchorContinuityError(
                f"VC for {vc.subject} issued at {vc.issued_at} outside current "
                f"generation {current.generation} window "
                f"[{current.not_before}, {current.valid_until})"
            )

        # 4. Current generation itself must not be revoked-for-compromise.
        if current.revoked_for_compromise:
            raise AnchorContinuityError(
                f"current anchor generation {current.generation} for "
                f"{vc.issuer} is revoked for compromise"
            )

        return current


# --- Failure trace: the t1 -> t2 scenario -------------------------------------
gate = FederatedHandoffGate(staleness_budget_s=300.0)
t0 = 1_000.0
t1 = 1_050.0
t2 = 1_400.0

gate.refresh("I_beta", [
    AnchorGeneration("I_beta", generation=1, not_before=t0,
                     valid_until=t2 + 10, revoked_for_compromise=True),
    AnchorGeneration("I_beta", generation=2, not_before=t2 - 100,
                     valid_until=t2 + 100_000),
])

# VC issued at t1 under g1, but by the time of handoff (t2) g1 is revoked.
stale_vc = VerifiableCredential(
    issuer="I_beta", subject="P", issued_at=t1, signature_valid=True,
)

try:
    gate.accept_handoff(stale_vc, now=t2)
except AnchorContinuityError as e:
    print(f"REJECTED (correctly): {e}")
