# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-attestation-that-is-valid-at-every-hop-transitive-trust-closure-versus-attestation-chain-freshness.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-attestation-that-is-valid-at-every-hop-transitive-trust-closure-versus-attestation-chain-freshness.warrant.json
# Markdown SHA-256:   497830809205c790200754d98dc4246e64115e1055b4a494f98596471fa687bf
# Code AST SHA-256:   3befe73e897c709c0774cea7018c92b8392558c417c90e2a8918bb74f0de5a68
# Verified Classes:   FederationAdmissionError, RegistryState, ChainLink, RegistrySnapshot, CapabilityChain, ActionPlan, AdmissionRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class FederationAdmissionError(RuntimeError):
    """Raised when a federated capability cannot be admitted under the freshness invariant."""


class RegistryState(Enum):
    REACHABLE = "reachable"
    UNREACHABLE = "unreachable"


@dataclass(frozen=True)
class ChainLink:
    grant_id: str
    issuer: str
    subject: str
    not_after_s: float


@dataclass(frozen=True)
class RegistrySnapshot:
    snapshot_id: str
    staleness_bound_s: float          # worst-case propagation delay S
    revoked_grant_ids: frozenset[str]
    node_state: RegistryState


@dataclass(frozen=True)
class CapabilityChain:
    links: tuple[ChainLink, ...]      # ordered leaf -> root

    def grant_ids(self) -> frozenset[str]:
        return frozenset(link.grant_id for link in self.links)


@dataclass(frozen=True)
class ActionPlan:
    expected_duration_s: float        # D
    checkpoint_interval_s: float | None = None


@dataclass
class AdmissionRecord:
    chain: CapabilityChain
    snapshot_id: str
    staleness_bound_s: float
    expected_duration_s: float
    checkpoint_interval_s: float | None
    revocation_key_set: frozenset[str] = field(default_factory=frozenset)


def admit_federated_action(
    chain: CapabilityChain,
    snapshot: RegistrySnapshot,
    action: ActionPlan,
) -> AdmissionRecord:
    # Fail-closed: an unreachable registry node cannot prove non-revocation.
    if snapshot.node_state is RegistryState.UNREACHABLE:
        raise FederationAdmissionError(
            f"registry node for snapshot {snapshot.snapshot_id} unreachable; "
            "refusing capability (fail-closed on partition)"
        )

    # Revocation must be checked against EVERY grant ID in the chain, not just the leaf.
    # A revocation published against the root grant_id is invisible to a leaf-keyed check.
    revoked_hits = chain.grant_ids() & snapshot.revoked_grant_ids
    if revoked_hits:
        raise FederationAdmissionError(
            f"chain contains revoked grant(s) {sorted(revoked_hits)} "
            f"under snapshot {snapshot.snapshot_id}"
        )

    # TTL check across every link.
    for link in chain.links:
        if link.not_after_s <= 0.0:
            raise FederationAdmissionError(
                f"grant {link.grant_id} expired (not_after_s={link.not_after_s})"
            )

    # The freshness invariant: D must be bounded by S, or checkpointed below S.
    S = snapshot.staleness_bound_s
    D = action.expected_duration_s
    if D > S:
        if action.checkpoint_interval_s is None:
            raise FederationAdmissionError(
                f"action duration D={D}s exceeds registry staleness bound S={S}s "
                "and no checkpoint schedule was registered; snapshot-validity "
                "does not imply execution-validity"
            )
        if action.checkpoint_interval_s > S:
            raise FederationAdmissionError(
                f"checkpoint interval {action.checkpoint_interval_s}s exceeds "
                f"staleness bound S={S}s; revocation could land between checkpoints"
            )

    return AdmissionRecord(
        chain=chain,
        snapshot_id=snapshot.snapshot_id,
        staleness_bound_s=S,
        expected_duration_s=D,
        checkpoint_interval_s=action.checkpoint_interval_s,
        revocation_key_set=chain.grant_ids(),
    )


def checkpoint_reverify(record: AdmissionRecord, fresh: RegistrySnapshot) -> None:
    if fresh.node_state is RegistryState.UNREACHABLE:
        raise FederationAdmissionError(
            f"checkpoint re-verification failed: registry {fresh.snapshot_id} unreachable"
        )
    revoked_hits = record.revocation_key_set & fresh.revoked_grant_ids
    if revoked_hits:
        raise FederationAdmissionError(
            f"revocation observed at checkpoint for grant(s) {sorted(revoked_hits)}; "
            "aborting in-flight action"
        )
