# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-chain-whose-warrant-depth-exceeds-its-own-trust-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-chain-whose-warrant-depth-exceeds-its-own-trust-horizon.warrant.json
# Markdown SHA-256:   f7ae1531a3eaeea7492ec90c6252369b2fca334360292bca8b2960f3632b22cb
# Code AST SHA-256:   8ccebeafb09ce96d3472ed659900a3b6466fab29eb44fa63e42de193dfb344eb
# Verified Classes:   WarrantDepthError, WarrantHop
# Defensive Guards:   11 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class WarrantDepthError(RuntimeError):
    """Raised when a delegated AAIF warrant chain violates the depth/horizon invariant."""


@dataclass(frozen=True)
class WarrantHop:
    issuer: str
    subject: str
    remaining_depth: int      # absolute budget from root, decremented per hop
    scope: frozenset[str]
    parent_hash: str | None   # None only at the root-minted hop


def verify_delegated_chain(
    chain: Sequence[WarrantHop],
    trust_horizon: int,
    root_anchor: str,
) -> None:
    """Accept a chain only if root-anchored depth is monotone and within horizon.

    Raises WarrantDepthError on any violation. Returns None on success.
    """
    if not chain:
        raise WarrantDepthError("empty chain: no warrant to verify")

    # 1. Every hop must carry an absolute, root-anchored depth field.
    for i, hop in enumerate(chain):
        if hop.remaining_depth is None:
            raise WarrantDepthError(
                f"hop {i} ({hop.issuer}->{hop.subject}): DepthUnanchored — "
                "no absolute remaining_depth; relative counting is forbidden"
            )

    # 2. Root hop must be bound to a pinned anchor.
    if chain[0].issuer != root_anchor:
        raise WarrantDepthError(
            f"root issuer {chain[0].issuer!r} is not the pinned anchor {root_anchor!r}"
        )
    if chain[0].parent_hash is not None:
        raise WarrantDepthError("root hop must have parent_hash=None")

    # 3. Depth must decrement by exactly 1 per hop (no resets, no skips).
    for i in range(1, len(chain)):
        prev, cur = chain[i - 1], chain[i]
        if cur.remaining_depth != prev.remaining_depth - 1:
            raise WarrantDepthError(
                f"hop {i}: remaining_depth {cur.remaining_depth} != "
                f"{prev.remaining_depth - 1} — budget was re-initialized, not decremented"
            )
        if cur.parent_hash is None:
            raise WarrantDepthError(f"hop {i}: non-root hop missing parent_hash")

    # 4. Absolute length must not exceed the receiver's local trust horizon.
    length = len(chain)
    if length > trust_horizon:
        raise WarrantDepthError(
            f"HorizonExceeded: chain length {length} > trust horizon {trust_horizon}"
        )

    # 5. Presenting agent's own budget must be non-negative.
    if chain[-1].remaining_depth < 0:
        raise WarrantDepthError(
            f"presenting agent budget {chain[-1].remaining_depth} < 0"
        )

    # 6. Scope must be a subset of parent at every hop.
    for i in range(1, len(chain)):
        if not chain[i].scope.issubset(chain[i - 1].scope):
            raise WarrantDepthError(
                f"hop {i}: scope {set(chain[i].scope)} not subset of parent "
                f"{set(chain[i - 1].scope)}"
            )


def attenuate_and_forward(
    inbound: WarrantHop,
    next_subject: str,
    next_scope: frozenset[str],
    child_hash: str,
) -> WarrantHop:
    """Create a child hop. Refuses to forward at remaining_depth <= 1."""
    if inbound.remaining_depth <= 1:
        raise WarrantDepthError(
            f"cannot delegate from {inbound.subject}: remaining_depth "
            f"{inbound.remaining_depth} would leave child at "
            f"{inbound.remaining_depth - 1} (must be >= 1)"
        )
    if not next_scope.issubset(inbound.scope):
        raise WarrantDepthError(
            f"attenuation widened scope: {set(next_scope)} not subset of "
            f"{set(inbound.scope)}"
        )
    return WarrantHop(
        issuer=inbound.subject,
        subject=next_subject,
        remaining_depth=inbound.remaining_depth - 1,
        scope=next_scope,
        parent_hash=child_hash,
    )
