# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-aaif-warrant-propagation-at-the-second-hop-of-a-delegated-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-aaif-warrant-propagation-at-the-second-hop-of-a-delegated-chain.warrant.json
# Markdown SHA-256:   07b2791fdee07ea15371f7fe78d4ff46bed5ab67d0fb9643b76177e9d4258c29
# Code AST SHA-256:   aa0c688b708ead8b2b3d02919439382e508593ad342310df98493daf5973c0af
# Verified Classes:   WarrantPropagationError, CanonicalizationMismatch, AttenuationViolation, Edge
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class WarrantPropagationError(RuntimeError):
    """Raised when a derived AAIF credential cannot preserve chain continuity."""


class CanonicalizationMismatch(WarrantPropagationError):
    """Parent edge was signed under a different canonicalizer than ours."""


class AttenuationViolation(WarrantPropagationError):
    """Child capability set is not a provable subset of the parent's."""


CANON_VERSION = "aaif-canon/2"


def canonicalize(cap: dict[str, Any], version: str) -> bytes:
    if version != CANON_VERSION:
        raise CanonicalizationMismatch(
            f"cannot canonicalize under {version!r}; this agent speaks {CANON_VERSION!r}"
        )
    normalized = {
        k: sorted(v) if isinstance(v, list) else v
        for k, v in sorted(cap.items())
    }
    return json.dumps(normalized, separators=(",", ":"), sort_keys=True).encode()


def cap_hash(cap: dict[str, Any], version: str) -> str:
    return hashlib.sha256(canonicalize(cap, version)).hexdigest()


@dataclass
class Edge:
    iss: str
    sub: str
    cap_hash: str
    canon_version: str


def derive_warrant(
    parent_chain: list[Edge],
    parent_caps: dict[str, Any],
    child_caps: dict[str, Any],
    issuer: str,
    subject: str,
) -> tuple[list[Edge], str]:
    """Re-delegate parent_caps to subject as child_caps, appending one edge."""
    # 1. Every upstream edge must be recomputable under its committed canon version.
    for edge in parent_chain:
        if edge.canon_version != CANON_VERSION:
            raise CanonicalizationMismatch(
                f"edge {edge.iss}->{edge.sub} pinned to {edge.canon_version}; "
                f"refusing to re-delegate across canonicalizer boundary"
            )

    # 2. Attenuation must be a semantic subset under the SAME canonicalizer.
    parent_norm = canonicalize(parent_caps, CANON_VERSION)
    child_norm = canonicalize(child_caps, CANON_VERSION)
    if not _is_subset(child_caps, parent_caps):
        raise AttenuationViolation(
            f"child caps {child_caps!r} not a subset of parent {parent_caps!r} "
            f"under {CANON_VERSION}"
        )

    # 3. Append exactly one edge; do not re-serialize upstream edges.
    new_edge = Edge(
        iss=issuer,
        sub=subject,
        cap_hash=cap_hash(child_caps, CANON_VERSION),
        canon_version=CANON_VERSION,
    )
    return parent_chain + [new_edge], new_edge.cap_hash


def _is_subset(child: dict[str, Any], parent: dict[str, Any]) -> bool:
    # Semantic containment: every child grant must be covered by a parent grant
    # under identical normalization. Lexical prefix checks are insufficient.
    for key, child_vals in child.items():
        parent_vals = parent.get(key)
        if parent_vals is None:
            return False
        if not set(child_vals).issubset(set(parent_vals)):
            return False
    return True


def verify_chain(chain: list[Edge], presented_caps: dict[str, Any]) -> None:
    """Verifier-side check: recompute every edge hash under its pinned version."""
    for edge in chain:
        expected = cap_hash(presented_caps, edge.canon_version)
        if expected != edge.cap_hash:
            raise WarrantPropagationError(
                f"chain hash mismatch at {edge.iss}->{edge.sub}: "
                f"recomputed {expected[:12]} != committed {edge.cap_hash[:12]}"
            )
