# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-last-event-id-resumption-against-mcp-streamable-session-state-after-a-transport-level-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-last-event-id-resumption-against-mcp-streamable-session-state-after-a-transport-level-reconnect.warrant.json
# Markdown SHA-256:   6b6183d20068cfcc25691aed5ab1e75979343599d0728cc4af5c6a2266d40148
# Code AST SHA-256:   91cf84ff25967f0d12950acdd43e6f6f910adcdfb8f26475c2daa8b054281f22
# Verified Classes:   SessionResumptionViolation, ReconnectReconciler
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SessionResumptionViolation(RuntimeError):
    """Raised when SSE reconnect success is mistaken for MCP session survival."""
    pass


class ReconnectReconciler:
    """
    Reconciles SSE Last-Event-ID replay against MCP session identity.

    Invariant enforced: replayed events are applied to workflow state ONLY
    after a state-discriminating probe confirms the session instance survived.
    """

    def __init__(self, client, session_id, expected_cursor):
        self.client = client
        self.session_id = session_id
        self.expected_cursor = expected_cursor
        self.holding = []          # replayed events awaiting confirmation
        self.confirmed = False

    def on_reconnect(self, last_event_id, replayed_events):
        # SSE layer says "resumed"; we do NOT trust it yet.
        self.holding.extend(replayed_events)
        probe = self.client.tools_list(cursor=self.expected_cursor,
                                       session_id=self.session_id)
        # A fresh/phantom session cannot honor a cursor minted by a dead one.
        if probe.get("cursor_echo") != self.expected_cursor:
            raise SessionResumptionViolation(
                f"session {self.session_id} re-created empty after reconnect; "
                f"cursor {self.expected_cursor!r} not honored "
                f"(got {probe.get('cursor_echo')!r}); "
                f"{len(self.holding)} replayed events discarded, session reset required"
            )
        # Identity confirmed: safe to apply held events in ID order.
        self.holding.sort(key=lambda e: e["id"])
        for ev in self.holding:
            self.client.apply_event(ev)
        self.holding.clear()
        self.confirmed = True

    def apply_or_hold(self, event):
        if self.confirmed:
            self.client.apply_event(event)
        else:
            # Stream is open but identity unproven: never apply directly.
            self.holding.append(event)
