# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-resurrection-in-aaif-credential-chains-when-a-mid-chain-re-delegation-outlives-its-parent-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-resurrection-in-aaif-credential-chains-when-a-mid-chain-re-delegation-outlives-its-parent-warrant.warrant.json
# Markdown SHA-256:   b457f442e9a177417452a4802b1e390790ddaac196d9a949a94a38727acd2147
# Code AST SHA-256:   6e91376252511aae1a3acc50af996991da80992c14a2c06c3e26c7c7433c8628
# Verified Classes:   DelegationResurrectionError, Warrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class DelegationResurrectionError(RuntimeError):
    """Raised when a delegated credential's authority outlives an ancestor warrant."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_id: Optional[str]
    scope: frozenset
    exp: float
    chain_expiry: Optional[float]  # signed min() over all ancestor expiries
    signature_ok: bool = True


def _hash(w: Warrant) -> str:
    return hashlib.sha256(w.warrant_id.encode()).hexdigest()


def validate(w: Warrant, revoked: set, now: Optional[float] = None) -> None:
    now = time.time() if now is None else now

    if not w.signature_ok:
        raise DelegationResurrectionError(f"bad signature on {w.warrant_id}")
    if now >= w.exp:
        raise DelegationResurrectionError(f"{w.warrant_id} expired")

    # Leaf revocation check is necessary but not sufficient.
    if _hash(w) in revoked:
        raise DelegationResurrectionError(f"{w.warrant_id} revoked")

    if w.parent_id is None:
        return  # root; issuer trust assumed established out of band

    # Invariant: a delegated warrant MUST carry a signed chain_expiry that
    # does not exceed its own exp. Absence => malformed, not "unknown".
    if w.chain_expiry is None:
        raise DelegationResurrectionError(
            f"{w.warrant_id} delegated but missing chain_expiry; "
            "stateless validation would be unsound"
        )
    if w.chain_expiry > w.exp:
        raise DelegationResurrectionError(
            f"{w.warrant_id} chain_expiry {w.chain_expiry} exceeds exp {w.exp}"
        )
    if now >= w.chain_expiry:
        # An ancestor has expired or been revoked; this leaf is a resurrection.
        raise DelegationResurrectionError(
            f"{w.warrant_id} resurrects dead ancestor authority "
            f"(chain_expiry={w.chain_expiry}, now={now})"
        )

    # If the verifier can reach the revocation set, walk the chain too.
    if w.parent_id in revoked:
        raise DelegationResurrectionError(
            f"{w.warrant_id} parent {w.parent_id} revoked"
        )


def issue_child(parent: Warrant, child_id: str, scope: frozenset,
                ttl: float, now: Optional[float] = None) -> Warrant:
    now = time.time() if now is None else now
    parent_chain = parent.chain_expiry if parent.chain_expiry is not None else parent.exp
    # Clamp: child can never outlive the shortest ancestor.
    child_exp = min(now + ttl, parent_chain)
    if not scope <= parent.scope:
        raise DelegationResurrectionError(
            f"scope {scope} not subset of parent {parent.scope}"
        )
    return Warrant(
        warrant_id=child_id,
        parent_id=_hash(parent),
        scope=scope,
        exp=child_exp,
        chain_expiry=child_exp,
    )
