# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reconnects-to-an-mcp-server-over-stateless-http-and-the-resumable-sse-fallback-resumes-a-stream-whose-capability-negotia.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reconnects-to-an-mcp-server-over-stateless-http-and-the-resumable-sse-fallback-resumes-a-stream-whose-capability-negotia.warrant.json
# Markdown SHA-256:   64facc2c90b4d47d883becdc5482f91811f7bcb2e654e73e71e1f20bebaf4f57
# Code AST SHA-256:   556695df32a1d4c26b0e48302b3b2e4a6592cb005449ecfd78d106900dafa4ca
# Verified Classes:   EpochMismatchOnResume, MissingEpochOnResume, StreamIdentity
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class EpochMismatchOnResume(RuntimeError):
    """Raised when a resumable SSE stream is resumed across a capability-epoch rotation."""
    pass


class MissingEpochOnResume(EpochMismatchOnResume):
    """Raised when the client cannot prove the epoch at resume equals the epoch at request."""
    pass


@dataclass
class StreamIdentity:
    request_id: str
    last_event_id: int
    capability_epoch: str  # hash of negotiated surface, recorded at original POST
    replay_buffer: list[dict[str, Any]] = field(default_factory=list)


def capability_epoch_hash(negotiated_surface: dict[str, Any]) -> str:
    """Stable hash of the negotiated capability surface (tools, schemas, versions)."""
    canonical = json.dumps(negotiated_surface, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]


def resume_stream(
    identity: StreamIdentity,
    current_surface: dict[str, Any],
    replayed_events: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    """
    Accept a resumable SSE replay only if the capability epoch is unchanged.
    Fails closed: missing or mismatched epoch aborts the stream and forces re-issue.
    """
    if not identity.capability_epoch:
        raise MissingEpochOnResume(
            f"request {identity.request_id}: no epoch recorded at original POST; "
            f"cannot prove replay continuity for Last-Event-ID={identity.last_event_id}"
        )

    current_epoch = capability_epoch_hash(current_surface)
    if current_epoch != identity.capability_epoch:
        raise EpochMismatchOnResume(
            f"request {identity.request_id}: capability epoch rotated "
            f"({identity.capability_epoch} -> {current_epoch}) across "
            f"Last-Event-ID={identity.last_event_id}; "
            f"replayed events are not semantically continuous with the original call. "
            f"Discard replay and re-issue with idempotency key."
        )

    # Epochs match: replay is safe to stitch onto the buffered pre-drop events.
    for event in replayed_events:
        seq = event.get("id")
        if seq is None or seq <= identity.last_event_id:
            continue
        identity.replay_buffer.append(event)

    return identity.replay_buffer


def dispatch_replayed_result(identity: StreamIdentity, result_event: dict[str, Any]) -> dict[str, Any]:
    """
    Validate a replayed terminal result against the epoch-bound schema before
    handing it to the reasoning loop. This is the last guard before divergence.
    """
    if not identity.replay_buffer:
        raise EpochMismatchOnResume(
            f"request {identity.request_id}: terminal result arrived with empty replay buffer; "
            f"stream continuity cannot be established"
        )
    if result_event.get("epoch") and result_event["epoch"] != identity.capability_epoch:
        raise EpochMismatchOnResume(
            f"request {identity.request_id}: terminal event carries epoch "
            f"{result_event['epoch']} != bound epoch {identity.capability_epoch}"
        )
    return result_event
