# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-narrowing-replay-in-aaif-delegated-credential-chains-when-the-attenuation-proof-is-valid-but-the-delegation-epoch-ha.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-narrowing-replay-in-aaif-delegated-credential-chains-when-the-attenuation-proof-is-valid-but-the-delegation-epoch-ha.warrant.json
# Markdown SHA-256:   e6f6fde9396e9f8e6d15d5f7d7784b593bf645cb29e4d5caca3b313db52f034a
# Code AST SHA-256:   33613e39c82444e07e646cd9ceaed852ee67a2ede9e23c9613a757e89dd26b53
# Verified Classes:   StaleDelegationEpoch, EpochForkDetected, EpochUnavailable, Token, EpochVector
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleDelegationEpoch(RuntimeError):
    """Raised when a delegated token's epoch lags its root's current epoch."""
    pass


class EpochForkDetected(RuntimeError):
    """Raised when a token claims an epoch the root has never issued."""
    pass


class EpochUnavailable(RuntimeError):
    """Raised when the root epoch cannot be attested and policy is fail-closed."""
    pass


@dataclass
class Token:
    issuer: str
    subject: str
    scope: str
    parent_hash: str
    epoch: int
    exp: float


@dataclass
class EpochVector:
    current: dict[str, int]          # root principal -> current epoch
    fetched_at: float                # monotonic timestamp of last successful fetch
    max_staleness_s: float           # policy bound for advisory reads


def verify_chain_admission(
    chain: list[Token],
    epoch_vector: Optional[EpochVector],
    now: float,
    sensitive: bool,
) -> None:
    """
    Enforce the epoch-equality invariant across every ancestor in the chain
    BEFORE any scope or signature acceptance is treated as sufficient.
    """
    # Structural pass (signatures, parent_hash linkage, scope subset) assumed done.
    for token in chain:
        if token.exp <= now:
            raise StaleDelegationEpoch(
                f"token for {token.subject} expired at {token.exp}"
            )

    if epoch_vector is None:
        if sensitive:
            raise EpochUnavailable(
                "root epoch unreachable and resource is sensitive; refusing admission"
            )
        # Non-sensitive: only admissible if feed staleness is within policy.
        # Caller must supply fetched_at elsewhere; here we treat None as unsafe.
        raise EpochUnavailable(
            "no epoch vector available; cannot evaluate delegation lease"
        )

    if sensitive and (now - epoch_vector.fetched_at) > epoch_vector.max_staleness_s:
        raise EpochUnavailable(
            f"epoch vector stale by {now - epoch_vector.fetched_at:.2f}s "
            f"> policy {epoch_vector.max_staleness_s:.2f}s"
        )

    for token in chain:
        root = token.issuer
        if root not in epoch_vector.current:
            raise EpochUnavailable(
                f"no attested epoch for root {root}; cannot verify delegation lease"
            )
        root_epoch = epoch_vector.current[root]
        if token.epoch < root_epoch:
            raise StaleDelegationEpoch(
                f"token subject={token.subject} epoch={token.epoch} "
                f"lags root={root} epoch={root_epoch}; delegation lease revoked"
            )
        if token.epoch > root_epoch:
            raise EpochForkDetected(
                f"token subject={token.subject} epoch={token.epoch} "
                f"ahead of root={root} epoch={root_epoch}; possible split-brain issuer"
            )
    # Invariant satisfied: every ancestor epoch equals its root's current epoch.
