# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-replay-as-authoritative-rather-than-as-a-superset-of-already-applied-tool-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-replay-as-authoritative-rather-than-as-a-superset-of-already-applied-tool-effects.warrant.json
# Markdown SHA-256:   b0125978c280d5959485627d4885719f0b8a06f161133f10dde8b74c0794b3b1
# Code AST SHA-256:   fbb1a60a7e94814c93ba62b0994e0144279852ea51882b549eb70196e767e1a8
# Verified Classes:   ResumptionSemanticsError, LedgerState, LedgerEntry, ResumptionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ResumptionSemanticsError(RuntimeError):
    """Raised when a resumed SSE stream delivers a tool-result event whose
    occurrence semantics cannot be resolved against the client ledger."""


class LedgerState(Enum):
    DISPATCHED = "dispatched"   # sent, no ack observed
    APPLIED = "applied"         # ack observed, effect counted once
    AMBIGUOUS = "ambiguous"     # replayed without matching token


@dataclass
class LedgerEntry:
    idempotency_token: str
    state: LedgerState
    event_ids: list[int] = field(default_factory=list)


class ResumptionLedger:
    """Durable-across-restart ledger. In production, back this with SQLite or
    a WAL file; in-memory here only for illustration. The key invariant:
    keyed by client-minted idempotency_token, NOT by SSE event id, because
    event ids are stream-scoped and reset across Mcp-Session-Id lifecycles."""

    def __init__(self, persisted: Optional[dict[str, LedgerEntry]] = None):
        self._entries: dict[str, LedgerEntry] = persisted or {}

    def record_dispatch(self, token: str) -> None:
        if token in self._entries and self._entries[token].state is LedgerState.APPLIED:
            raise ResumptionSemanticsError(
                f"token {token!r} already applied; refusing to re-dispatch"
            )
        self._entries[token] = LedgerEntry(token, LedgerState.DISPATCHED)

    def apply_replayed_result(
        self, token: Optional[str], event_id: int, non_idempotent: bool
    ) -> LedgerState:
        if token is None:
            # Server did not echo our token. We cannot tell replay from retry.
            if non_idempotent:
                raise ResumptionSemanticsError(
                    f"event {event_id}: tool-result without idempotency token on "
                    f"non-idempotent tool; reconciliation required before apply"
                )
            return LedgerState.AMBIGUOUS

        entry = self._entries.get(token)
        if entry is None:
            # Token unknown: client lost ledger or server minted a retry.
            if non_idempotent:
                raise ResumptionSemanticsError(
                    f"event {event_id}: unknown token {token!r} on non-idempotent "
                    f"tool; must read-back against authoritative state, not apply"
                )
            self._entries[token] = LedgerEntry(
                token, LedgerState.AMBIGUOUS, [event_id]
            )
            return LedgerState.AMBIGUOUS

        if entry.state is LedgerState.APPLIED:
            # Replay of an already-applied effect: suppress, do not re-count.
            entry.event_ids.append(event_id)
            return LedgerState.APPLIED

        # DISPATCHED -> APPLIED: this is the intended fast path.
        entry.state = LedgerState.APPLIED
        entry.event_ids.append(event_id)
        return LedgerState.APPLIED


def resume_stream(
    ledger: ResumptionLedger,
    replayed_events: list[dict],
    non_idempotent_tools: set[str],
) -> list[LedgerState]:
    outcomes: list[LedgerState] = []
    for ev in replayed_events:
        if ev.get("type") != "tool_result":
            outcomes.append(LedgerState.APPLIED)  # stream-only, safe
            continue
        tool = ev["tool"]
        outcomes.append(
            ledger.apply_replayed_result(
                token=ev.get("_meta", {}).get("idempotency_token"),
                event_id=ev["id"],
                non_idempotent=tool in non_idempotent_tools,
            )
        )
    return outcomes
