# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-tokens-when-an-aaif-issuer-rotates-signing-keys-mid-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-tokens-when-an-aaif-issuer-rotates-signing-keys-mid-delegation-chain.warrant.json
# Markdown SHA-256:   77ea2211d46342713eaa3c4315d5c588c0d8daed50b44ea9ef6b960db1abf307
# Code AST SHA-256:   aa4f163100ac35a3e5e0518ae16511b4c76e4952d9e19d18a6bcb73335e66c3c
# Verified Classes:   DelegationChainError, EpochMismatchError, UnknownKeyError, DepthExhaustedError, KeyInterval, Link
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationChainError(RuntimeError):
    """Base for AAIF delegation-chain validation failures."""


class EpochMismatchError(DelegationChainError):
    """Link's authorized_by kid disagrees with the key authoritative at parent iat."""


class UnknownKeyError(DelegationChainError):
    """Parent link's kid is absent from the issuer transition log entirely."""


class DepthExhaustedError(DelegationChainError):
    """Delegation depth budget consumed; retry would compound the leak."""


@dataclass(frozen=True)
class KeyInterval:
    kid: str
    not_before: float
    not_after: float


@dataclass(frozen=True)
class Link:
    iss: str
    iat: float
    kid: str                 # key this link was signed under
    authorized_by: str       # kid the delegator claims authorized the parent
    depth_consumed: int


def authoritative_kid(iss: str, iat: float,
                      transition_log: dict[str, list[KeyInterval]]) -> Optional[str]:
    for iv in transition_log.get(iss, []):
        if iv.not_before <= iat < iv.not_after:
            return iv.kid
    return None


def validate_chain(chain: list[Link],
                   transition_log: dict[str, list[KeyInterval]],
                   max_depth: int) -> None:
    """
    Validate a delegation chain against the issuer's key-transition history.
    Raises on the first violated invariant; does NOT consume depth on failure.
    """
    if not chain:
        raise DelegationChainError("empty delegation chain")

    total_depth = 0
    for idx, link in enumerate(chain):
        # 1. The key the link was signed under must be authoritative at its own iat.
        auth = authoritative_kid(link.iss, link.iat, transition_log)
        if auth is None:
            raise UnknownKeyError(
                f"link[{idx}] iss={link.iss} iat={link.iat} has no authoritative key; "
                f"possible forged chain or rotation outran publication"
            )
        if auth != link.kid:
            raise EpochMismatchError(
                f"link[{idx}] signed under kid={link.kid} but authoritative kid at "
                f"iat={link.iat} is {auth}"
            )

        # 2. The delegator's claimed authorization key must match the parent's
        #    authoritative key at the parent's iat -- NOT the current key set.
        if idx > 0:
            parent = chain[idx - 1]
            parent_auth = authoritative_kid(parent.iss, parent.iat, transition_log)
            if parent_auth is None:
                raise UnknownKeyError(
                    f"link[{idx}] parent iss={parent.iss} has no authoritative key"
                )
            if link.authorized_by != parent_auth:
                raise EpochMismatchError(
                    f"link[{idx}] authorized_by={link.authorized_by} but parent "
                    f"authoritative kid={parent_auth}; delegator stamped a "
                    f"config-derived epoch instead of the verified kid"
                )

        total_depth += link.depth_consumed

    # 3. Depth accounting is checked last and only commits if the chain is valid.
    #    A failed validation above must not have consumed budget.
    if total_depth > max_depth:
        raise DepthExhaustedError(
            f"chain depth {total_depth} exceeds max {max_depth}; "
            f"note: if this is reached via retry, the leak is a rotation artifact, "
            f"not a policy violation -- escalate to root issuer"
        )


def handle_chain_failure(err: DelegationChainError, retries: int,
                         cache_age_s: float, overlap_window_s: float) -> str:
    """
    Decide retry / escalate / unwind. The decision boundary is error-class
    specific; treating all chain errors as transient is the failure mode.
    """
    if isinstance(err, UnknownKeyError):
        # Never retry an unknown-key chain: retry is how a stale key gets accepted.
        return "unwind"
    if isinstance(err, EpochMismatchError):
        if cache_age_s > overlap_window_s and retries < 2:
            # Only a root-level re-mint can fix this; local re-sign is wrong.
            return "escalate_root_remint"
        return "escalate_root_remint"
    if isinstance(err, DepthExhaustedError):
        # Budget leak is not recoverable by the delegating agent.
        return "escalate_root_reset_depth"
    raise DelegationChainError(f"unclassified chain failure: {err!r}")
