# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-policy-chain-was-re-signed-by-an-intermediate-broker.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-policy-chain-was-re-signed-by-an-intermediate-broker.warrant.json
# Markdown SHA-256:   e95141305f508746429fbf26232527eb2607c6345684057c53dfeea529783206
# Code AST SHA-256:   adfd8155bd1a29c338f4a6ae042147fe686f42996dcc6b9efc7228982952a416
# Verified Classes:   BrokerAttenuationDrop, Constraint, ChainHop, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class BrokerAttenuationDrop(RuntimeError):
    """Raised when a re-signed warrant's reconstructable policy chain is a
    strict widening of the origin's intent (constraint dropped at a broker hop)."""


@dataclass(frozen=True)
class Constraint:
    namespace: str
    name: str
    value_hash: str  # hash of canonicalized value; value itself not compared


@dataclass(frozen=True)
class ChainHop:
    issuer: str
    constraints: FrozenSet[Constraint]
    prev_hop_hash: str  # binds this hop to the preceding constraint set


@dataclass(frozen=True)
class Warrant:
    capability: str
    provenance_origin: str
    policy_chain: tuple  # tuple[ChainHop, ...]
    broker_vocabularies: dict = field(default_factory=dict)  # issuer -> set[str]


def verify_delegation_chain(
    w: Warrant,
    trusted_policy_root: dict,  # origin -> frozenset[Constraint]
) -> None:
    origin_constraints = trusted_policy_root.get(w.provenance_origin)
    if origin_constraints is None:
        raise BrokerAttenuationDrop(
            f"origin {w.provenance_origin!r} not in trusted policy root"
        )

    if not w.policy_chain:
        raise BrokerAttenuationDrop("empty policy chain; cannot reconstruct provenance")

    # Invariant 3: chain must be tamper-evident hop-to-hop.
    for i in range(1, len(w.policy_chain)):
        prev = w.policy_chain[i - 1]
        cur = w.policy_chain[i]
        if cur.prev_hop_hash != _hash_constraints(prev.constraints):
            raise BrokerAttenuationDrop(
                f"hop {i} ({cur.issuer}) not bound to preceding constraint set"
            )

    reconstructed = frozenset().union(
        *(hop.constraints for hop in w.policy_chain)
    )
    reconstructed_ids = {(c.namespace, c.name) for c in reconstructed}
    origin_ids = {(c.namespace, c.name) for c in origin_constraints}

    missing = origin_ids - reconstructed_ids
    if not missing:
        return  # faithful attenuation; proceed

    # Invariant 2: a missing constraint is only tolerable if a broker declared
    # its vocabulary gap AND refused to re-delegate. A declared gap that still
    # produced a warrant is a rejectable drop.
    for ns_name in missing:
        ns = ns_name[0]
        declared = any(
            ns in vocab for vocab in w.broker_vocabularies.values()
        )
        if declared:
            raise BrokerAttenuationDrop(
                f"broker declared ignorance of namespace {ns!r} but re-delegated "
                f"anyway; constraint {ns_name} dropped — refuse and attribute fault"
            )
        raise BrokerAttenuationDrop(
            f"constraint {ns_name} present in origin policy root but absent from "
            f"reconstructable chain; silent widening at a broker hop"
        )


def _hash_constraints(constraints: FrozenSet[Constraint]) -> str:
    import hashlib
    h = hashlib.sha256()
    for c in sorted(constraints, key=lambda x: (x.namespace, x.name, x.value_hash)):
        h.update(f"{c.namespace}:{c.name}:{c.value_hash}".encode())
    return h.hexdigest()
