# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-last-event-id-resumption-as-a-replay-of-events-not-a-replay-of-state-and-why-the-distinct.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-last-event-id-resumption-as-a-replay-of-events-not-a-replay-of-state-and-why-the-distinct.warrant.json
# Markdown SHA-256:   b05ac3595f506cdeac737b94ab2699499f54051370364e14582a0d2247d8fc7a
# Code AST SHA-256:   1d9b5abe916569c75b169b126af2f3447105b0f1bed0ebaa0ae472b8347a72e4
# Verified Classes:   ResumeGapViolation, StreamCursor
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field


class ResumeGapViolation(RuntimeError):
    """Raised when SSE resumption replays a suffix over an unapplied prefix."""


@dataclass
class StreamCursor:
    session_id: str
    last_applied_id: int          # durable, written AFTER effects committed
    applied_event_ids: set = field(default_factory=set)


def apply_resumed_event(cursor: StreamCursor, event: dict) -> None:
    """
    Enforce the resumption invariant: the first event after resume must be
    exactly last_applied_id + 1. A larger ID means the server evicted the
    gap; applying the suffix onto stale partial state silently corrupts memory.
    """
    event_id = int(event["id"])

    if event_id in cursor.applied_event_ids:
        return  # idempotent re-application; safe

    if event_id != cursor.last_applied_id + 1:
        missing = event_id - cursor.last_applied_id - 1
        raise ResumeGapViolation(
            f"session={cursor.session_id} resume replay starts at id={event_id} "
            f"but persisted applied cursor is {cursor.last_applied_id}; "
            f"{missing} events were evicted from the replay buffer. "
            f"Partial tool state for this session is now suspect: discard and "
            f"re-derive from a checkpoint predating the disconnect."
        )

    # effects committed to agent memory first, cursor advanced second
    _commit_effects(cursor, event)
    cursor.applied_event_ids.add(event_id)
    cursor.last_applied_id = event_id


def _commit_effects(cursor: StreamCursor, event: dict) -> None:
    # placeholder for progress accumulation / partial-result assembly
    _ = json.dumps(event)
