# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-mcp-streamable-http-resume-tokens-as-bound-to-a-session-not-to-an-event-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-mcp-streamable-http-resume-tokens-as-bound-to-a-session-not-to-an-event-cursor.warrant.json
# Markdown SHA-256:   20b17b327daaae37209f4aecf921653958bde761d31d36b09053fbf55665d253
# Code AST SHA-256:   5f95aa77c2338a16bc98a3d5904023200b31619b23d9b4be4478908408ba1d7f
# Verified Classes:   ResumeCursorViolation, EventCursor, StreamLog
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import hmac
import time
from dataclasses import dataclass


class ResumeCursorViolation(RuntimeError):
    """Raised when a Last-Event-ID resume cannot be proven replayable on this instance."""
    pass


@dataclass(frozen=True)
class EventCursor:
    replica_id: str
    epoch: int
    seq: int

    def encode(self, secret: bytes) -> str:
        payload = f"{self.replica_id}:{self.epoch}:{self.seq}".encode()
        mac = hmac.new(secret, payload, hashlib.sha256).hexdigest()[:16]
        return f"{payload.decode()}:{mac}"


def decode_cursor(raw: str, secret: bytes) -> EventCursor:
    try:
        replica_id, epoch_s, seq_s, mac = raw.rsplit(":", 3)
    except ValueError as exc:
        raise ResumeCursorViolation(f"malformed cursor {raw!r}") from exc
    payload = f"{replica_id}:{epoch_s}:{seq_s}".encode()
    expected = hmac.new(secret, payload, hashlib.sha256).hexdigest()[:16]
    if not hmac.compare_digest(mac, expected):
        raise ResumeCursorViolation(f"cursor mac mismatch for {raw!r}")
    return EventCursor(replica_id, int(epoch_s), int(seq_s))


class StreamLog:
    def __init__(self, replica_id: str, epoch: int, secret: bytes, retain: int = 512):
        self.replica_id = replica_id
        self.epoch = epoch
        self.secret = secret
        self.retain = retain
        self._events: dict[int, dict] = {}
        self._high_water = 0

    def append(self, event: dict) -> EventCursor:
        self._high_water += 1
        self._events[self._high_water] = event
        if len(self._events) > self.retain:
            oldest = min(self._events)
            del self._events[oldest]
        return EventCursor(self.replica_id, self.epoch, self._high_water)

    def resume_from(self, raw_cursor: str) -> list[dict]:
        cursor = decode_cursor(raw_cursor, self.secret)
        if cursor.replica_id != self.replica_id or cursor.epoch != self.epoch:
            # Foreign replica or stale epoch: fail closed, never silently restart.
            raise ResumeCursorViolation(
                f"cursor {cursor} not owned by replica {self.replica_id}@epoch {self.epoch}"
            )
        if cursor.seq not in self._events and cursor.seq != self._high_water:
            # Cursor has aged out of the retained window: gap, not continuity.
            raise ResumeCursorViolation(
                f"cursor seq {cursor.seq} evicted; oldest retained {min(self._events)}"
            )
        return [self._events[s] for s in sorted(self._events) if s > cursor.seq]


def handle_resume(log: StreamLog, last_event_id: str | None, session_valid: bool) -> list[dict]:
    if not session_valid:
        raise ResumeCursorViolation("session invalid; require re-initialize")
    if last_event_id is None:
        return []  # fresh stream, no continuity claim
    try:
        return log.resume_from(last_event_id)
    except ResumeCursorViolation:
        # Surface to client as explicit resume-unavailable; do NOT fall through to "from now".
        raise
