# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-delegated-warrant-it-can-cryptographically-verify-the-revocation-frontier-gap-in-a2a-v1-0-delegation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-delegated-warrant-it-can-cryptographically-verify-the-revocation-frontier-gap-in-a2a-v1-0-delegation-chains.warrant.json
# Markdown SHA-256:   56d4e1a1ec632a008981b6c8cd21e6417c1c236df04c04705d7c017a7eb9b1bd
# Code AST SHA-256:   86820590b3ce3e797324e939c0bdadabc0aa7748a13cdc9b3ada7f093a1ed332
# Verified Classes:   StaleAttestationError, AncestorRevokedError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a delegated warrant's revocation attestation is too old to trust."""


class AncestorRevokedError(RuntimeError):
    """Raised when an ancestor warrant in the chain has been revoked."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer_id: str
    parent_hash: Optional[str]
    scope: frozenset
    issued_at: float
    ttl: float
    attestation_ts: Optional[float]  # signed "I checked ancestors as of τ"
    signature_valid: bool

    @property
    def expires_at(self) -> float:
        return self.issued_at + self.ttl


def verify_delegated_warrant(
    w: Warrant,
    now: float,
    delta_max: float,
    min_ancestor_ttl: float,
    revocation_cache: dict,  # warrant_id -> revoked_at (or absent)
    retry_budget: int = 2,
) -> bool:
    if not w.signature_valid:
        raise AncestorRevokedError(f"signature invalid on {w.warrant_id}")
    if w.parent_hash is not None and w.parent_hash in revocation_cache:
        raise AncestorRevokedError(
            f"ancestor {w.parent_hash} revoked at {revocation_cache[w.parent_hash]}"
        )
    if now >= w.expires_at:
        raise StaleAttestationError(f"{w.warrant_id} expired at {w.expires_at}")

    if w.attestation_ts is None:
        raise StaleAttestationError(
            f"{w.warrant_id} lacks revocation attestation from {w.issuer_id}"
        )
    age = now - w.attestation_ts
    if age > delta_max:
        raise StaleAttestationError(
            f"{w.warrant_id} attestation age {age:.1f}s exceeds Δ_max {delta_max}s"
        )
    if delta_max >= min_ancestor_ttl:
        raise StaleAttestationError(
            f"Δ_max {delta_max}s not strictly below min ancestor TTL {min_ancestor_ttl}s"
        )
    return True


def invalidate_descendants(
    revoked_id: str,
    issued_graph: dict,  # issuer_id -> list[Warrant]
    revocation_cache: dict,
    now: float,
) -> list:
    """Transitive revocation: revoke every warrant whose parent chain includes revoked_id."""
    newly_revoked = []
    frontier = [revoked_id]
    while frontier:
        target = frontier.pop()
        for issuer, warrants in issued_graph.items():
            for w in warrants:
                if w.parent_hash == target and w.warrant_id not in revocation_cache:
                    revocation_cache[w.warrant_id] = now
                    newly_revoked.append(w.warrant_id)
                    frontier.append(w.warrant_id)
    return newly_revoked
