# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-server-initiated-elicitation-as-a-state-mutating-reentrant-call-rather-than-a-fire-and-forget-prompt.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-server-initiated-elicitation-as-a-state-mutating-reentrant-call-rather-than-a-fire-and-forget-prompt.warrant.json
# Markdown SHA-256:   eb328b83ea7592f3fec932da37bf63996596a6dc6abe121680dc1884dda3913e
# Code AST SHA-256:   569e3f3ea880aa224f2bea9d87bd701829487d74f490625e6c98076a00482017
# Verified Classes:   ElicitationFrameLost, ToolCallFrame, FrameStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ElicitationFrameLost(RuntimeError):
    """Raised when an elicitation response cannot be safely applied to agent state."""


@dataclass
class ToolCallFrame:
    correlation_id: str
    arguments: dict
    idempotent: bool

    def digest(self) -> str:
        canonical = json.dumps(self.arguments, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()


@dataclass
class FrameStore:
    """Durable store kept outside the context window; survives compaction."""
    frames: dict = field(default_factory=dict)

    def pin(self, frame: ToolCallFrame) -> None:
        self.frames[frame.correlation_id] = (frame, frame.digest())

    def verify(self, correlation_id: str, expected_digest: str) -> bool:
        entry = self.frames.get(correlation_id)
        return entry is not None and entry[1] == expected_digest


def apply_elicitation_response(
    store: FrameStore,
    correlation_id: str,
    response: str,
    context_digest: Optional[str],
    compaction_ran_during_wait: bool,
) -> str:
    """Decide whether to resume from context or re-anchor from the frame store.

    response: 'accept' | 'decline' | 'cancel'
    context_digest: digest of F0 as currently present in context (None if summarized away)
    """
    entry = store.frames.get(correlation_id)
    if entry is None:
        raise ElicitationFrameLost(
            f"no pinned frame for correlation_id={correlation_id}; "
            "cannot bind elicitation response to an in-flight call"
        )
    frame, pinned_digest = entry

    if response == "decline" or response == "cancel":
        # Terminal: synthesize an explicit cancelled result so the agent does not re-issue.
        return f"tool_result:{correlation_id}:cancelled"

    # response == 'accept'
    if frame.idempotent:
        return f"tool_result:{correlation_id}:resumed"

    # Non-idempotent: require frame identity in context AND no compaction during wait.
    if compaction_ran_during_wait:
        raise ElicitationFrameLost(
            f"compaction ran during elicitation wait for {correlation_id}; "
            "context may no longer match server-pinned arguments — must re-anchor"
        )
    if context_digest is None or not store.verify(correlation_id, context_digest):
        raise ElicitationFrameLost(
            f"frame identity check failed for {correlation_id}: "
            "context F0 does not match pinned digest — re-anchor required"
        )
    return f"tool_result:{correlation_id}:resumed"
