# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-mcp-session-id-collision-when-a-stateless-edge-multiplexes-concurrent-sse-streams-across-cold-started-replicas.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-mcp-session-id-collision-when-a-stateless-edge-multiplexes-concurrent-sse-streams-across-cold-started-replicas.warrant.json
# Markdown SHA-256:   03e90e4bd62cb0723bdd13614df37b98ff4fb65f25fd3be3384f1214bca759ef
# Code AST SHA-256:   d0a2209b64e0340f9e56f8e04f50762c951a29e323afb20027532f2c5133ac32
# Verified Classes:   SessionContinuityViolation, SessionId
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
import time
from dataclasses import dataclass


class SessionContinuityViolation(RuntimeError):
    """Raised when a replica receives a frame for a session it cannot authoritatively serve."""


@dataclass(frozen=True)
class SessionId:
    client_nonce: str
    incarnation: str
    epoch: int
    mac: str


def mint_session_id(client_nonce: str, incarnation: str, epoch: int, key: bytes) -> str:
    payload = f"{client_nonce}.{incarnation}.{epoch}".encode()
    mac = hmac.new(key, payload, hashlib.sha256).hexdigest()[:16]
    return f"{client_nonce}.{incarnation}.{epoch}.{mac}"


def parse_and_validate(raw: str, my_incarnation: str, key: bytes) -> SessionId:
    try:
        client_nonce, incarnation, epoch_s, mac = raw.split(".")
        epoch = int(epoch_s)
    except ValueError as e:
        raise SessionContinuityViolation(f"malformed session id: {raw!r}") from e

    payload = f"{client_nonce}.{incarnation}.{epoch}".encode()
    expected = hmac.new(key, payload, hashlib.sha256).hexdigest()[:16]
    if not hmac.compare_digest(mac, expected):
        raise SessionContinuityViolation(f"session id MAC mismatch: {raw!r}")

    if incarnation != my_incarnation:
        # Distinguishable from a genuine unknown session: this replica never
        # held it, and must NOT silently re-initialize counters to zero.
        raise SessionContinuityViolation(
            f"session {raw!r} belongs to incarnation {incarnation!r}, "
            f"not this replica {my_incarnation!r}; reject with 410, do not adopt"
        )
    return SessionId(client_nonce, incarnation, epoch, mac)


def allocate_progress_token(session: SessionId, external_store) -> int:
    # nextProgress MUST come from shared, lease-backed state, never from
    # a cold-started in-process counter, or token 0 is reissued to a client
    # that still holds a live token 0 from the evicted replica.
    lease = external_store.get(f"progress:{session.client_nonce}", lease_ttl_s=300)
    if lease is None or lease.epoch != session.epoch:
        raise SessionContinuityViolation(
            f"no valid progress lease for epoch {session.epoch}; "
            "refusing to reissue tokens from zero"
        )
    token = lease.next_progress
    external_store.cas_increment(f"progress:{session.client_nonce}", expected=token, to=token + 1)
    return token


def handle_frame(raw_session: str, my_incarnation: str, key: bytes, store) -> int:
    session = parse_and_validate(raw_session, my_incarnation, key)
    return allocate_progress_token(session, store)
