# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-anchor-an-mcp-streamable-http-session-after-a-server-initiated-sse-reconnect-and-why-the-resume-token-is-not-a-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-anchor-an-mcp-streamable-http-session-after-a-server-initiated-sse-reconnect-and-why-the-resume-token-is-not-a-cursor.warrant.json
# Markdown SHA-256:   d0388d3bf2bc57c2e1d843c33bd67f9b552c49eef0048907f4b5a9d4ff2d5485
# Code AST SHA-256:   a19ddd6b6fc176211b3d6759784c3121926b159068b6ceec4c1212950e5da540
# Verified Classes:   ResumeReconciliationError, RequestState, LedgerEntry, OutboundLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ResumeReconciliationError(RuntimeError):
    """Raised when an SSE reconnect cannot be reconciled with the outbound ledger."""


class RequestState(Enum):
    PENDING = "pending"
    RESOLVED = "resolved"
    ORPHANED = "orphaned"


@dataclass
class LedgerEntry:
    jsonrpc_id: str
    state: RequestState = RequestState.PENDING
    idempotent: bool = False
    # Highest SSE event id observed when this request was issued; used to
    # decide whether a response could have been emitted before the anchor.
    issued_at_event: int = 0


@dataclass
class OutboundLedger:
    entries: Dict[str, LedgerEntry] = field(default_factory=dict)
    # Highest event id durably processed into agent state (NOT merely received).
    acknowledged_event: int = 0
    processed_server_requests: Set[str] = field(default_factory=set)

    def issue(self, jsonrpc_id: str, idempotent: bool) -> None:
        self.entries[jsonrpc_id] = LedgerEntry(
            jsonrpc_id=jsonrpc_id,
            idempotent=idempotent,
            issued_at_event=self.acknowledged_event,
        )

    def resolve(self, jsonrpc_id: str) -> None:
        entry = self.entries.get(jsonrpc_id)
        if entry is None:
            raise ResumeReconciliationError(
                f"response for unknown request id {jsonrpc_id}"
            )
        entry.state = RequestState.RESOLVED

    def acknowledge(self, event_id: int, committed: bool) -> None:
        # Refuse to advance the anchor past an uncommitted frame: receipt is
        # not processing. This is the guard against the e137 orphan gap.
        if not committed:
            raise ResumeReconciliationError(
                f"cannot acknowledge event {event_id}: payload not committed to ledger"
            )
        if event_id <= self.acknowledged_event:
            return
        self.acknowledged_event = event_id

    def reconcile_on_reconnect(self, replay_anchor: int) -> None:
        """Called on every SSE (re)connect, before processing replayed frames."""
        if replay_anchor > self.acknowledged_event:
            # Client is asking the server to replay frames it already processed;
            # that would double-deliver server-initiated requests.
            raise ResumeReconciliationError(
                f"replay anchor {replay_anchor} exceeds acknowledged "
                f"{self.acknowledged_event}; would re-execute handled events"
            )
        for entry in self.entries.values():
            if entry.state is not RequestState.PENDING:
                continue
            # If the response could have been emitted at or before the anchor,
            # it is unrecoverable by replay: mark orphaned, do not leave pending.
            if entry.issued_at_event <= replay_anchor:
                entry.state = RequestState.ORPHANED

    def resolve_orphans(self) -> None:
        for entry in self.entries.values():
            if entry.state is not RequestState.ORPHANED:
                continue
            if entry.idempotent:
                entry.state = RequestState.PENDING
                entry.issued_at_event = self.acknowledged_event
            else:
                raise ResumeReconciliationError(
                    f"non-idempotent request {entry.jsonrpc_id} orphaned by "
                    f"reconnect at event {self.acknowledged_event}; turn must fail"
                )

    def handle_server_request(self, dedup_key: str) -> bool:
        """Returns True if the handler should execute, False if this is a replay."""
        if dedup_key in self.processed_server_requests:
            return False
        self.processed_server_requests.add(dedup_key)
        return True
