# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-checkpoint-relative-to-a-lossy-compaction-boundary-to-guarantee-recoverable-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-checkpoint-relative-to-a-lossy-compaction-boundary-to-guarantee-recoverable-state.warrant.json
# Markdown SHA-256:   d0293b03ebf220d544aa0d98cf2e78615108b5ad8e1f3f05f1270d308f31f122
# Code AST SHA-256:   cfbd304935cc28950b717af1e829fd48d2168f2cad229f6081c888f2e5702023
# Verified Classes:   RecoveryPointInvalidError, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class RecoveryPointInvalidError(RuntimeError):
    """Raised when a checkpoint is structurally valid but cannot serve as a
    recovery point for a side-effecting replay."""
    pass


@dataclass
class Checkpoint:
    summary: str
    recent_window: list[dict]
    action_ledger: dict[str, Any]          # verbatim args for pending/committed ops
    pre_compaction_token_count: int
    pre_compaction_hash: str
    summarizer_id: str                     # model + version + params, pinned
    taken_after_compaction: bool = True


def make_checkpoint(pre_transcript: list[dict],
                    summarizer,
                    summarizer_id: str,
                    pending_action: dict | None) -> Checkpoint:
    pre_hash = hashlib.sha256(
        json.dumps(pre_transcript, sort_keys=True).encode()
    ).hexdigest()
    summary = summarizer(pre_transcript)
    ledger = {}
    if pending_action is not None:
        # Lossy summary is NOT allowed to carry action args. Preserve verbatim.
        ledger[pending_action["id"]] = pending_action["args"]
    return Checkpoint(
        summary=summary,
        recent_window=pre_transcript[-8:],
        action_ledger=ledger,
        pre_compaction_token_count=sum(len(t.get("content", "")) for t in pre_transcript),
        pre_compaction_hash=pre_hash,
        summarizer_id=summarizer_id,
        taken_after_compaction=True,
    )


def restore_for_replay(ckpt: Checkpoint,
                       current_summarizer_id: str,
                       action_id: str) -> dict:
    # Invariant 2: summarizer must be pinned and match.
    if ckpt.summarizer_id != current_summarizer_id:
        raise RecoveryPointInvalidError(
            f"summarizer drift: checkpoint={ckpt.summarizer_id!r} "
            f"runtime={current_summarizer_id!r}; summary not reproducible"
        )
    # Invariant 1: side-effecting action args must be present verbatim.
    if action_id not in ckpt.action_ledger:
        raise RecoveryPointInvalidError(
            f"action {action_id!r} not in verbatim ledger; "
            f"checkpoint is a conversational, not operational, recovery point"
        )
    # Invariant 3: boundary alignment is asserted by construction; verify hash present.
    if not ckpt.pre_compaction_hash:
        raise RecoveryPointInvalidError(
            "missing pre-compaction hash; cannot prove which pre-state summary represents"
        )
    return ckpt.action_ledger[action_id]
