# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-verify-tool-provenance-before-registering-a-dynamically-discovered-mcp-capability-or-capability-shadowing-silently-rewrites-its.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-verify-tool-provenance-before-registering-a-dynamically-discovered-mcp-capability-or-capability-shadowing-silently-rewrites-its.warrant.json
# Markdown SHA-256:   dd6b19bc50600a967e89382dfe97e879fb57ee2175c63e9c5e16a5de876e7d81
# Code AST SHA-256:   96ecad20c5cffc7a1180ee44442e428a698336e76b9de3de6aba7640b80e7dc1
# Verified Classes:   CapabilityShadowingError, Provenance, BoundTool
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable
import unicodedata


class CapabilityShadowingError(RuntimeError):
    """Raised when a dynamic registration would shadow or widen a bound capability."""


@dataclass(frozen=True)
class Provenance:
    root: str          # trust root identifier
    trust_rank: int    # higher = more trusted; must be monotonic on merge


@dataclass
class BoundTool:
    name: str
    schema_args: frozenset[str]
    description: str
    provenance: Provenance
    impl: Callable


def _confusable(a: str, b: str) -> bool:
    na = unicodedata.normalize("NFKC", a)
    nb = unicodedata.normalize("NFKC", b)
    if na == nb:
        return True
    # crude edit-distance-1 on normalized forms plus confusable folding
    fold = str.maketrans({"I": "l", "1": "l", "0": "o", "O": "o"})
    return na.translate(fold) == nb.translate(fold)


def register_dynamic(
    registry: dict[str, BoundTool],
    proposal: BoundTool,
    quarantine: dict[str, BoundTool],
) -> None:
    for existing_name, incumbent in registry.items():
        if existing_name == proposal.name:
            if proposal.provenance.trust_rank < incumbent.provenance.trust_rank:
                raise CapabilityShadowingError(
                    f"lower-trust source {proposal.provenance.root} attempted to "
                    f"rebind '{proposal.name}' held by {incumbent.provenance.root}"
                )
            widened = proposal.schema_args - incumbent.schema_args
            if widened:
                raise CapabilityShadowingError(
                    f"schema widening on '{proposal.name}': new args {sorted(widened)} "
                    f"require escalation, not automatic merge"
                )
            registry[proposal.name] = proposal  # narrowing update, same-or-better trust
            return
        if _confusable(existing_name, proposal.name):
            quarantine[proposal.name] = proposal
            raise CapabilityShadowingError(
                f"near-miss name '{proposal.name}' collides with bound "
                f"'{existing_name}'; quarantined pending disambiguation"
            )
    registry[proposal.name] = proposal


def select_tool(registry: dict[str, BoundTool], model_choice: str) -> BoundTool:
    if model_choice not in registry:
        raise CapabilityShadowingError(
            f"model selected '{model_choice}' which is not in the bound set; "
            f"quarantined or unregistered names are not selectable"
        )
    return registry[model_choice]
