# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-tool-registry-manifest-whose-declared-capability-hash-diverges-from-its-post-load-runtime-schema-and-how-d.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-tool-registry-manifest-whose-declared-capability-hash-diverges-from-its-post-load-runtime-schema-and-how-d.warrant.json
# Markdown SHA-256:   c5b1ab2e8bf62f0abb9622c40f219a198b36960b184e43f89ba4dbefe5e842f4
# Code AST SHA-256:   f97661b9e454c0529a87981668b271c4efe43c554cb1b2bdefd97f2a6d7e4918
# Verified Classes:   ManifestSchemaDivergence, Manifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestSchemaDivergence(RuntimeError):
    """Raised when a loaded handler's runtime schema does not match its manifest."""


@dataclass(frozen=True)
class Manifest:
    name: str
    parameters: dict          # declared JSON-schema properties
    capability_hash: str      # sha256 over the DECLARED schema
    description: str


def runtime_schema_hash(handler) -> str:
    """Hash the schema the executor will actually enforce, post-parse."""
    surface = {
        "params": sorted(handler.accepted_parameters()),
        "types": {p: handler.parameter_type(p) for p in handler.accepted_parameters()},
        "doc": handler.__doc__ or "",
    }
    blob = json.dumps(surface, sort_keys=True).encode()
    return "sha256:" + hashlib.sha256(blob).hexdigest()


def verify_binding(manifest: Manifest, handler) -> None:
    declared = set(manifest.parameters)
    accepted = set(handler.accepted_parameters())

    undeclared = accepted - declared
    if undeclared:
        # Injection surface: model can be steered into params it never saw.
        raise ManifestSchemaDivergence(
            f"{manifest.name}: runtime accepts undeclared params {sorted(undeclared)}"
        )

    # Type widening: manifest says integer, runtime accepts string -> eval surface.
    for p in declared & accepted:
        if handler.parameter_type(p) != manifest.parameters[p].get("type"):
            raise ManifestSchemaDivergence(
                f"{manifest.name}: type drift on '{p}': "
                f"manifest={manifest.parameters[p].get('type')} "
                f"runtime={handler.parameter_type(p)}"
            )

    # Description drift is a prompt-injection vector through the field the model reads.
    if (handler.__doc__ or "").strip() != manifest.description.strip():
        raise ManifestSchemaDivergence(
            f"{manifest.name}: description drift between manifest and runtime docstring"
        )

    # Primary tripwire: hash must cover the runtime surface, not the declaration.
    if runtime_schema_hash(handler) != manifest.capability_hash:
        raise ManifestSchemaDivergence(
            f"{manifest.name}: capability_hash does not bind runtime schema"
        )


def load_tool(manifest: Manifest, handler) -> object:
    try:
        verify_binding(manifest, handler)
    except ManifestSchemaDivergence:
        # Remove from registry entirely; never expose a half-trusted surface.
        raise
    return handler
