# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-its-delegated-aaif-credential-silently-outlived-the-authority-that-minted-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-its-delegated-aaif-credential-silently-outlived-the-authority-that-minted-it.warrant.json
# Markdown SHA-256:   b4cb888a430d93106ca40ab4105fdd9dfd40734acfb93580152bc7632f04410b
# Code AST SHA-256:   b2fe083c68ed858488dbdf0f57316a064d902c5f3aff692b6aa92f49d59f8b1c
# Verified Classes:   OrphanedDelegationError, Warrant, LeafCredential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class OrphanedDelegationError(RuntimeError):
    """Raised when a leaf credential verifies locally but an ancestor warrant
    in the AAIF chain is expired, revoked, or unconfirmable within Δ."""
    pass


@dataclass
class Warrant:
    issuer: str
    not_before: float
    not_after: float
    scope: frozenset


@dataclass
class LeafCredential:
    subject: str
    parent: str
    not_before: float
    not_after: float
    scope: frozenset
    signature_valid: bool


REVOCATION_FRESHNESS_DELTA = 30.0  # seconds; hard bound on ancestor liveness staleness


def _ancestor_live(warrant: Warrant, now: float, oracle_reachable: bool) -> bool:
    if not oracle_reachable:
        # fail closed: unconfirmable liveness is treated as dead, never as OK
        return False
    return warrant.not_before <= now <= warrant.not_after


def validate_chain_at_use(
    leaf: LeafCredential,
    ancestors: list[Warrant],
    now: Optional[float] = None,
    oracle_reachable: bool = True,
) -> None:
    now = time.time() if now is None else now

    # 1. leaf-local checks (necessary, not sufficient)
    if not leaf.signature_valid:
        raise OrphanedDelegationError(f"leaf signature invalid for {leaf.subject}")
    if not (leaf.not_before <= now <= leaf.not_after):
        raise OrphanedDelegationError(
            f"leaf {leaf.subject} outside its own window at t={now}"
        )

    # 2. temporal containment across the full chain
    if not ancestors:
        raise OrphanedDelegationError(
            f"leaf {leaf.subject} has no ancestor chain to justify it"
        )
    parent_window_open = min(w.not_after for w in ancestors)
    parent_window_start = max(w.not_before for w in ancestors)
    if leaf.not_after > parent_window_open:
        raise OrphanedDelegationError(
            f"leaf {leaf.subject} outlives ancestor authority: "
            f"leaf.not_after={leaf.not_after} > min(ancestor.not_after)={parent_window_open}"
        )
    if leaf.not_before < parent_window_start:
        raise OrphanedDelegationError(
            f"leaf {leaf.subject} predates ancestor authority: "
            f"leaf.not_before={leaf.not_before} < max(ancestor.not_before)={parent_window_start}"
        )

    # 3. scope attenuation must hold at every hop
    for i, w in enumerate(ancestors):
        if not leaf.scope.issubset(w.scope):
            raise OrphanedDelegationError(
                f"leaf scope {sorted(leaf.scope)} escapes ancestor[{i}] "
                f"scope {sorted(w.scope)}"
            )

    # 4. use-time ancestor liveness within Δ (fail closed)
    for i, w in enumerate(ancestors):
        if not _ancestor_live(w, now, oracle_reachable):
            raise OrphanedDelegationError(
                f"orphaned delegation: ancestor[{i}] issuer={w.issuer} "
                f"not live within Δ={REVOCATION_FRESHNESS_DELTA}s at t={now}; "
                f"leaf {leaf.subject} must not be exercised"
            )
