# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-sse-last-event-id-as-a-claim-rather-than-a-cursor-the-replay-identity-invariant-in-mcp-http-native-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-sse-last-event-id-as-a-claim-rather-than-a-cursor-the-replay-identity-invariant-in-mcp-http-native-transport.warrant.json
# Markdown SHA-256:   190478f7a8fe53f3be66dba7f6373d6ddd588beb10f9d527fc020925d71575ef
# Code AST SHA-256:   618942a32112e1a9ff800d2c4d0d1295137c4e1b4dcd503f1d553ec61e003c42
# Verified Classes:   ResumeIdentityViolation, ResumeCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class ResumeIdentityViolation(RuntimeError):
    """Raised when a resumed SSE stream cannot be reconciled with committed agent state."""


@dataclass
class ResumeCursor:
    session_id: str
    last_parsed_id: int | None = None       # volatile: set by SSE reader
    last_committed_id: int | None = None    # durable: set only after episode-log commit
    committed_ids: set[int] = field(default_factory=set)
    retention_window: int = 200

    def header_value(self) -> str | None:
        # Deliberately understate: never send an id the agent has not committed.
        return None if self.last_committed_id is None else str(self.last_committed_id)

    def commit(self, event_id: int, payload: object) -> None:
        # Caller must have durably written payload to the episode log first.
        self.last_committed_id = event_id
        self.committed_ids.add(event_id)
        if len(self.committed_ids) > self.retention_window:
            self.committed_ids.discard(min(self.committed_ids))

    def accept_replayed(self, event_id: int) -> bool:
        """Return True if this frame is a duplicate of an already-committed event."""
        if event_id in self.committed_ids:
            return True
        if self.last_committed_id is not None and event_id < self.last_committed_id:
            # Below our committed frontier but unseen: server evicted a gap.
            raise ResumeIdentityViolation(
                f"session {self.session_id}: resumed frame id {event_id} is below "
                f"committed frontier {self.last_committed_id} and was never committed; "
                f"server retention gap — reconcile via idempotency key, do not accept"
            )
        return False


def resume_stream(cursor: ResumeCursor, frames: list[tuple[int, str | None]]) -> list[int]:
    """
    frames: (event_id, terminal_marker_or_None). Returns ids the agent should process.
    Raises on ambiguous EOF or retention gaps.
    """
    if cursor.last_committed_id is None and cursor.header_value() is not None:
        raise ResumeIdentityViolation(
            f"session {cursor.session_id}: cursor header present without committed frontier"
        )

    accepted: list[int] = []
    saw_terminal = False
    for event_id, terminal in frames:
        if cursor.accept_replayed(event_id):
            continue
        accepted.append(event_id)
        if terminal is not None:
            saw_terminal = True

    if not saw_terminal:
        # A resumed stream that ends without a terminal frame is not "caught up";
        # it is an unverifiable continuation. Refuse to let the agent reason on it.
        raise ResumeIdentityViolation(
            f"session {cursor.session_id}: resumed stream ended with EOF and no terminal "
            f"frame after Last-Event-ID={cursor.header_value()}; result may have been "
            f"delivered on the lost connection — reconcile by idempotency key"
        )
    return accepted
