# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-aaif-credential-as-already-dead-at-the-moment-of-signature-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-aaif-credential-as-already-dead-at-the-moment-of-signature-verification.warrant.json
# Markdown SHA-256:   fe5e83858ec717e6ec5ed147fd668c04f0adc5272def7e4929fd46b93549dbe9
# Code AST SHA-256:   fc6e1c692b196e920dd53ffab48ef13b0f2dc48d7a106bc666f0084af3caae0c
# Verified Classes:   StaleDelegationError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional
import time


class StaleDelegationError(RuntimeError):
    """Raised when a delegated credential's signature verifies but its
    authority cannot be proven current: an ancestor is unconfirmed,
    un-walkable, ambiguously normalized, or the revocation oracle is
    unreachable beyond the freshness tolerance Δ."""
    pass


@dataclass(frozen=True)
class Warrant:
    id: str
    parent_id: Optional[str]
    exp: float
    scope: frozenset


def canonical_id(raw: str) -> str:
    # Single normalizer shared by mint, revoke, and verify sites.
    return raw.strip().lower()


def authorize(
    leaf: Warrant,
    chain: dict[str, Warrant],          # id -> Warrant, ancestors included
    revoked: dict[str, float],          # canonical_id -> revoked_at
    last_chain_check: dict[str, float], # canonical_id -> timestamp
    delta: float,
    now: float,
    oracle_reachable: bool,
) -> bool:
    if leaf.exp <= now:
        raise StaleDelegationError(f"leaf {leaf.id} expired at {leaf.exp}")

    # Walk the full chain to the root. A leaf-only check is unsound:
    # the revoking ancestor is, by construction, one or more links up.
    cursor: Optional[Warrant] = leaf
    visited: set[str] = set()
    while cursor is not None:
        cid = canonical_id(cursor.id)
        if cid in visited:
            raise StaleDelegationError(f"cycle in delegation chain at {cid}")
        visited.add(cid)

        if cid in revoked:
            raise StaleDelegationError(
                f"ancestor {cid} revoked at {revoked[cid]}; "
                f"leaf {leaf.id} is already-dead despite valid signature"
            )

        checked = last_chain_check.get(cid)
        if checked is None or (now - checked) > delta:
            if not oracle_reachable:
                # Fail closed: unreachable oracle is not evidence of non-revocation.
                raise StaleDelegationError(
                    f"ancestor {cid} freshness unconfirmed "
                    f"(last={checked}, delta={delta}) and oracle unreachable"
                )
            raise StaleDelegationError(
                f"ancestor {cid} freshness stale (last={checked}, delta={delta}); "
                f"re-walk required before admission"
            )

        if cursor.parent_id is None:
            break
        pid = canonical_id(cursor.parent_id)
        if pid not in chain:
            # Un-walkable chain == un-checkable chain == revoked-by-default.
            raise StaleDelegationError(
                f"chain truncated: parent {pid} of {cid} unresolved"
            )
        cursor = chain[pid]

    return True
