# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-attestation-chain-whose-leaf-warrant-was-minted-under-a-superseded-aaif-root-key.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-attestation-chain-whose-leaf-warrant-was-minted-under-a-superseded-aaif-root-key.warrant.json
# Markdown SHA-256:   cb673ddc03acc2d1252f7588df4b5bd3c3dc5543369b0c73ad8dfcd75ad1ab69
# Code AST SHA-256:   1bc2c77f7e1957ed359e41c307b8d11097a7ce79edef00775baa3eb404540641
# Verified Classes:   WarrantStaleError, Warrant, RootKey
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Sequence


class WarrantStaleError(RuntimeError):
    """Raised when a delegated warrant chain was extended after its root key was retired."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    issued_at: float
    not_after: float
    scope: str
    signature_valid: bool


@dataclass(frozen=True)
class RootKey:
    key_id: str
    retired_at: float  # hard cutoff for chain extension
    grace_until: float  # retention for presentation of pre-retirement chains only


def verify_delegated_chain(
    chain: Sequence[Warrant],
    root_key: RootKey,
    now: float,
    requested_scope: str,
) -> None:
    if not chain:
        raise WarrantStaleError("empty warrant chain")

    # 1. Signature integrity across every link.
    for link in chain:
        if not link.signature_valid:
            raise WarrantStaleError(f"invalid signature on link issued by {link.issuer}")

    # 2. Presentation-time bound on every link.
    for link in chain:
        if now > link.not_after:
            raise WarrantStaleError(
                f"link from {link.issuer} expired at {link.not_after}, now={now}"
            )

    # 3. THE INVARIANT: chain extension must predate root retirement.
    #    Grace window covers presentation of pre-retirement chains, NOT extension.
    chain_max_issued = max(link.issued_at for link in chain)
    if chain_max_issued >= root_key.retired_at:
        raise WarrantStaleError(
            f"chain extended at {chain_max_issued} under root {root_key.key_id} "
            f"retired at {root_key.retired_at}; re-delegate under current root"
        )

    # 4. Grace window only applies to chains fully minted before retirement.
    if now > root_key.grace_until:
        raise WarrantStaleError(
            f"root {root_key.key_id} grace expired at {root_key.grace_until}, now={now}"
        )

    # 5. Scope check happens last, only on a chain that passed the invariant.
    if requested_scope not in {link.scope for link in chain}:
        raise WarrantStaleError(
            f"scope {requested_scope!r} not granted by any link in chain"
        )
