# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-a-session-rebind-and-silently-replays-a-truncated-json-rpc-frame.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-a-session-rebind-and-silently-replays-a-truncated-json-rpc-frame.warrant.json
# Markdown SHA-256:   8f165b84c5a5c0556f58203b3c28623d016ba518b6c06691161f91ac187bde33
# Code AST SHA-256:   6b2c735cb25ec8b5f6280abb0a9177dbcd5aaaf73e163499e959357bd7a41081
# Verified Classes:   StreamResumeTruncationError, EventFrame, ResumeCursor, McpStreamClient
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class StreamResumeTruncationError(RuntimeError):
    """Raised when MCP stream resumption would frame a truncated JSON-RPC message."""


@dataclass
class EventFrame:
    event_id: str
    data: str
    complete: bool = False


@dataclass
class ResumeCursor:
    # Cursor MUST only advance on fully-consumed, fully-framed messages.
    last_complete_event_id: Optional[str] = None
    # Partial buffer for an event we have begun but not terminated.
    partial: Optional[EventFrame] = None
    seen_ids: set[str] = field(default_factory=set)


class McpStreamClient:
    def __init__(self) -> None:
        self.cursor = ResumeCursor()

    def begin_event(self, event_id: str) -> None:
        if self.cursor.partial is not None:
            raise StreamResumeTruncationError(
                f"new event {event_id!r} began while event "
                f"{self.cursor.partial.event_id!r} was still unterminated; "
                f"framing would concatenate payloads"
            )
        if event_id in self.cursor.seen_ids:
            # Duplicate re-delivery is legal under at-least-once; ignore payload.
            self.cursor.partial = EventFrame(event_id=event_id, data="", complete=True)
            return
        self.cursor.partial = EventFrame(event_id=event_id, data="")

    def append_data(self, chunk: str) -> None:
        if self.cursor.partial is None:
            raise StreamResumeTruncationError("data chunk with no open event")
        self.cursor.partial.data += chunk

    def terminate_event(self) -> dict:
        frame = self.cursor.partial
        if frame is None:
            raise StreamResumeTruncationError("terminator with no open event")
        if frame.complete:
            # duplicate; discard
            self.cursor.partial = None
            return {}
        try:
            msg = json.loads(frame.data)
        except json.JSONDecodeError as exc:
            raise StreamResumeTruncationError(
                f"event {frame.event_id!r} data is not valid JSON after termination: {exc}"
            ) from exc
        # COMMIT POINT: only now is the cursor allowed to advance.
        self.cursor.last_complete_event_id = frame.event_id
        self.cursor.seen_ids.add(frame.event_id)
        self.cursor.partial = None
        return msg

    def resume_request(self) -> dict:
        """Build the reconnect request. Refuses to resume mid-event."""
        if self.cursor.partial is not None:
            raise StreamResumeTruncationError(
                f"cannot resume: event {self.cursor.partial.event_id!r} "
                f"is partially buffered; must re-request from last complete "
                f"event {self.cursor.last_complete_event_id!r} inclusive"
            )
        return {"Last-Event-ID": self.cursor.last_complete_event_id}

    def accept_replay(self, frames: list[EventFrame]) -> list[dict]:
        """Server must replay FULL events from the cursor inclusive."""
        out: list[dict] = []
        for f in frames:
            if not f.complete:
                raise StreamResumeTruncationError(
                    f"server replayed partial event {f.event_id!r}; "
                    f"full-event replay is required"
                )
            self.begin_event(f.event_id)
            self.append_data(f.data)
            out.append(self.terminate_event())
        return out
