# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-fresh-subscription-rather-than-a-gap-fill-and-why-silent-replay-loss-fol.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-fresh-subscription-rather-than-a-gap-fill-and-why-silent-replay-loss-fol.warrant.json
# Markdown SHA-256:   c38abdbf9a5a2b7cd805499e8ff4280f822fa124a54c653121e7ab00b5e40258
# Code AST SHA-256:   9bd3267376bd8ff19dbd357af393c97a2550c75bc1ece9d0b920b35846dfdf0a
# Verified Classes:   ReplayCursorUnverifiable
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ReplayCursorUnverifiable(RuntimeError):
    """Raised when a resume cursor cannot be proven to belong to the
    current serving epoch's replay window. Must NOT be swallowed into a
    silent gap-fill; the client must be told the gap exists."""
    pass


def resolve_resume(cursor: str, current_epoch: str, floor_seq: int, head_seq: int) -> str:
    """
    cursor format: "<epoch>:<seq>"
    Returns one of: "gap-fill", "fresh-subscription".
    Raises ReplayCursorUnverifiable when the cursor is ahead of head or
    from a different epoch -- i.e. when it *looks* caught up but isn't.
    """
    try:
        epoch, seq_s = cursor.split(":", 1)
        seq = int(seq_s)
    except (ValueError, AttributeError) as exc:
        raise ReplayCursorUnverifiable(f"malformed Last-Event-ID: {cursor!r}") from exc

    if epoch != current_epoch:
        # Different process lifetime / counter namespace. The cursor is not
        # orderable against our head; treating it as "ahead" would silently
        # drop every event between the two epochs.
        raise ReplayCursorUnverifiable(
            f"cursor epoch {epoch!r} != serving epoch {current_epoch!r}; "
            f"resume is a fresh subscription, not a gap-fill"
        )

    if seq > head_seq:
        # Same epoch but ahead of head: impossible under a monotonic counter
        # unless the client is lying or state was lost. Refuse to attach.
        raise ReplayCursorUnverifiable(
            f"cursor seq {seq} > head {head_seq} in epoch {current_epoch!r}"
        )

    if seq < floor_seq - 1:
        # Evicted below the replay floor: a real gap exists. Caller must
        # emit an explicit replay-gap marker, not clamp silently.
        raise ReplayCursorUnverifiable(
            f"cursor seq {seq} below replay floor {floor_seq - 1}; "
            f"gap of {floor_seq - 1 - seq} events must be surfaced"
        )

    return "gap-fill"


def handle_resume(cursor: str, session: dict) -> dict:
    try:
        mode = resolve_resume(
            cursor,
            current_epoch=session["epoch"],
            floor_seq=session["floor"],
            head_seq=session["head"],
        )
    except ReplayCursorUnverifiable as exc:
        # Loud, bounded failure. Client re-derives state; nothing silently lost.
        return {"action": "replay-gap", "reason": str(exc), "resume_from": cursor}
    return {"action": mode, "replay": session["events"][int(cursor.split(":")[1]) + 1:]}
