# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-sse-last-event-id-resumption-as-a-new-logical-stream-rather-than-a-continuation-and-how-does-silent-event-id-namesp.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-sse-last-event-id-resumption-as-a-new-logical-stream-rather-than-a-continuation-and-how-does-silent-event-id-namesp.warrant.json
# Markdown SHA-256:   15b81f9e89367909a376a735b842edd4d7e64c65c9ae139cfc4e5048b20fc655
# Code AST SHA-256:   63f79f87b0504ce4ee78c8ecb69b8f33546c69e3f6b8502486e3a332666ca10e
# Verified Classes:   StreamGenerationMismatch, StreamLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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

class StreamGenerationMismatch(RuntimeError):
    """Raised when a Last-Event-ID cursor cannot be proven to belong to the
    stream generation the server is about to serve. Resumption MUST be refused;
    the client must cold-start and re-drive pending tool calls."""
    pass

@dataclass
class StreamLog:
    generation: str = field(default_factory=lambda: uuid.uuid4().hex)
    events: list = field(default_factory=list)   # list of (event_id:int, payload:dict)
    retention_floor: int = 0

    def head(self) -> int:
        return self.events[-1][0] if self.events else 0

    def emit(self, payload: dict) -> int:
        eid = self.head() + 1
        self.events.append((eid, payload))
        return eid

    def resume(self, last_generation: str, last_event_id: int) -> list:
        # Invariant: cursor is only meaningful relative to a generation.
        if last_generation != self.generation:
            raise StreamGenerationMismatch(
                f"cursor generation {last_generation!r} != current "
                f"{self.generation!r}; refusing silent resumption"
            )
        if last_event_id > self.head():
            # Cursor ahead of head is impossible within one log -> different log.
            raise StreamGenerationMismatch(
                f"cursor {last_event_id} ahead of head {self.head()}; "
                f"server cannot honor as continuation"
            )
        if last_event_id < self.retention_floor:
            raise StreamGenerationMismatch(
                f"cursor {last_event_id} below retention floor "
                f"{self.retention_floor}; replay impossible"
            )
        return [p for (eid, p) in self.events if eid > last_event_id]

def handle_reconnect(log: StreamLog, last_generation: Optional[str],
                     last_event_id: Optional[int]) -> dict:
    if last_event_id is None:
        return {"action": "fresh_subscribe", "generation": log.generation}
    try:
        replayed = log.resume(last_generation or "", last_event_id)
    except StreamGenerationMismatch as e:
        # Loud, actionable signal instead of monotonic lie.
        return {"action": "resync.required",
                "reason": str(e),
                "current_generation": log.generation,
                "must_redrive_pending_calls": True}
    return {"action": "resume", "replayed": replayed,
            "generation": log.generation}
