# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-federated-capability-grant-silently-outlive-the-policy-epoch-that-authorized-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-federated-capability-grant-silently-outlive-the-policy-epoch-that-authorized-it.warrant.json
# Markdown SHA-256:   64588d41512ef3b408988e2316f0993197c36a66c0d0f1f7c2129ccd9387d25e
# Code AST SHA-256:   f28bf2ee2ea32f6fd986448341e2f4b89f6b8115727e6a7c8ad79121d32f4d2c
# Verified Classes:   EpochAdmissionError, CapabilityToken, OwnerEpochState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class EpochAdmissionError(RuntimeError):
    """Raised when a capability token's policy epoch is not admissible at the resource owner."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    resource_owner: str
    policy_epoch: str
    data_class: str
    expires_at: float
    signature_valid: bool


@dataclass(frozen=True)
class OwnerEpochState:
    current_epoch: str
    pinned_data_classes: frozenset
    # epochs for which the owner has issued an explicit continuity proof
    continuity_proven_epochs: frozenset


def admit_capability(
    token: CapabilityToken,
    owner_state: OwnerEpochState,
    now: Optional[float] = None,
) -> bool:
    now = time.time() if now is None else now

    if not token.signature_valid:
        raise EpochAdmissionError(
            f"signature invalid for subject={token.subject} owner={token.resource_owner}"
        )

    if token.expires_at <= now:
        raise EpochAdmissionError(
            f"token expired at {token.expires_at} (now={now})"
        )

    epoch_is_current = token.policy_epoch == owner_state.current_epoch

    if epoch_is_current:
        return True

    # Superseded epoch: admissible only via explicit continuity proof AND
    # only when the data class is not jurisdiction-pinned.
    if token.data_class in owner_state.pinned_data_classes:
        raise EpochAdmissionError(
            f"epoch-pinned admission required: token_epoch={token.policy_epoch} "
            f"owner_epoch={owner_state.current_epoch} data_class={token.data_class} "
            f"subject={token.subject}; continuity proofs are invalid for pinned classes"
        )

    if token.policy_epoch not in owner_state.continuity_proven_epochs:
        raise EpochAdmissionError(
            f"superseded epoch {token.policy_epoch} lacks continuity proof under "
            f"owner_epoch={owner_state.current_epoch} for data_class={token.data_class}"
        )

    return True
