# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-resume-state-when-an-mcp-http-native-tool-server-rotates-its-oauth-2-1-resource-indicator-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-resume-state-when-an-mcp-http-native-tool-server-rotates-its-oauth-2-1-resource-indicator-mid-stream.warrant.json
# Markdown SHA-256:   da887918929ba66c88f9547ccadaf1c82de6462062593b20b472965b6150727f
# Code AST SHA-256:   54234c06e5477748092e57d7438d0d44ecd727f5cf2020cb2ad8a889d2ee21de
# Verified Classes:   ResumeEpochMismatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumeEpochMismatch(RuntimeError):
    """Raised when an SSE resume crosses a resource-indicator epoch boundary
    without the server advertising epoch-aware replay."""
    pass


def reconcile_resume(
    last_event_id: str | None,
    resource_at_mint: str | None,
    presented_resource: str,
    pending_request_ids: set[str],
    server_caps: dict,
) -> str | None:
    """
    Decide whether to trust Last-Event-ID on reconnect.
    Returns the event ID to send, or None to force a fresh stream.
    """
    if last_event_id is None:
        return None

    if resource_at_mint is None:
        # No recorded epoch; cannot prove cursor validity.
        raise ResumeEpochMismatch(
            f"event cursor {last_event_id} has no recorded resource epoch; "
            f"presented resource={presented_resource}"
        )

    if resource_at_mint == presented_resource:
        return last_event_id

    # Epoch boundary crossed.
    if server_caps.get("streaming", {}).get("resumeAcrossEpochs") is True:
        return last_event_id

    if pending_request_ids:
        # Hard-reset is unsafe for non-idempotent calls unless caller
        # has idempotency keys; surface the decision to the caller.
        raise ResumeEpochMismatch(
            f"resource rotated {resource_at_mint} -> {presented_resource} "
            f"with {len(pending_request_ids)} pending requests "
            f"({sorted(pending_request_ids)}); replay not guaranteed, "
            f"hard-reset required"
        )

    # No pending work: safe to start fresh.
    return None
