#!/usr/bin/env node
// Check Margaret's poem-commission ledger yourself. Node 18+, no dependencies.
//
//   node verify-ledger.mjs                              the live ledger at https://poems.lorepunk.ai
//   node verify-ledger.mjs https://other.host           another copy of the server
//   node verify-ledger.mjs ./ledger.jsonl               a copy you saved earlier
//   node verify-ledger.mjs --expect <entry hash> [...]  also check that an entry you were given is still there
//
// The rules it checks:
//   hash  = sha256 of the entry without "hash", keys sorted, as JSON
//   prev  = the hash of the entry before it (the first entry's prev is 64 zeros)
//   seq   = 1, 2, 3, … with no gaps
// and, when reading a live server, that each delivered poem's text still has the fingerprint (poem_sha256)
// last recorded for it: sha256 of the text as GET /poems/<id>?format=json returns it.
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";

const args = process.argv.slice(2);
const expect = [];
for (let i = args.indexOf("--expect"); i !== -1; i = args.indexOf("--expect")) { expect.push(args[i + 1]); args.splice(i, 2); }
const target = args[0] ?? "https://poems.lorepunk.ai";
const live = /^https?:\/\//.test(target);
const base = target.replace(/\/$/, "");

const sha256 = (s) => createHash("sha256").update(s, "utf8").digest("hex");
const canonical = (e) => JSON.stringify(Object.fromEntries(Object.keys(e).filter((k) => k !== "hash").sort().map((k) => [k, e[k]])));

const raw = live ? await (await fetch(`${base}/ledger.jsonl`)).text() : readFileSync(target, "utf8");
const entries = raw.split("\n").filter((l) => l.trim()).map((l, i) => { try { return JSON.parse(l); } catch { console.log(`✗ line ${i + 1} is not JSON`); process.exit(1); } });

let prev = "0".repeat(64), bad = 0;
for (const [i, e] of entries.entries()) {
  const problems = [];
  if (e.seq !== i + 1) problems.push(`seq ${e.seq}, expected ${i + 1}`);
  if (e.prev !== prev) problems.push("prev doesn't match the entry before");
  if (sha256(canonical(e)) !== e.hash) problems.push("hash doesn't match the contents");
  if (problems.length) { bad++; console.log(`✗ entry ${i + 1} (${e.kind} ${e.commission}): ${problems.join("; ")}`); }
  prev = e.hash;
}
console.log(`${bad ? "✗" : "✓"} ${entries.length} entries, chain ${bad ? "BROKEN" : "intact"}, head ${prev}`);

for (const h of expect) {
  const found = entries.find((e) => e.hash === h);
  console.log(found ? `✓ ${h.slice(0, 16)}… is entry ${found.seq} (${found.kind}, ${found.commission})` : `✗ ${h} is not in this ledger`);
  if (!found) bad++;
}

if (live) {
  const latest = new Map();
  for (const e of entries) if (e.kind === "delivered" || e.kind === "revised") latest.set(e.commission, e);
  for (const [id, e] of latest) {
    const r = await fetch(`${base}/poems/${encodeURIComponent(e.poem)}?format=json`);
    if (!r.ok) { console.log(`· ${id}: poem ${e.poem} is no longer on the shelf`); continue; }
    const same = sha256((await r.json()).text) === e.poem_sha256;
    console.log(`${same ? "✓" : "·"} ${id}: poem ${e.poem} ${same ? "matches its recorded fingerprint" : "has changed since its last recorded fingerprint (the server records a revision within a minute)"}`);
  }
}
process.exit(bad ? 1 : 0);
