# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-mcp-session-resumption-as-a-replay-safety-problem-rather-than-a-reconnection-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-mcp-session-resumption-as-a-replay-safety-problem-rather-than-a-reconnection-problem.warrant.json
# Markdown SHA-256:   2f8a88c346f0aef906217059b00b3be2205c4148bfed9bcd976412cd7aec4269
# Code AST SHA-256:   8d9a5ed4f46c1e40e33de22baaa734b1fa509e70c73da1ffe3614efc5010f872
# Verified Classes:   ResumeScopeError, StreamCursor, ResumableSession
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ResumeScopeError(RuntimeError):
    """Raised when a resume token is applied to a stream that did not issue it."""


@dataclass
class StreamCursor:
    session_id: str
    stream_id: str
    last_event_id: str | None = None
    seen_ids: set[str] = field(default_factory=set)


class ResumableSession:
    """Enforces the invariant: a Last-Event-ID is valid only against its issuing stream."""

    def __init__(self, session_id: str):
        self.session_id = session_id
        self._cursors: dict[str, StreamCursor] = {}
        self._resume_supported: bool | None = None  # None = unprobed

    def cursor_for(self, stream_id: str) -> StreamCursor:
        return self._cursors.setdefault(
            stream_id, StreamCursor(self.session_id, stream_id)
        )

    def record_event(self, stream_id: str, event_id: str) -> bool:
        """Return True if this event is new (dispatch it), False if a replay duplicate."""
        cur = self.cursor_for(stream_id)
        cur.last_event_id = event_id
        if event_id in cur.seen_ids:
            return False
        cur.seen_ids.add(event_id)
        return True

    def resume_headers(self, stream_id: str) -> dict[str, str]:
        """Build headers for re-opening `stream_id`. Never leaks a foreign cursor."""
        cur = self._cursors.get(stream_id)
        if cur is None or cur.last_event_id is None:
            # Different stream or never held an ID: start at live head, no cursor.
            return {}
        if self._resume_supported is False:
            return {}
        return {"Last-Event-ID": cur.last_event_id}

    def on_resume_rejected(self, stream_id: str) -> None:
        """Server returned 400 to a same-stream resume: mark non-resumable, re-query."""
        self._resume_supported = False
        cur = self._cursors.get(stream_id)
        if cur is not None:
            cur.last_event_id = None

    def assert_resume_scope(self, stream_id: str, claimed_event_id: str) -> None:
        """Guard for callers that try to hand-assemble a resume token."""
        cur = self._cursors.get(stream_id)
        if cur is None:
            raise ResumeScopeError(
                f"stream {stream_id!r} has no cursor in session {self.session_id!r}"
            )
        if claimed_event_id not in cur.seen_ids and claimed_event_id != cur.last_event_id:
            raise ResumeScopeError(
                f"event {claimed_event_id!r} was never observed on stream "
                f"{stream_id!r}; refusing cross-stream resume"
            )


def reissue_post(session: ResumableSession, stream_id: str, body: dict,
                 server_honors_resume: bool) -> dict:
    """Re-issue a severed non-idempotent POST without double-executing it."""
    headers = session.resume_headers(stream_id)
    if headers and not server_honors_resume:
        # Server ignores Last-Event-ID on POST: retrying would re-run the tool.
        raise ResumeScopeError(
            f"cannot safely re-issue POST on stream {stream_id!r}: server does not "
            f"honor Last-Event-ID, non-idempotent body would be re-executed; "
            f"query side-effect status first"
        )
    return {"stream_id": stream_id, "headers": headers, "body": body}
