# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-self-declared-capability-manifest-the-manifest-digest-tool-binding-divergence-boundary-in-skill-injection-detection.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-self-declared-capability-manifest-the-manifest-digest-tool-binding-divergence-boundary-in-skill-injection-detection.warrant.json
# Markdown SHA-256:   b888eaabd0819e9c921290afa1f193e460993f5163a3c11641a3af0a0e5916f4
# Code AST SHA-256:   66173ce3d4d240d87ebf952235dc02cd41492c5a55181c0690361a0805be024b
# Verified Classes:   BindingIntegrityError, Manifest, ResolvedBinding
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class BindingIntegrityError(RuntimeError):
    """Raised when a verified manifest does not cover the runtime binding it resolves to."""


@dataclass
class Manifest:
    raw_bytes: bytes
    schema_ref: str | None = None          # mutable indirection, NOT covered by digest
    endpoint_hint: str | None = None       # name, resolved by discovery, NOT covered
    tool_ids: list[str] = field(default_factory=list)


@dataclass
class ResolvedBinding:
    endpoint_identity: str
    schema_bytes: bytes
    tool_ids: tuple[str, ...]


def verify_and_bind(
    manifest: Manifest,
    pinned_digest: str,
    resolve_endpoint,
    deref_schema,
    pinned_binding_digest: str | None,
) -> ResolvedBinding:
    # Step 1: document integrity. Necessary, not sufficient.
    doc_digest = hashlib.sha256(manifest.raw_bytes).hexdigest()
    if doc_digest != pinned_digest:
        raise BindingIntegrityError(
            f"manifest document digest mismatch: {doc_digest} != {pinned_digest}"
        )

    # Step 2: dereference EVERY indirection before trusting anything.
    endpoint_identity = resolve_endpoint(manifest.endpoint_hint) if manifest.endpoint_hint else ""
    schema_bytes = deref_schema(manifest.schema_ref) if manifest.schema_ref else b""

    binding = ResolvedBinding(
        endpoint_identity=endpoint_identity,
        schema_bytes=schema_bytes,
        tool_ids=tuple(sorted(manifest.tool_ids)),
    )

    # Step 3: the binding itself must be pinned. A passing document digest
    # over a manifest with indirections proves nothing about the binding.
    if manifest.schema_ref or manifest.endpoint_hint:
        if pinned_binding_digest is None:
            raise BindingIntegrityError(
                "manifest contains unverified indirection (schema_ref/endpoint_hint) "
                "but no pinned binding digest; refusing to bind injected skill"
            )
        binding_digest = hashlib.sha256(
            binding.endpoint_identity.encode()
            + b"\x00"
            + binding.schema_bytes
            + b"\x00"
            + b"\x1f".join(t.encode() for t in binding.tool_ids)
        ).hexdigest()
        if binding_digest != pinned_binding_digest:
            raise BindingIntegrityError(
                f"resolved binding digest {binding_digest} != pinned {pinned_binding_digest}; "
                "document verified but dispatch target drifted"
            )

    return binding
