# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-manifest-level-skill-injection-when-a-trusted-mcp-registry-entry-is-silently-re-published-with-an-expanded-tool-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-manifest-level-skill-injection-when-a-trusted-mcp-registry-entry-is-silently-re-published-with-an-expanded-tool-surface.warrant.json
# Markdown SHA-256:   b065033a07876fddfe4d4b5be6ae163908e3b35c63904eded3c2a87bd7fab00a
# Code AST SHA-256:   7b19f38ed90887e8f91c9ee4baec6cf456b17b0cf2b22487fc571f2505282aa8
# Verified Classes:   CapabilityDriftError, ToolBinding
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class CapabilityDriftError(RuntimeError):
    """Raised when a re-resolved tool manifest widens the expressible action surface."""


@dataclass(frozen=True)
class ToolBinding:
    name: str
    publisher_did: str
    capability_digest: str


def _canonical_tool_digest(tools: list[dict[str, Any]]) -> str:
    # Canonicalize: sort tools by name, sort schema keys, hash the whole surface.
    # This intentionally captures schema widening and description drift, not just names.
    normalized = []
    for t in sorted(tools, key=lambda x: x["name"]):
        normalized.append({
            "name": t["name"],
            "schema": json.dumps(t["inputSchema"], sort_keys=True, separators=(",", ":")),
            "desc": hashlib.sha256(t.get("description", "").encode()).hexdigest(),
        })
    blob = json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def _is_widening(prev_tools: list[dict[str, Any]], new_tools: list[dict[str, Any]]) -> bool:
    prev = {t["name"]: t for t in prev_tools}
    for t in new_tools:
        old = prev.get(t["name"])
        if old is None:
            return True  # new tool appeared
        old_schema, new_schema = old["inputSchema"], t["inputSchema"]
        if new_schema.get("additionalProperties") is True and old_schema.get("additionalProperties") is not True:
            return True
        old_props = set(old_schema.get("properties", {}))
        new_props = set(new_schema.get("properties", {}))
        if new_props - old_props:
            return True  # schema gained expressible fields
    return False


def bind_manifest(
    manifest: dict[str, Any],
    last_approved: ToolBinding | None,
    approved_digests: set[str],
) -> ToolBinding:
    digest = _canonical_tool_digest(manifest["tools"])

    if last_approved is None:
        if digest not in approved_digests:
            raise CapabilityDriftError(
                f"first bind of {manifest['name']}@{manifest['semver']} has digest {digest} "
                f"not present in approved set; require out-of-band approval"
            )
        return ToolBinding(manifest["name"], manifest["publisher_did"], digest)

    if digest == last_approved.capability_digest:
        return last_approved  # identity AND capability continuity

    # Identity matched (caller already verified name+DID+semver) but content drifted.
    if _is_widening(manifest.get("_prev_tools", []), manifest["tools"]):
        raise CapabilityDriftError(
            f"capability widening on {manifest['name']}@{manifest['semver']}: "
            f"{last_approved.capability_digest} -> {digest}; binding refused pending re-approval"
        )

    if digest not in approved_digests:
        raise CapabilityDriftError(
            f"non-widening drift on {manifest['name']}@ {manifest['semver']} unapproved: {digest}"
        )
    return ToolBinding(manifest["name"], manifest["publisher_did"], digest)
