# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-scope-token-whose-aaif-credential-chain-has-expired-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-scope-token-whose-aaif-credential-chain-has-expired-mid-handoff.warrant.json
# Markdown SHA-256:   c1292aa291c5889c243becaefcd29929dcfcb351139fb63ee424f9c60b289a29
# Code AST SHA-256:   2301e6e09b47a03deb3559f00f199a8e48321d21fcee27d116ab96f21e8562ad
# Verified Classes:   DelegatedScopeChainError, Credential, ChainLink, DelegatedToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class DelegatedScopeChainError(RuntimeError):
    """Raised when a delegated-scope token's authority chain is not honorable."""
    pass


@dataclass
class Credential:
    subject: str
    not_before: float
    not_after: float

    def live_at(self, t: float) -> bool:
        return self.not_before <= t <= self.not_after


@dataclass
class ChainLink:
    delegator_cred: Credential
    minted_at: float


@dataclass
class DelegatedToken:
    subject: str
    exp: float
    chain: list[ChainLink] = field(default_factory=list)
    has_chain_liveness: bool = False
    last_liveness_check: Optional[float] = None


def validate_delegated_token(
    token: DelegatedToken,
    now: float,
    delta: float = 60.0,
    root_reachable: bool = True,
) -> None:
    # Clause 1: leaf liveness
    if token.exp <= now:
        raise DelegatedScopeChainError(
            f"leaf token expired: exp={token.exp} now={now}"
        )

    # Clause 2: delegation-time liveness of every ancestor link
    for i, link in enumerate(token.chain):
        if not link.delegator_cred.live_at(link.minted_at):
            raise DelegatedScopeChainError(
                f"chain link {i} ({link.delegator_cred.subject}) was not live "
                f"at delegation time minted_at={link.minted_at}; "
                f"window=[{link.delegator_cred.not_before},{link.delegator_cred.not_after}]"
            )

    # Clause 3: use-time root liveness fallback
    if not token.has_chain_liveness:
        if not root_reachable:
            raise DelegatedScopeChainError(
                "token lacks chain_liveness assertion and root issuer unreachable; "
                "cannot confirm use-time authority"
            )
        if token.last_liveness_check is None:
            raise DelegatedScopeChainError(
                "resumed instance has no recorded last_liveness_check; "
                "treat as delta exceeded and refuse"
            )
        if now - token.last_liveness_check > delta:
            raise DelegatedScopeChainError(
                f"use-time liveness stale: last check {now - token.last_liveness_check:.1f}s "
                f"ago exceeds delta={delta}s"
            )


# Trace: root C_A live [0,900], delegate at t=100 (valid), leaf exp=1200.
# Verifier acts at t=940. Leaf live, but root dead behind it.
root = Credential("planner", 0.0, 900.0)
token = DelegatedToken(
    subject="verifier",
    exp=1200.0,
    chain=[ChainLink(delegator_cred=root, minted_at=100.0)],
    has_chain_liveness=False,
    last_liveness_check=None,  # resumed from checkpoint
)
validate_delegated_token(token, now=940.0)  # raises: stale liveness on resume
