# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-capability-token-past-the-depth-its-attestation-chain-can-prove.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-capability-token-past-the-depth-its-attestation-chain-can-prove.warrant.json
# Markdown SHA-256:   928931e1de493d5f06463ce1f4191d65e621481fc116e6c3688064eef7312439
# Code AST SHA-256:   ee296dd48872be99be9a0c491c61674d167c8403fb7e75d1d434f1301739ac1d
# Verified Classes:   DelegationDepthUnprovable, Attestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationDepthUnprovable(RuntimeError):
    """Raised when an instance cannot derive remaining delegation depth from the
    parent token's signed payload, and therefore must not mint a child token."""


@dataclass(frozen=True)
class Attestation:
    delegatee: str
    token_digest: str
    parent_digest: Optional[str]
    # remaining_depth MUST be inherited-and-decremented, never restated.
    remaining_depth: Optional[int]
    signature_valid: bool


def mint_child(
    parent: Attestation,
    child_delegatee: str,
    child_token_digest: str,
    root_max_depth: int,
) -> Attestation:
    # Step 1: local signature check is necessary but NOT sufficient.
    if not parent.signature_valid:
        raise DelegationDepthUnprovable(
            f"parent attestation for {parent.delegatee} failed signature check"
        )

    # Step 2: the depth budget must be derivable from the signed payload.
    # If the parent restated an opaque depth or omitted the field, we cannot
    # prove the child hop is within the root principal's budget.
    if parent.remaining_depth is None:
        raise DelegationDepthUnprovable(
            f"parent {parent.delegatee} carries no provable remaining_depth; "
            "refusing to mint child hop (would be unverifiable downstream)"
        )

    # Step 3: decrement, do not restate. A zero budget cannot delegate further.
    if parent.remaining_depth <= 0:
        raise DelegationDepthUnprovable(
            f"parent {parent.delegatee} has remaining_depth="
            f"{parent.remaining_depth}; delegation budget exhausted "
            f"(root max={root_max_depth})"
        )

    child_remaining = parent.remaining_depth - 1
    if child_remaining < 0:
        # Defensive: unreachable given the check above, but the invariant is
        # explicit so a future refactor cannot silently drop it.
        raise DelegationDepthUnprovable(
            "computed child remaining_depth < 0; invariant violated"
        )

    return Attestation(
        delegatee=child_delegatee,
        token_digest=child_token_digest,
        parent_digest=parent.token_digest,
        remaining_depth=child_remaining,
        signature_valid=True,
    )


def verify_chain(chain: list[Attestation], root_max_depth: int) -> None:
    """Terminal verifier: reconstruct depth from the chain, not from claims."""
    if not chain:
        raise DelegationDepthUnprovable("empty attestation chain")

    expected = root_max_depth
    for hop in chain:
        if hop.remaining_depth != expected:
            raise DelegationDepthUnprovable(
                f"hop {hop.delegatee}: remaining_depth={hop.remaining_depth} "
                f"but chain-derived depth={expected}; provenance broken"
            )
        expected -= 1
