/**
 * Chain persistence via srmd.exe localhost API (desktop only).
 */
export function createExeChainPersistence() {
  async function load() {
    const res = await fetch("/v1/exe/chain/load", { cache: "no-store" });
    if (!res.ok) return null;
    return res.json();
  }

  async function saveBlock(height, block, meta, state) {
    await fetch("/v1/exe/chain/block", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ height, block, meta, state: state || null }),
    });
  }

  async function clear() {
    await fetch("/v1/exe/chain/clear", { method: "POST" });
  }

  async function ensureReserve() {
    const res = await fetch("/v1/exe/store/reserve", { method: "POST" });
    const json = await res.json().catch(() => ({}));
    if (!res.ok || !json.ok) {
      return { ok: false, error: json.error || "Need 1 GB free disk to mine this wallet" };
    }
    return json;
  }

  async function ensureRam() {
    const res = await fetch("/v1/exe/ram/reserve", { method: "POST" });
    const json = await res.json().catch(() => ({}));
    if (!res.ok || !json.ok) {
      return { ok: false, error: json.error || "Need at least 3 RAM slabs (96 MB) to mine this wallet" };
    }
    return json;
  }

  async function releaseRam() {
    await fetch("/v1/exe/ram/release", { method: "POST" }).catch(() => {});
  }

  return { load, saveBlock, clear, ensureReserve, ensureRam, releaseRam };
}
