# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-capability-degradation-when-an-mcp-a2a-gateway-collapses-structured-tool-schemas-into-lossy-legacy-function-call-si.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-capability-degradation-when-an-mcp-a2a-gateway-collapses-structured-tool-schemas-into-lossy-legacy-function-call-si.warrant.json
# Markdown SHA-256:   2e4a2c2e6c5b0a8a16a88d42082b885988e91593ecd3cb840bb42c999972ddce
# Code AST SHA-256:   8fb52a1c144abf62b49ac934cbf419d383c5a91ce0b9befe58dc4a14fced90fb
# Verified Classes:   CapabilityDegradationError, TranslationRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityDegradationError(RuntimeError):
    """Raised when a gateway's emitted schema accepts inputs the upstream schema would reject,
    or when an inbound call is coerced into a shape the caller did not express."""
    pass


CONSTRAINT_KEYWORDS = {"minimum", "maximum", "enum", "oneOf", "anyOf", "pattern", "required"}


def _schema_hash(schema: dict) -> str:
    return hashlib.sha256(json.dumps(schema, sort_keys=True).encode()).hexdigest()


def _collect_dropped(upstream: dict, emitted: dict, path: str = "$") -> list[str]:
    """Walk both schemas in parallel; record every constraint keyword present upstream
    but absent (or altered) in the emitted schema."""
    dropped: list[str] = []
    up_props = upstream.get("properties", {})
    em_props = emitted.get("properties", {})
    for key, up_sub in up_props.items():
        em_sub = em_props.get(key, {})
        for kw in CONSTRAINT_KEYWORDS & up_sub.keys():
            if em_sub.get(kw) != up_sub.get(kw):
                dropped.append(f"{path}.properties.{key}.{kw}")
        if up_sub.get("type") == "object":
            dropped.extend(_collect_dropped(up_sub, em_sub, f"{path}.properties.{key}"))
    for kw in CONSTRAINT_KEYWORDS & upstream.keys():
        if emitted.get(kw) != upstream.get(kw):
            dropped.append(f"{path}.{kw}")
    return dropped


@dataclass
class TranslationRecord:
    upstream_hash: str
    emitted_hash: str
    dropped: list[str]


def translate_tool(upstream_schema: dict, emitted_schema: dict, consequence: str) -> TranslationRecord:
    """Translate an MCP inputSchema into a downstream transport schema.
    Refuses lossy translation for high-consequence tools; annotates otherwise."""
    dropped = _collect_dropped(upstream_schema, emitted_schema)
    record = TranslationRecord(
        upstream_hash=_schema_hash(upstream_schema),
        emitted_hash=_schema_hash(emitted_schema),
        dropped=dropped,
    )
    if dropped and consequence == "high":
        raise CapabilityDegradationError(
            f"lossy translation of high-consequence tool; dropped constraints: {dropped}"
        )
    return record


def validate_inbound(call_args: dict, record: TranslationRecord, upstream_schema: dict) -> None:
    """Inbound path must validate against the RETAINED upstream schema, never coerce.
    Any repair attempt is a semantic guess and is treated as a hard failure."""
    if record.dropped:
        # We cannot trust the emitted schema; re-validate against upstream.
        props = upstream_schema.get("properties", {})
        for key, sub in props.items():
            if "enum" in sub and call_args.get(key) not in sub["enum"]:
                raise CapabilityDegradationError(
                    f"inbound call violates upstream enum at {key}: {call_args.get(key)!r}"
                )
            if "minimum" in sub and isinstance(call_args.get(key), (int, float)):
                if call_args[key] < sub["minimum"]:
                    raise CapabilityDegradationError(
                        f"inbound call violates upstream minimum at {key}: {call_args[key]}"
                    )
    if record.upstream_hash != record.emitted_hash and not record.dropped:
        raise CapabilityDegradationError(
            "schema hashes differ with no recorded drops; translation is unaccounted for"
        )
