# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-chain-the-aaif-attenuation-gap-invariant-at-hop-depth-3.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-chain-the-aaif-attenuation-gap-invariant-at-hop-depth-3.warrant.json
# Markdown SHA-256:   fc3e4afb1dbe80689910a969f924031e2c206b47ef1858c417e753d581095c6d
# Code AST SHA-256:   baaf7fd08af0560f2f045b04b4683d4bb4042e6212483f4b5434d41fa724bf1b
# Verified Classes:   AttenuationGapError, Warrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class AttenuationGapError(RuntimeError):
    """Raised when a delegated credential chain cannot prove constraint preservation."""
    pass


@dataclass
class Warrant:
    hop_id: str
    scope: frozenset
    constraints: dict
    parent_constraints_hash: str | None  # H(parent.constraints) committed in the signed proof
    signature_valid: bool = True


def _constraints_hash(constraints: dict) -> str:
    canonical = json.dumps(constraints, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def _at_least_as_restrictive(child: dict, parent: dict) -> bool:
    """child ⊒ parent: every parent constraint preserved and not loosened."""
    for key, parent_val in parent.items():
        if key not in child:
            return False
        child_val = child[key]
        if isinstance(parent_val, bool):
            if parent_val and not child_val:
                return False
        elif isinstance(parent_val, (int, float)):
            if child_val > parent_val:  # larger budget = weaker
                return False
        elif isinstance(parent_val, (list, set, tuple)):
            if not set(parent_val).issubset(set(child_val)):
                return False
        elif isinstance(parent_val, str):
            if child_val != parent_val:
                return False
        else:
            if child_val != parent_val:
                return False
    return True


def verify_chain(chain: list[Warrant]) -> None:
    """Admit a delegated chain only if scope inclusion AND constraint meet both hold."""
    if not chain:
        raise AttenuationGapError("empty chain")

    root = chain[0]
    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]

        if not child.signature_valid:
            raise AttenuationGapError(f"hop {child.hop_id}: invalid signature")

        # Condition 1: scope inclusion (AAIF v1.2 enforces this).
        if not child.scope.issubset(parent.scope):
            raise AttenuationGapError(
                f"hop {child.hop_id}: scope {child.scope} not subset of {parent.scope}"
            )

        # Condition 3: the child must commit to the parent's constraint block.
        expected_parent_hash = _constraints_hash(parent.constraints)
        if child.parent_constraints_hash is None:
            raise AttenuationGapError(
                f"hop {child.hop_id}: no H(parent.constraints) commitment; "
                f"constraint preservation unverifiable — refusing chain"
            )
        if child.parent_constraints_hash != expected_parent_hash:
            raise AttenuationGapError(
                f"hop {child.hop_id}: parent-constraint hash mismatch "
                f"(reconstruction detected) — refusing chain"
            )

        # Condition 2: constraint meet must be at least as restrictive.
        if not _at_least_as_restrictive(child.constraints, parent.constraints):
            raise AttenuationGapError(
                f"hop {child.hop_id}: constraints {child.constraints} "
                f"not ⊒ {parent.constraints} — attenuation gap"
            )

    # Final invariant: leaf meet must equal the root's declared constraints.
    leaf_meet = chain[-1].constraints
    if not _at_least_as_restrictive(leaf_meet, root.constraints):
        raise AttenuationGapError(
            "leaf constraint meet weaker than root declaration — refusing admission"
        )
