# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-mcp-streamable-http-resumption-against-a-replayed-sse-event-id-before-it-may-treat-a-tool-call-as-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-mcp-streamable-http-resumption-against-a-replayed-sse-event-id-before-it-may-treat-a-tool-call-as-committed.warrant.json
# Markdown SHA-256:   6ae429e46b7582177e16ada8a4a7dad2e53fd6960072feec61788443485b4b5a
# Code AST SHA-256:   808f9844cd2cdc913ffb73d0a85ab053d58f59228f29fe2a8042d5ccc49107fe
# Verified Classes:   ResumptionIntegrityError, DurableTaskLog, ReplayResponse
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ResumptionIntegrityError(RuntimeError):
    """Raised when SSE resumption cannot be reconciled with durable task state."""


@dataclass
class DurableTaskLog:
    # high-water mark of *applied* events, not parsed events
    commit_cursor: int = 0
    applied: dict = field(default_factory=dict)  # event_id -> body_hash
    call_state: dict = field(default_factory=dict)  # idempotency_key -> "pending"|"committed"


@dataclass
class ReplayResponse:
    requested_last_event_id: int
    earliest_retained_id: Optional[int]  # None => server does not attest coverage
    events: list  # list of (event_id, body, body_hash)


def reconcile_resumption(
    log: DurableTaskLog,
    replay: ReplayResponse,
    pending_call_keys: list,
) -> DurableTaskLog:
    """
    Apply a resumption replay to durable state under the commit-cursor invariant.
    Raises ResumptionIntegrityError when the replay cannot be ordered or trusted.
    """
    # 1. Coverage check: can we trust an empty/partial replay?
    coverage_attested = replay.earliest_retained_id is not None
    covers_cursor = (
        coverage_attested and replay.earliest_retained_id <= log.commit_cursor + 1
    )

    if not replay.events and not covers_cursor:
        # Empty replay with no coverage attestation is ambiguous, not clean.
        # Do NOT advance commit_cursor. Force reconciliation of pending calls.
        for key in pending_call_keys:
            if log.call_state.get(key) == "pending":
                raise ResumptionIntegrityError(
                    f"ambiguous resumption: no coverage attestation and no replay "
                    f"for pending call {key!r} at cursor {log.commit_cursor}; "
                    f"must reconcile by idempotency key before re-issuing"
                )
        return log

    # 2. Order and idempotency check against the durable log.
    for event_id, body, body_hash in replay.events:
        if event_id <= log.commit_cursor:
            prior = log.applied.get(event_id)
            if prior is not None and prior != body_hash:
                # Same ID, different body: event store rebuilt / ID namespace reused.
                raise ResumptionIntegrityError(
                    f"event {event_id} replayed with divergent body "
                    f"(recorded {prior}, got {body_hash}); cannot order across rebuild"
                )
            # Idempotent re-apply: already committed, skip without re-effect.
            continue
        if event_id != log.commit_cursor + 1:
            raise ResumptionIntegrityError(
                f"gap in replay: expected {log.commit_cursor + 1}, got {event_id}"
            )
        # Apply semantic effect, THEN advance cursor.
        _apply_effect(log, body)
        log.applied[event_id] = body_hash
        log.commit_cursor = event_id

    return log


def _apply_effect(log: DurableTaskLog, body: dict) -> None:
    key = body.get("idempotency_key")
    if key and body.get("terminal"):
        log.call_state[key] = "committed"
