#!/usr/bin/env python3
import json
from pathlib import Path


checkpoint_path = Path(__file__).with_name("checkpoint.json")
effects_path = Path(__file__).with_name("side-effects.json")


def write_json(path, value):
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def load_json(path, default):
    return json.loads(path.read_text(encoding="utf-8")) if path.exists() else default


def side_effect(idempotency_key):
    effects = load_json(effects_path, [])
    if idempotency_key not in effects:
        effects.append(idempotency_key)
        write_json(effects_path, effects)
        return "created"
    return "deduplicated"


for path in (checkpoint_path, effects_path):
    if path.exists():
        path.unlink()

events = []
state = {"step": "execute", "idempotency_key": "refund-order-demo", "completed": False}
write_json(checkpoint_path, state)

try:
    events.append({"phase": "first_run", "effect": side_effect(state["idempotency_key"])})
    raise RuntimeError("simulated_process_crash_after_effect")
except RuntimeError as exc:
    events.append({"phase": "crash", "error": str(exc)})

resumed = load_json(checkpoint_path, {})
events.append({"phase": "resume", "effect": side_effect(resumed["idempotency_key"])})
resumed.update({"step": "done", "completed": True})
write_json(checkpoint_path, resumed)

result = {"terminal": "success", "checkpoint": resumed, "side_effects": load_json(effects_path, []), "events": events}
Path(__file__).with_name("experiment-result.json").write_text(
    json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
print(json.dumps(result, ensure_ascii=False, indent=2))
