# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-mcp-elicitation-replies-as-untrusted-state-transitions-not-resumptions-of-a-suspended-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-mcp-elicitation-replies-as-untrusted-state-transitions-not-resumptions-of-a-suspended-call.warrant.json
# Markdown SHA-256:   657349acaed1d3811dd235d7ed5b303358336645edf311f82559525d79c04589
# Code AST SHA-256:   a58697a9a7005030b42a21065dc214eb7e02b1d2e4a863d29373572d83701e94
# Verified Classes:   ElicitationBindingError, ElicitationCheckpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ElicitationBindingError(RuntimeError):
    """Raised when an elicitation reply cannot be bound to the call that requested it."""


@dataclass(frozen=True)
class ElicitationCheckpoint:
    elicitation_id: str
    call_epoch: str
    schema_hash: str
    target: str


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


def bind_elicitation_reply(
    reply: dict,
    checkpoints: dict[str, ElicitationCheckpoint],
    current_schema: dict,
    current_call_epoch: str,
) -> ElicitationCheckpoint:
    """Validate that a reply is bound to the exact suspended call it claims to answer.

    Refuses to resume when the reply's elicitation id is unknown, when the call
    epoch has advanced, or when the tool schema was renegotiated mid-gap.
    """
    eid = reply.get("id")
    if eid not in checkpoints:
        raise ElicitationBindingError(
            f"reply references unknown or expired elicitation id {eid!r}; "
            "pending continuation must be cancelled, not resumed"
        )

    cp = checkpoints[eid]

    if cp.call_epoch != current_call_epoch:
        raise ElicitationBindingError(
            f"elicitation {eid!r} was emitted in epoch {cp.call_epoch!r} but session "
            f"is now in epoch {current_call_epoch!r}; concurrent call interleaved, "
            "reply cannot be trusted to target the original call"
        )

    if _hash_schema(current_schema) != cp.schema_hash:
        raise ElicitationBindingError(
            f"elicitation {eid!r} was presented under schema {cp.schema_hash[:12]} but "
            "tool schema changed via tools/list_changed; discard and re-elicit"
        )

    if reply.get("action") not in ("accept", "decline", "cancel"):
        raise ElicitationBindingError(
            f"elicitation {eid!r} returned unrecognized action {reply.get('action')!r}"
        )

    return cp


def resume_suspended_call(
    reply: dict,
    checkpoints: dict[str, ElicitationCheckpoint],
    current_schema: dict,
    current_call_epoch: str,
) -> dict:
    cp = bind_elicitation_reply(reply, checkpoints, current_schema, current_call_epoch)
    if reply["action"] != "accept":
        return {"status": "aborted", "target": cp.target, "reason": reply["action"]}
    return {"status": "resumed", "target": cp.target, "content": reply.get("content", {})}
