#!/usr/bin/env node
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";

const root = process.cwd();
const proofRoot = "proof/verified-runs";
const indexPath = "proof/PROOF_INDEX.md";

async function sha256(relativePath) {
  return createHash("sha256").update(await readFile(join(root, relativePath))).digest("hex");
}

async function readBundles() {
  if (!existsSync(join(root, proofRoot))) return [];
  const entries = await readdir(join(root, proofRoot), { withFileTypes: true });
  const bundles = [];
  for (const entry of entries.filter((item) => item.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))) {
    const path = `${proofRoot}/${entry.name}/proof-bundle.json`;
    if (!existsSync(join(root, path))) continue;
    const bundle = JSON.parse(await readFile(join(root, path), "utf8"));
    bundles.push({ path, digest: await sha256(path), bundle });
  }
  return bundles;
}

const bundles = await readBundles();
const lines = [
  "# OMK Proof Index",
  "",
  "Generated by `node scripts/build-proof-index.mjs`.",
  "",
  "| Proof ID | Scenario | Provider policy | Verdict | Bundle file | SHA-256 |",
  "| --- | --- | --- | --- | --- | --- |",
];
for (const { path, digest, bundle } of bundles) {
  const providerPolicy = String(bundle.providerPolicy ?? "").replaceAll("|", "\\|");
  lines.push(`| ${bundle.proofId} | ${bundle.scenario} | ${providerPolicy} | ${bundle.verdict} | \`${path}\` | \`${digest}\` |`);
}
if (bundles.length === 0) lines.push("| none | missing | none | missing |  |  |");
await mkdir(join(root, "proof"), { recursive: true });
await writeFile(join(root, indexPath), `${lines.join("\n")}\n`);
console.log(`wrote ${indexPath} with ${bundles.length} bundle(s)`);
