"""An offline checkpoint exercise, not a video renderer. Python 3.10+."""
import hashlib
import json
from pathlib import Path
from tempfile import TemporaryDirectory


def digest(data):
    return hashlib.sha256(data).hexdigest()


def encoded(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8")


def atomic_write(path, data):
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_bytes(data)
    temporary.replace(path)


class Interrupted(Exception):
    pass


def run(root, brief, stop_after=None):
    root = Path(root)
    root.mkdir(parents=True, exist_ok=True)
    state_path = root / "state.json"
    state = json.loads(state_path.read_text(encoding="utf-8")) if state_path.exists() else {}
    # Local single-process example. Each stage depends on the previous output digest.
    events, previous_hash = [], None
    for index, stage in enumerate(["plan", "narration", "package"], 1):
        inputs = {"stage": stage, "version": 1, "brief": brief, "upstream": previous_hash}
        fingerprint = digest(encoded(inputs))
        artifact = root / (stage + ".json")
        record = state.get(stage, {})
        reusable = (record.get("input_hash") == fingerprint and artifact.is_file()
                    and digest(artifact.read_bytes()) == record.get("output_hash"))
        if reusable:
            events.append(stage + ": reused")
        else:
            # A tiny deterministic artifact makes validation inspectable without AI services.
            output = encoded({"example_stage": stage, "inputs": inputs})
            atomic_write(artifact, output)
            record = {"input_hash": fingerprint, "output_hash": digest(output)}
            state[stage] = record
            atomic_write(state_path, encoded(state))
            events.append(stage + ": built")
        previous_hash = record["output_hash"]
        if stop_after == index:
            raise Interrupted("Stopped after checkpoint: " + stage)
    return events


def demo():
    with TemporaryDirectory(prefix="checkpoint-example-") as folder:
        root = Path(folder)
        try:
            run(root, "Explain checkpoints", stop_after=2)
        except Interrupted as error:
            interruption = str(error)
        resumed = run(root, "Explain checkpoints")
        (root / "narration.json").write_text("damaged output", encoding="utf-8")
        repaired = run(root, "Explain checkpoints")
        changed = run(root, "Explain checkpoints with a new example")
        return {"interruption": interruption, "resume": resumed,
                "after_damage": repaired, "changed_brief": changed}


if __name__ == "__main__":
    print(json.dumps(demo(), indent=2))
