# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-re-attested-mcp-tool-descriptor-whose-schema-hash-matches-but-whose-inputschema-subtree-was-silently-widened.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-re-attested-mcp-tool-descriptor-whose-schema-hash-matches-but-whose-inputschema-subtree-was-silently-widened.warrant.json
# Markdown SHA-256:   d150e9a615a2c6269fdc62b0c9373ce1d5b8c7a25a9b7960d5a2e4320a78a373
# Code AST SHA-256:   32d40cc16cf40f1fb3042911975d948ec831b812ca08e3fed814bff2ccc65549
# Verified Classes:   SchemaProjectionMismatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class SchemaProjectionMismatch(RuntimeError):
    """Raised when a re-attested MCP descriptor's semantic projection
    diverges from the pinned projection despite a matching raw digest."""


def canonical_no_skip(obj: Any) -> bytes:
    # Non-lossy: do NOT skip defaults, do NOT normalize absent vs false.
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def semantic_projection(descriptor: dict) -> dict:
    schema = descriptor.get("inputSchema", {})
    props = schema.get("properties", {})
    fields = {}
    for name, spec in props.items():
        fields[name] = {
            "type": spec.get("type"),
            "enum": spec.get("enum"),
            "maxLength": spec.get("maxLength"),
            "minLength": spec.get("minLength"),
            "pattern": spec.get("pattern"),
        }
    return {
        "name": descriptor.get("name"),
        "required": sorted(schema.get("required", [])),
        # Explicit sentinel so absent != false.
        "additionalProperties": schema.get("additionalProperties", "__ABSENT__"),
        "fields": fields,
        "description_digest": hashlib.sha256(
            descriptor.get("description", "").encode()
        ).hexdigest(),
    }


def projection_hash(descriptor: dict) -> str:
    return hashlib.sha256(canonical_no_skip(semantic_projection(descriptor))).hexdigest()


def verify_refresh(pinned: dict, refreshed: dict, raw_digest_matches: bool) -> None:
    pinned_ph = projection_hash(pinned)
    refreshed_ph = projection_hash(refreshed)
    if raw_digest_matches and pinned_ph != refreshed_ph:
        raise SchemaProjectionMismatch(
            "raw descriptor digest matched but semantic projection changed: "
            f"pinned={pinned_ph[:12]} refreshed={refreshed_ph[:12]}; "
            "refusing hot-swap, holding last-good descriptor"
        )
    if not raw_digest_matches:
        raise SchemaProjectionMismatch(
            "raw digest mismatch on refresh; attestation does not cover pinned payload"
        )
