# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-mints-a-delegation-credential-without-re-attesting-the-parent-warrant-s-scope-predicate.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-mints-a-delegation-credential-without-re-attesting-the-parent-warrant-s-scope-predicate.warrant.json
# Markdown SHA-256:   94fda4329242a07b6ad2b1db4e1cb6c6975d85784b16c71e83247276fdaffb49
# Code AST SHA-256:   41826904b0a676f9e72c891e9e78fbb3d0ed1b371278a74a782def9c98180510
# Verified Classes:   ScopeContainmentError, Binding, Credential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable, Any


class ScopeContainmentError(RuntimeError):
    """Raised when a delegated credential's scope is not provably contained
    in its parent's scope under pinned bindings."""
    pass


@dataclass(frozen=True)
class Binding:
    name: str
    content_hash: str          # sha256 of the resolved set
    members: frozenset         # resolved members at issuance/verification


@dataclass
class Credential:
    subject: str
    issuer: str
    predicate: Callable[[dict], bool]
    predicate_src: str
    narrowing_delta: str | None          # None => re-declaration, not attenuation
    bindings: dict[str, Binding] = field(default_factory=dict)
    parent_hash: str | None = None


def _binding_fingerprint(bindings: dict[str, Binding]) -> str:
    h = hashlib.sha256()
    for name in sorted(bindings):
        h.update(name.encode())
        h.update(bindings[name].content_hash.encode())
    return h.hexdigest()


def verify_link(parent: Credential, child: Credential) -> None:
    # 1. Structural linkage
    if child.issuer != parent.subject:
        raise ScopeContainmentError(
            f"issuer/subject mismatch: child.issuer={child.issuer!r} "
            f"parent.subject={parent.subject!r}"
        )
    if child.parent_hash != _binding_fingerprint(parent.bindings):
        raise ScopeContainmentError(
            "parent_hash does not match parent's pinned binding fingerprint; "
            "chain link is dangling or bindings were swapped"
        )

    # 2. Attenuation must be proven, not asserted
    if child.narrowing_delta is None:
        raise ScopeContainmentError(
            "child credential carries no narrowing_delta: this is a "
            "re-declaration, not an attenuation. Refusing to treat a "
            "freshly-authored predicate as within parent authority."
        )

    # 3. Bindings referenced by the child must be pinned by hash, and any
    #    binding shared with the parent must agree on content hash.
    for name, b in child.bindings.items():
        if not b.content_hash:
            raise ScopeContainmentError(
                f"binding {name!r} is not content-addressed; a stale shard "
                f"could substitute a different set at verification time"
            )
        if name in parent.bindings and parent.bindings[name].content_hash != b.content_hash:
            raise ScopeContainmentError(
                f"binding {name!r} drifted between parent and child: "
                f"parent={parent.bindings[name].content_hash[:12]} "
                f"child={b.content_hash[:12]}"
            )

    # 4. Containment check: every sampled child-satisfying point must also
    #    satisfy the parent predicate under the pinned bindings.
    samples = _sample_satisfying(child.predicate, child.bindings, n=256)
    for point in samples:
        if not parent.predicate(point):
            raise ScopeContainmentError(
                f"scope containment violated: point {point!r} satisfies "
                f"child predicate ({child.predicate_src}) but not parent "
                f"predicate ({parent.predicate_src})"
            )


def _sample_satisfying(pred: Callable[[dict], bool], bindings: dict[str, Binding],
                       n: int) -> list[dict]:
    # In production this is a symbolic check over the predicate AST; here we
    # approximate with a bounded search over the pinned binding members.
    out = []
    for name, b in bindings.items():
        for member in list(b.members)[:n]:
            point = {name: member}
            if pred(point):
                out.append(point)
                if len(out) >= n:
                    return out
    return out


def delegate(parent: Credential, subject: str, child_predicate: Callable[[dict], bool],
             child_predicate_src: str, narrowing_delta: str | None,
             child_bindings: dict[str, Binding]) -> Credential:
    child = Credential(
        subject=subject,
        issuer=parent.subject,
        predicate=child_predicate,
        predicate_src=child_predicate_src,
        narrowing_delta=narrowing_delta,
        bindings=child_bindings,
        parent_hash=_binding_fingerprint(parent.bindings),
    )
    verify_link(parent, child)   # fail closed at issuance
    return child
