# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-capability-warrant-as-unverifiable-when-an-intermediate-agent-has-legitimately-re-scoped-its.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-capability-warrant-as-unverifiable-when-an-intermediate-agent-has-legitimately-re-scoped-its.warrant.json
# Markdown SHA-256:   b5792e6bde40f76e41675f6271360554b7ccccc720aa6d680a2515446d22b106
# Code AST SHA-256:   d0564b0dfad312934f6057a18da13ca2d75ab8bd01463e6c6c6b9ec0fbadead5
# Verified Classes:   DelegationChainError, AttenuationViolation, UnverifiableWarrant, Hop
# Defensive Guards:   10 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class DelegationChainError(RuntimeError):
    """Base for delegation-chain verification failures."""


class AttenuationViolation(DelegationChainError):
    """Child hop widens scope/actions, extends expiry, or fails depth monotonicity."""


class UnverifiableWarrant(DelegationChainError):
    """Parent payload absent or non-canonicalizable: cannot decide, must deny."""


@dataclass(frozen=True)
class Hop:
    payload: dict          # decoded warrant body for this hop
    parent_hash: str | None  # sha256 of canonical(parent.payload); None only for root
    signature: bytes
    signer_pubkey: bytes


def canonical(payload: dict) -> bytes:
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()


def hop_hash(hop: Hop) -> str:
    return hashlib.sha256(canonical(hop.payload)).hexdigest()


def _subset(child, parent) -> bool:
    if isinstance(child, dict) and isinstance(parent, dict):
        return all(k in parent and _subset(v, parent[k]) for k, v in child.items())
    if isinstance(child, list) and isinstance(parent, list):
        return set(child) <= set(parent)
    return child == parent


def assert_attenuates(child: Hop, parent: Hop) -> None:
    cp, pp = child.payload, parent.payload
    if not _subset(cp.get("resource", {}), pp.get("resource", {})):
        raise AttenuationViolation(
            f"resource scope widened at hop {cp.get('hop_id')}: "
            f"{cp.get('resource')} not subset of {pp.get('resource')}"
        )
    if not set(cp.get("actions", [])) <= set(pp.get("actions", [])):
        raise AttenuationViolation(
            f"actions widened at hop {cp.get('hop_id')}: "
            f"{cp.get('actions')} not subset of {pp.get('actions')}"
        )
    if cp.get("expiry", 0) > pp.get("expiry", 0):
        raise AttenuationViolation(
            f"expiry extended at hop {cp.get('hop_id')}: "
            f"{cp.get('expiry')} > parent {pp.get('expiry')}"
        )
    if cp.get("depth", 0) >= pp.get("depth", 0):
        raise AttenuationViolation(
            f"depth counter non-monotonic at hop {cp.get('hop_id')}: "
            f"{cp.get('depth')} >= parent {pp.get('depth')}"
        )


def verify_chain(chain: list[Hop], now: int) -> None:
    if not chain:
        raise UnverifiableWarrant("empty chain")
    for i, hop in enumerate(chain):
        if i == 0:
            if hop.parent_hash is not None:
                raise UnverifiableWarrant("root hop must not claim a parent")
            continue
        parent = chain[i - 1]
        if hop.parent_hash is None:
            raise UnverifiableWarrant(
                f"hop {hop.payload.get('hop_id')} omits parent hash; "
                "continuity is not checkable"
            )
        if hop.parent_hash != hop_hash(parent):
            raise UnverifiableWarrant(
                f"hop {hop.payload.get('hop_id')} parent hash mismatch; "
                "parent payload not in hand"
            )
        assert_attenuates(hop, parent)
    terminal = chain[-1]
    if terminal.payload.get("expiry", 0) <= now:
        raise DelegationChainError(
            f"terminal warrant expired: {terminal.payload.get('expiry')} <= {now}"
        )
    if terminal.payload.get("depth", 0) < 0:
        raise DelegationChainError("terminal depth underflow")
