# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-lossless-looking-gateway-translation-between-mcp-tools-call-a2a-tasks-send-and-legacy-function-calling-json.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-lossless-looking-gateway-translation-between-mcp-tools-call-a2a-tasks-send-and-legacy-function-calling-json.warrant.json
# Markdown SHA-256:   7c170b14e1d630a5145a752977549c42f845aa7aa4968043e6590efba4bfaa65
# Code AST SHA-256:   e5905fba59744ef0539280131d8a901b7fcfd3c2d1507c63f4192da4af70c1be
# Verified Classes:   ContractLossError, ToolContractManifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Literal

Disposition = Literal["pass_through", "synthesize", "refuse_if_present", "drop_safe"]


class ContractLossError(RuntimeError):
    """Raised when a gateway translation would silently drop a contract-bearing field."""

    def __init__(self, tool: str, dropped: list[str], reason: str):
        self.tool = tool
        self.dropped = dropped
        self.reason = reason
        super().__init__(
            f"refusing lossy translation for tool={tool!r}: "
            f"contract-bearing fields {dropped} cannot be represented in target schema ({reason})"
        )


@dataclass
class ToolContractManifest:
    # Per-field disposition; anything absent defaults to refuse_if_present.
    fields: dict[str, Disposition] = field(default_factory=dict)

    def disposition(self, name: str) -> Disposition:
        return self.fields.get(name, "refuse_if_present")


def translate_mcp_call_to_legacy(
    tool: str,
    params: dict[str, Any],
    manifest: ToolContractManifest,
    target_schema_params: set[str],
) -> dict[str, Any]:
    """Translate an MCP tools/call params dict into a legacy function-call arguments dict.

    Enforces the invariant: no contract-bearing field is dropped silently.
    """
    legacy_args: dict[str, Any] = {}
    dropped_contract: list[str] = []

    # Contract-bearing top-level fields we know about.
    if "_meta" in params:
        meta = params["_meta"] or {}
        if "progressToken" in meta:
            disp = manifest.disposition("_meta.progressToken")
            if disp == "refuse_if_present":
                dropped_contract.append("_meta.progressToken")
            elif disp == "synthesize":
                # Gateway must have a heartbeat path; record intent, do not drop.
                legacy_args.setdefault("__progress_emulation__", meta["progressToken"])
            # pass_through / drop_safe: no action needed for legacy target

    output_schema = params.get("outputSchema")
    if output_schema:
        required = output_schema.get("required", [])
        disp = manifest.disposition("outputSchema")
        if required and disp == "refuse_if_present":
            dropped_contract.append(f"outputSchema.required={required}")
        elif required and disp == "synthesize":
            # Caller must have a parser; without one this is still lossy.
            if not manifest.fields.get("__has_structured_parser__"):
                dropped_contract.append(
                    f"outputSchema.required={required} (no structured parser registered)"
                )

    for key, value in (params.get("arguments") or {}).items():
        if key in target_schema_params:
            legacy_args[key] = value
        else:
            disp = manifest.disposition(key)
            if disp == "refuse_if_present":
                dropped_contract.append(f"arguments.{key}")
            elif disp == "drop_safe":
                continue
            elif disp == "synthesize":
                legacy_args[f"__passthrough__{key}"] = value

    if dropped_contract:
        raise ContractLossError(
            tool=tool,
            dropped=dropped_contract,
            reason="target schema lacks fields; default disposition is refuse_if_present",
        )

    return {"name": tool, "arguments": legacy_args}
