# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-stream-resumption-has-silently-replayed-a-non-idempotent-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-stream-resumption-has-silently-replayed-a-non-idempotent-tool-call.warrant.json
# Markdown SHA-256:   f7038c1b08229b4b5ee32cfbd68bcd516f53e893e05465dfe230be68db738c62
# Code AST SHA-256:   73e8563e729c8efe9a1437d592af11aeafe507c0dddc1ec014f053553014a415
# Verified Classes:   ResumptionIntegrityError, SessionEpoch, PendingCall
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ResumptionIntegrityError(RuntimeError):
    """Raised when a stream resumption cannot be proven safe for a non-idempotent call."""


@dataclass
class SessionEpoch:
    session_id: str
    epoch: str
    durable: bool
    ids_session_global: bool


@dataclass
class PendingCall:
    tool: str
    arguments: dict[str, Any]
    idempotency_key: str
    last_event_id: int | None = None
    executed: bool = False


def make_idempotency_key(tool: str, arguments: dict[str, Any], call_seq: int) -> str:
    payload = json.dumps(
        {"tool": tool, "args": arguments, "seq": call_seq},
        sort_keys=True,
        separators=(",", ":"),
    ).encode()
    return hashlib.sha256(payload).hexdigest()


def resume_stream(
    epoch_at_connect: SessionEpoch,
    epoch_at_resume: SessionEpoch,
    pending: PendingCall,
    server_supports_dedup: bool,
) -> str:
    """Decide whether to resume via Last-Event-ID or re-issue with an idempotency key.

    Returns a decision token: "resume" or "reissue".
    """
    if not pending.executed:
        # Nothing has fired yet; resumption is always safe.
        return "resume"

    # A tool call already executed. Resumption now risks replaying its side effect.
    epoch_changed = epoch_at_connect.epoch != epoch_at_resume.epoch
    session_lost = epoch_at_connect.session_id != epoch_at_resume.session_id
    ids_unsafe = not epoch_at_resume.ids_session_global
    store_unsafe = not epoch_at_resume.durable

    resumption_unsafe = epoch_changed or session_lost or ids_unsafe or store_unsafe

    if resumption_unsafe and not server_supports_dedup:
        raise ResumptionIntegrityError(
            f"cannot safely resume executed call {pending.tool!r} "
            f"(key={pending.idempotency_key[:12]}...): "
            f"epoch_changed={epoch_changed} session_lost={session_lost} "
            f"ids_unsafe={ids_unsafe} store_unsafe={store_unsafe} "
            f"and server does not deduplicate on idempotency keys"
        )

    if resumption_unsafe and server_supports_dedup:
        # Safe to re-issue: the server will suppress the duplicate.
        return "reissue"

    return "resume"
