# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-delegated-authority-when-an-aaif-attestation-chain-is-truncated-by-intermediate-warrant-expiry.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-delegated-authority-when-an-aaif-attestation-chain-is-truncated-by-intermediate-warrant-expiry.warrant.json
# Markdown SHA-256:   2d097e891d00a20bc6fdbf602b49e49a41f02c1617cf5c40817e083c9f0f7fbc
# Code AST SHA-256:   d9d3fa6e7f141b6340f70f8368be11524a1306b1b3ca2ca6cdb006a10ad4942e
# Verified Classes:   OrphanedWarrantError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanedWarrantError(RuntimeError):
    """Raised when a leaf warrant's provenance cannot be established at execution time."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    subject: str
    not_before: float
    not_after: float
    revoked: bool = False

    def valid_at(self, t: float) -> bool:
        return (not self.revoked) and (self.not_before <= t <= self.not_after)


def verify_delegation_chain(
    chain: list[Warrant],
    t_exec: float,
    *,
    chain_truncated: bool,
    cached_links: Optional[dict[str, Warrant]] = None,
) -> None:
    """
    Enforce AAIF provenance: every link must be valid at t_exec, not t_recv.
    Fails closed on truncation unless every missing link is re-validated from cache.
    """
    if not chain:
        raise OrphanedWarrantError("empty chain: no root authority to anchor provenance")

    # Resolve truncation gaps from cache, but re-validate each cached link at t_exec.
    resolved = list(chain)
    if chain_truncated:
        if not cached_links:
            raise OrphanedWarrantError(
                f"chain truncated at t_exec={t_exec} with no cache: "
                "cannot distinguish valid leaf from orphaned-leaf window; failing closed"
            )
        for link in cached_links.values():
            if not link.valid_at(t_exec):
                raise OrphanedWarrantError(
                    f"cached link {link.warrant_id} invalid at t_exec={t_exec} "
                    f"(window {link.not_before}-{link.not_after}); cache is stale"
                )
            resolved.append(link)

    # Temporal-intersection clause: every link valid at execution time.
    for link in resolved:
        if not link.valid_at(t_exec):
            raise OrphanedWarrantError(
                f"link {link.warrant_id} not valid at t_exec={t_exec}: "
                f"window {link.not_before}-{link.not_after}, revoked={link.revoked}"
            )

    # Linkage: each issuer must be the prior subject (root -> ... -> leaf).
    for parent, child in zip(resolved, resolved[1:]):
        if parent.subject != child.issuer:
            raise OrphanedWarrantError(
                f"linkage break: {parent.warrant_id}.subject={parent.subject} "
                f"!= {child.warrant_id}.issuer={child.issuer}"
            )

    leaf = resolved[-1]
    min_ancestor_horizon = min(w.not_after for w in resolved[:-1])
    if leaf.not_after > min_ancestor_horizon:
        # Leaf outlives its narrowest ancestor; only sound if mint-time min-derivation attested.
        # Without that attestation, provenance is bounded by the ancestor horizon.
        if t_exec > min_ancestor_horizon:
            raise OrphanedWarrantError(
                f"leaf {leaf.warrant_id} executed at t_exec={t_exec} beyond "
                f"narrowest ancestor horizon {min_ancestor_horizon}: orphaned-leaf window"
            )
