# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-re-delegated-aaif-warrant-whose-attenuation-chain-is-monotone-in-scope-but-non-monotone-in-delegation-depth.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-re-delegated-aaif-warrant-whose-attenuation-chain-is-monotone-in-scope-but-non-monotone-in-delegation-depth.warrant.json
# Markdown SHA-256:   7e76c55dd8a493efe32616d2b71a24004a1f2fcf9f674262468c9e4323ba14e8
# Code AST SHA-256:   14a5fa01f628e9764eee37a699f69ef7bec905e2460cd78648bd109ed19caaaa
# Verified Classes:   WarrantAttenuationError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantAttenuationError(RuntimeError):
    """Raised when an AAIF warrant chain violates an attenuation invariant."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: frozenset[str]
    asserted_depth: int          # issuer-supplied; must NOT be trusted as the bound
    parent_id: Optional[str]


def validate_chain(chain: list[Warrant], root_depth: int) -> dict[str, int]:
    """
    Validate an AAIF attenuation chain on BOTH axes.

    Scope axis:  caps(child) must be a subset of caps(parent).
    Depth axis:  derived_depth(child) must be derived_depth(parent) - 1,
                 and the child's asserted_depth must not exceed the derived value.

    Returns a map of subject -> derived_depth for the accepted chain.
    Raises WarrantAttenuationError on any violation.
    """
    if not chain:
        raise WarrantAttenuationError("empty warrant chain")

    derived: dict[str, int] = {}
    derived[chain[0].issuer] = root_depth

    for i, w in enumerate(chain):
        parent_depth = derived.get(w.issuer)
        if parent_depth is None:
            raise WarrantAttenuationError(
                f"hop {i}: issuer {w.issuer!r} not present in derived chain"
            )

        # Depth axis: derive, do not accept the assertion.
        expected_depth = parent_depth - 1
        if expected_depth < 0:
            raise WarrantAttenuationError(
                f"hop {i}: delegation budget exhausted at {w.issuer!r}"
            )
        if w.asserted_depth > expected_depth:
            raise WarrantAttenuationError(
                f"hop {i}: asserted_depth={w.asserted_depth} exceeds derived "
                f"bound {expected_depth} for subject {w.subject!r} "
                f"(depth-non-monotone delegation)"
            )

        # Scope axis: child scope must be a subset of parent scope.
        if i > 0:
            parent_scope = chain[i - 1].scope
            if not w.scope.issubset(parent_scope):
                raise WarrantAttenuationError(
                    f"hop {i}: scope {set(w.scope)} not a subset of parent "
                    f"scope {set(parent_scope)}"
                )

        derived[w.subject] = expected_depth

    return derived


def honor_incoming(warrant: Warrant, received_depth: int) -> None:
    """
    Local instance-side check: refuse a warrant whose asserted depth is not
    strictly less than the depth this instance itself received.
    """
    if warrant.asserted_depth >= received_depth:
        raise WarrantAttenuationError(
            f"refusing warrant to {warrant.subject!r}: asserted_depth="
            f"{warrant.asserted_depth} is not strictly less than received "
            f"depth {received_depth}; local monotonicity violated"
        )
