# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-dynamically-loaded-skill-schema-shadowing-poisoning-at-mcp-tool-registration-time.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-dynamically-loaded-skill-schema-shadowing-poisoning-at-mcp-tool-registration-time.warrant.json
# Markdown SHA-256:   5e9a1e5b92c8f0e0fffccee45237094c70c4dcfa95799ef7f4af7002686e8aa6
# Code AST SHA-256:   b4e431cf901a8438cff520a1845298a87331a4d285a7afa4efb71d1f5d277811
# Verified Classes:   SchemaShadowingError, BoundTool
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaShadowingError(RuntimeError):
    """Raised when a dynamic skill attempts to redefine a bound tool name."""


@dataclass(frozen=True)
class BoundTool:
    name: str
    schema: dict

    @property
    def schema_hash(self) -> str:
        canonical = json.dumps(self.schema, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()


def _normalize(name: str) -> str:
    return name.lower().replace("-", "_")


def _edit_distance_le(a: str, b: str, k: int) -> bool:
    # Cheap bounded check; sufficient for near-miss quarantine.
    if abs(len(a) - len(b)) > k:
        return False
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1] <= k


def load_skill(namespace: dict[str, BoundTool], manifest: dict) -> dict[str, BoundTool]:
    """Merge a skill manifest into the live namespace under shadowing rules."""
    incoming = manifest.get("tools", [])
    staged: dict[str, BoundTool] = {}

    for tool in incoming:
        name = tool["name"]
        candidate = BoundTool(name=name, schema=tool["schema"])

        if name in namespace:
            existing = namespace[name]
            if candidate.schema_hash == existing.schema_hash:
                continue  # idempotent re-declaration
            raise SchemaShadowingError(
                f"tool '{name}' collides with bound schema "
                f"{existing.schema_hash[:12]} (incoming {candidate.schema_hash[:12]}); "
                f"refusing bundle, not merging"
            )

        for bound_name in namespace:
            if _normalize(bound_name) == _normalize(name) or _edit_distance_le(
                _normalize(bound_name), _normalize(name), 2
            ):
                raise SchemaShadowingError(
                    f"tool '{name}' is a near-miss of bound tool '{bound_name}'; "
                    f"quarantine for review"
                )

        staged[name] = candidate

    merged = dict(namespace)
    merged.update(staged)
    return merged


def handle_call(namespace: dict[str, BoundTool], name: str, schema_hash: str, args: dict):
    """Dispatch only if the caller pins the schema it was shown."""
    if name not in namespace:
        raise SchemaShadowingError(f"unbound tool '{name}'")
    bound = namespace[name]
    if bound.schema_hash != schema_hash:
        raise SchemaShadowingError(
            f"call to '{name}' pinned schema {schema_hash[:12]} but bound is "
            f"{bound.schema_hash[:12]}; binding changed since model saw it"
        )
    return {"tool": name, "args": args, "dispatched": True}
