# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-mcp-sse-stream-resumption-rather-than-replay-from-last-event-id.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-mcp-sse-stream-resumption-rather-than-replay-from-last-event-id.warrant.json
# Markdown SHA-256:   c21c9479dd86afc66d13c476a004a32e3f570d40c648c58075f81b9f58b5fb99
# Code AST SHA-256:   909893e36500233f4d584674418f5d299ebb345e2e62da669bd21120dd713316
# Verified Classes:   SSEStreamResumeUnsafe
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SSEStreamResumeUnsafe(RuntimeError):
    """Raised when Last-Event-ID resumption cannot preserve semantic continuity."""
    pass


def resume_stream(
    last_event_id: int,
    server_retained_floor: int,
    session_scoped_ids: bool,
    in_flight_tool_calls: list[dict],
) -> str:
    """
    Decide whether to resume an MCP SSE stream or abandon and re-initialize.
    Returns 'resume' or 'reinitialize'. Raises on unsafe-but-attempted resume.
    """
    if not session_scoped_ids:
        raise SSEStreamResumeUnsafe(
            f"Server uses connection-scoped event IDs; Last-Event-ID={last_event_id} "
            "is meaningless across reconnects. Must re-initialize session."
        )

    if last_event_id < server_retained_floor:
        raise SSEStreamResumeUnsafe(
            f"Resume point {last_event_id} precedes retained floor "
            f"{server_retained_floor}; events evicted under backpressure. "
            "Replay would silently drop tool results. Must re-initialize and "
            "reconcile against server state."
        )

    for call in in_flight_tool_calls:
        if not call.get("idempotency_key"):
            raise SSEStreamResumeUnsafe(
                f"In-flight tool call {call.get('id')} lacks idempotency key; "
                "a fallback retry could duplicate side effects. Must re-initialize "
                "and query authoritative tool outcome before retrying."
            )

    return "resume"


def handle_reconnect(last_event_id, floor, scoped, calls):
    try:
        action = resume_stream(last_event_id, floor, scoped, calls)
        return {"action": action, "from": last_event_id}
    except SSEStreamResumeUnsafe as e:
        return {"action": "reinitialize", "reason": str(e)}
