# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-at-the-aaif-trust-boundary-crossing-when-its-warrant-chain-is-re-scoped-but-not-re-signed.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-at-the-aaif-trust-boundary-crossing-when-its-warrant-chain-is-re-scoped-but-not-re-signed.warrant.json
# Markdown SHA-256:   36255d575736456866a3cfbce5f847f32e1edf9db26b9e52858a9c033e8c2e16
# Code AST SHA-256:   9c54364d3580c741895a6933026031e1557d517be9ab6022e0ef768f327030f0
# Verified Classes:   WarrantChainError, WarrantLink
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantChainError(RuntimeError):
    """Raised when an AAIF warrant chain violates monotonicity or chain-termination invariants."""


@dataclass(frozen=True)
class WarrantLink:
    issuer: str
    scope: FrozenSet[str]
    depth_remaining: int
    parent: "WarrantLink | None" = None
    translated: bool = False
    chain_terminated: bool = False


def verify_chain(leaf: WarrantLink) -> FrozenSet[str]:
    """
    Walk the chain from leaf to root, enforcing:
      1. A translated link MUST be chain-terminated (no live parent in the subset check).
      2. Every non-translated link's scope MUST be a subset of its parent's scope.
      3. Depth budget MUST be monotonically non-increasing and non-negative.
    Returns the effective (intersected) scope for the verifier.
    """
    if leaf.translated and not leaf.chain_terminated:
        raise WarrantChainError(
            f"translated link from {leaf.issuer} claims a live parent; "
            "re-scoped warrants must terminate the chain and federate, not attenuate"
        )

    effective = leaf.scope
    link = leaf
    seen_depth = leaf.depth_remaining

    while link.parent is not None:
        parent = link.parent
        if link.translated:
            # Unreachable given the guard above, but kept explicit: a translated
            # link must never enter the subset check with a parent.
            raise WarrantChainError(
                f"translated link {link.issuer}->{parent.issuer} entered subset check"
            )
        if not link.scope.issubset(parent.scope):
            raise WarrantChainError(
                f"scope escalation: {link.issuer} scope {sorted(link.scope)} "
                f"is not a subset of {parent.issuer} scope {sorted(parent.scope)}"
            )
        if link.depth_remaining > parent.depth_remaining:
            raise WarrantChainError(
                f"depth budget increased across {link.issuer}->{parent.issuer}: "
                f"{link.depth_remaining} > {parent.depth_remaining}"
            )
        effective = effective & link.scope
        link = parent

    if seen_depth < 0:
        raise WarrantChainError(f"depth budget exhausted at {leaf.issuer}: {seen_depth}")

    return effective


def handle_delegation_failure(err: Exception, current: WarrantLink) -> WarrantLink:
    """
    Retry policy: verification failures re-verify the SAME chain; only delegation
    failures re-delegate, and only from the correct parent with depth decremented once.
    """
    if isinstance(err, WarrantChainError):
        # Re-verify, do not re-delegate. Returning the same link is correct.
        return current
    if isinstance(err, TimeoutError):
        if current.depth_remaining <= 0:
            raise WarrantChainError(
                f"cannot re-delegate from {current.issuer}: depth budget exhausted"
            )
        # Re-delegate from the SAME parent, decrementing depth exactly once.
        return WarrantLink(
            issuer=current.issuer,
            scope=current.scope,
            depth_remaining=current.depth_remaining - 1,
            parent=current.parent,
            translated=current.translated,
            chain_terminated=current.chain_terminated,
        )
    raise WarrantChainError(f"unclassifiable delegation failure: {err!r}")
