# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-a-recorded-tool-trace-is-re-executed-against-a-live-mutated-tool-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-a-recorded-tool-trace-is-re-executed-against-a-live-mutated-tool-surface.warrant.json
# Markdown SHA-256:   04366dc18b44a6028333eb095c7d495c88b7bd521041eaf59cac634891601fc9
# Code AST SHA-256:   5aa0a0991f0fb4dcd65bc4c8be9943490d31db9fbcaf30a27eecbf2b43ca0271
# Verified Classes:   ReplayDivergenceError, CallRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ReplayDivergenceError(RuntimeError):
    """Raised when a replayed call's context or tool contract no longer matches the record."""


@dataclass
class CallRecord:
    tool_name: str
    input_args: dict[str, Any]
    response: Any
    response_hash: str
    schema_hash: str
    context_assembly_hash: str


def _hash(obj: Any) -> str:
    return hashlib.sha256(
        json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def replay_call(
    record: CallRecord,
    live_tool,
    live_schema: dict[str, Any],
    assembled_context: list[dict[str, Any]],
    mode: str = "live",
) -> Any:
    """Replay a single recorded call and verify the three-part fingerprint.

    mode='pinned' returns the recorded response without touching the live surface.
    mode='live' re-invokes the tool and verifies schema, response, and context hashes.
    """
    if mode == "pinned":
        return record.response

    if mode != "live":
        raise ReplayDivergenceError(f"unknown replay mode: {mode!r}")

    # Schema hash is checked FIRST: a schema change is a stronger contract
    # violation than a content change, and a lenient deserializer can mask it.
    live_schema_hash = _hash(live_schema)
    if live_schema_hash != record.schema_hash:
        raise ReplayDivergenceError(
            f"schema drift on tool {record.tool_name!r}: "
            f"recorded={record.schema_hash[:12]} live={live_schema_hash[:12]}"
        )

    live_response = live_tool(**record.input_args)
    live_response_hash = _hash(live_response)
    if live_response_hash != record.response_hash:
        raise ReplayDivergenceError(
            f"content drift on tool {record.tool_name!r}: "
            f"recorded={record.response_hash[:12]} live={live_response_hash[:12]}"
        )

    # Context-assembly hash catches truncation/serialization divergence that
    # neither schema nor response hash can detect.
    live_context_hash = _hash(assembled_context)
    if live_context_hash != record.context_assembly_hash:
        raise ReplayDivergenceError(
            f"context-assembly drift before LLM call after {record.tool_name!r}: "
            f"recorded={record.context_assembly_hash[:12]} live={live_context_hash[:12]}"
        )

    return live_response
