# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-loaded-tool-registry-as-a-trust-boundary-rather-than-a-namespace.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-loaded-tool-registry-as-a-trust-boundary-rather-than-a-namespace.warrant.json
# Markdown SHA-256:   850a6be0e1c4b13aae5e8478efe20d20cb869d7c7d4c227735f014618ade72db
# Code AST SHA-256:   4439b4cb7e9914c6dccba7771120db6c38dfc97455011205a3c307698d0f78d7
# Verified Classes:   DescriptorDriftError, UnknownToolError, PinnedRegistry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any, Callable


class DescriptorDriftError(RuntimeError):
    """Raised when a tool call's planned descriptor no longer matches the registry."""


class UnknownToolError(LookupError):
    """Raised when a planned tool name is absent from the registry at dispatch."""


def _digest(descriptor: dict[str, Any]) -> str:
    canonical = json.dumps(descriptor, sort_keys=True, separators=(",", ":"))
    return "sha256:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()


class PinnedRegistry:
    def __init__(self) -> None:
        self._entries: dict[str, tuple[dict[str, Any], Callable[..., Any]]] = {}

    def register(self, name: str, descriptor: dict[str, Any], handler: Callable[..., Any]) -> str:
        self._entries[name] = (descriptor, handler)
        return _digest(descriptor)

    def dispatch(self, call: dict[str, Any], *args: Any, **kwargs: Any) -> Any:
        name = call.get("tool")
        planned_digest = call.get("descriptor_digest")
        if planned_digest is None:
            raise DescriptorDriftError(
                f"tool call for {name!r} carries no descriptor_digest; "
                "refusing name-only resolution"
            )
        entry = self._entries.get(name)
        if entry is None:
            raise UnknownToolError(f"tool {name!r} not present in registry at dispatch")
        descriptor, handler = entry
        current_digest = _digest(descriptor)
        if current_digest != planned_digest:
            raise DescriptorDriftError(
                f"descriptor drift for {name!r}: planned {planned_digest}, "
                f"current {current_digest}; plan is stale, re-plan required"
            )
        return handler(*args, **kwargs)


def plan_tool_call(registry: PinnedRegistry, name: str) -> dict[str, Any]:
    entry = registry._entries.get(name)
    if entry is None:
        raise UnknownToolError(f"cannot plan call to unknown tool {name!r}")
    descriptor, _ = entry
    return {"tool": name, "descriptor_digest": _digest(descriptor)}
