# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-trust-brokered-capability-attestation-whose-transitive-delegation-depth-exceeds-the-origin-warrant-s-remai.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-trust-brokered-capability-attestation-whose-transitive-delegation-depth-exceeds-the-origin-warrant-s-remai.warrant.json
# Markdown SHA-256:   063ed587c7efadbd837bd3a8d42b933c3af5f3106e62cc4fec4e5e530768ce67
# Code AST SHA-256:   a8acbf3dae48b687d1ade59ddbd436b0132dbc3f01bce8134974da522806aded
# Verified Classes:   DelegationDepthExceeded, Attestation, OriginWarrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class DelegationDepthExceeded(RuntimeError):
    """Raised when a brokered attestation consumes more hops than the origin warrant permits."""


@dataclass(frozen=True)
class Attestation:
    issuer: str
    subject: str
    capability: str
    parent_hash: str | None  # None only for the self-signed origin warrant
    asserted_remaining_depth: int
    signature_valid: bool


@dataclass(frozen=True)
class OriginWarrant:
    issuer: str
    capability: str
    max_delegation_depth: int
    pinned_key_ok: bool


def verify_brokered_attestation(
    leaf: Attestation,
    chain: list[Attestation],
    origin: OriginWarrant,
) -> None:
    """Enforce global hop-budget conservation across a brokered delegation chain.

    Reconstructs the chain from leaf back to origin, counts delegation edges,
    and rejects if the count exceeds the origin warrant's budget -- regardless
    of whether every individual signature verifies.
    """
    if not origin.pinned_key_ok:
        raise DelegationDepthExceeded(
            f"origin warrant key for {origin.issuer!r} is not pinned; refusing unverifiable root"
        )

    # Reconstruct ordered chain: origin -> ... -> leaf, following parent hashes.
    by_hash = {id(a): a for a in chain}
    ordered: list[Attestation] = [leaf]
    cursor = leaf
    while cursor.parent_hash is not None:
        parent = next(
            (a for a in chain if _hash_of(a) == cursor.parent_hash), None
        )
        if parent is None:
            raise DelegationDepthExceeded(
                f"chain unresolvable: no parent for {cursor.issuer!r} "
                f"(parent_hash={cursor.parent_hash!r})"
            )
        ordered.append(parent)
        cursor = parent
    ordered.reverse()  # now origin-first

    root = ordered[0]
    if root.issuer != origin.issuer:
        raise DelegationDepthExceeded(
            f"chain root {root.issuer!r} does not match pinned origin {origin.issuer!r}"
        )

    consumed_hops = len(ordered) - 1  # edges, not nodes
    if consumed_hops > origin.max_delegation_depth:
        offender = ordered[origin.max_delegation_depth + 1]
        raise DelegationDepthExceeded(
            f"delegation depth exceeded: consumed={consumed_hops} "
            f"budget={origin.max_delegation_depth} offending_hop={offender.issuer!r}"
        )

    # Per-hop residual consistency: asserted depth must not exceed computed residual.
    for position, node in enumerate(ordered):
        computed_residual = origin.max_delegation_depth - position
        if node.asserted_remaining_depth > computed_residual:
            raise DelegationDepthExceeded(
                f"broker arithmetic inconsistent at {node.issuer!r}: "
                f"asserted_remaining={node.asserted_remaining_depth} "
                f"computed_residual={computed_residual}"
            )

    for node in ordered:
        if not node.signature_valid:
            raise DelegationDepthExceeded(f"invalid signature at {node.issuer!r}")


def _hash_of(attestation: Attestation) -> str:
    return f"{attestation.issuer}:{attestation.subject}:{attestation.capability}:{attestation.asserted_remaining_depth}"
