# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-renegotiated-mcp-tool-schema-when-the-server-mutates-parameters-in-place-under-a-stable-capability-token.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-renegotiated-mcp-tool-schema-when-the-server-mutates-parameters-in-place-under-a-stable-capability-token.warrant.json
# Markdown SHA-256:   4b240a96c4ef19e1a5f3a4a012798b7cb8477b2f5c0d67f22a5a939a9cb47080
# Code AST SHA-256:   57b3ecf390d25ff60a57d52794d2fab6e4deee3dfa84b7d800ce50dfccb605ff
# Verified Classes:   SchemaDriftUnrecoverable, CachedTool, DriftEvent, SchemaCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SchemaDriftUnrecoverable(RuntimeError):
    """Raised when schema drift cannot be reconciled within the retry budget."""
    pass


def canonical_schema_hash(input_schema: dict[str, Any]) -> str:
    """Content hash of a tool inputSchema, stable across key ordering."""
    canonical = json.dumps(input_schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class CachedTool:
    name: str
    schema: dict[str, Any]
    schema_hash: str = field(init=False)

    def __post_init__(self) -> None:
        self.schema_hash = canonical_schema_hash(self.schema)


@dataclass
class DriftEvent:
    tool: str
    old_hash: str
    new_hash: str
    old_schema: dict[str, Any]
    new_schema: dict[str, Any]


class SchemaCache:
    """Cache keyed by content hash, never by capability token."""

    def __init__(self) -> None:
        self._tools: dict[str, CachedTool] = {}
        self._drift_strikes: dict[str, int] = {}

    def load(self, tools: list[dict[str, Any]]) -> None:
        for t in tools:
            self._tools[t["name"]] = CachedTool(name=t["name"], schema=t["inputSchema"])

    def detect_drift(self, fresh: list[dict[str, Any]]) -> list[DriftEvent]:
        events: list[DriftEvent] = []
        for t in fresh:
            name = t["name"]
            new_hash = canonical_schema_hash(t["inputSchema"])
            cached = self._tools.get(name)
            if cached is None:
                continue  # new tool, not drift
            if cached.schema_hash != new_hash:
                events.append(
                    DriftEvent(
                        tool=name,
                        old_hash=cached.schema_hash,
                        new_hash=new_hash,
                        old_schema=cached.schema,
                        new_schema=t["inputSchema"],
                    )
                )
                self._tools[name] = CachedTool(name=name, schema=t["inputSchema"])
        return events

    def record_strike(self, tool: str) -> int:
        self._drift_strikes[tool] = self._drift_strikes.get(tool, 0) + 1
        return self._drift_strikes[tool]


def reconcile_after_invalid_params(
    cache: SchemaCache,
    tool_name: str,
    attempted_args: dict[str, Any],
    refetch_tools: Any,  # callable returning list[dict]
    max_strikes: int = 2,
) -> dict[str, Any]:
    """
    On an InvalidParams error, disambiguate 'bad args' from 'schema drift'.
    Returns rebuilt args against the live schema, or raises if drift is unrecoverable.
    """
    fresh = refetch_tools()
    events = cache.detect_drift(fresh)
    drift = next((e for e in events if e.tool == tool_name), None)

    if drift is None:
        # Schema is identical: the agent's own argument construction was at fault.
        # Do NOT loop; surface for re-planning against the known-good schema.
        raise SchemaDriftUnrecoverable(
            f"No drift for tool {tool_name!r}; argument construction was invalid. "
            f"Re-plan required, do not retry identical payload."
        )

    strikes = cache.record_strike(tool_name)
    if strikes >= max_strikes:
        raise SchemaDriftUnrecoverable(
            f"Tool {tool_name!r} drifted {strikes} times; failing closed to avoid "
            f"divergent repair loop. Old={drift.old_hash[:12]} New={drift.new_hash[:12]}"
        )

    # Rebuild args against the new schema: drop keys absent from new schema,
    # rename where a single-key delta is detectable, clamp bounds.
    new_schema = drift.new_schema
    props = new_schema.get("properties", {})
    required = set(new_schema.get("required", []))
    rebuilt = {k: v for k, v in attempted_args.items() if k in props}

    for key in required - rebuilt.keys():
        # Cannot synthesize a required value without re-planning.
        raise SchemaDriftUnrecoverable(
            f"Required property {key!r} missing after drift on {tool_name!r}; "
            f"re-plan against new schema required."
        )

    for key, spec in props.items():
        if key in rebuilt and "maximum" in spec and isinstance(rebuilt[key], (int, float)):
            rebuilt[key] = min(rebuilt[key], spec["maximum"])

    return rebuilt
