// verify.mjs: the check for the-planets-under-question.
// Offline:   node research/the-planets-under-question/verify.mjs
// Mutations: node research/the-planets-under-question/verify.mjs --mutate

import { readFileSync } from "node:fs";
import { parseCSV, computeStats, wilsonInterval, Z95 } from "./engine.mjs";

const SLUG = "the-planets-under-question";
const HERE = new URL(".", import.meta.url);
const ROOT = new URL("../..", HERE);
const PUB = new URL("public/strata/" + SLUG + "/", ROOT);

const readText = (u) => readFileSync(u, "utf8");

// ---------- independent recomputation helpers -------------------------

// A second field splitter, regex-based, sharing no code with the
// engine's character-state machine.
function splitLine(line) {
  const out = [];
  const re = /("(?:[^"]|"")*"|[^,]*)(,|$)/g;
  let m;
  while ((m = re.exec(line)) !== null) {
    out.push(m[1]);
    if (re.lastIndex >= line.length) break;
  }
  return out.map((s) =>
    s.length > 1 && s.startsWith('"') && s.endsWith('"')
      ? s.slice(1, -1).replace(/""/g, '"')
      : s
  );
}

// Recount the headline numbers straight from the raw text, line by
// line. Sound only because a separate check confirms the snapshot
// holds no newline inside a quoted field (both routes must agree on
// the row count, and go red if they do not).
function bruteCounts(text) {
  const lines = text
    .replace(/\r\n?/g, "\n")
    .split("\n")
    .filter((l) => l.trim() !== "");
  const header = splitLine(lines[0]).map((h) => h.trim());
  const iFlag = header.indexOf("pl_controv_flag");
  const iDef = header.indexOf("default_flag");
  let n = 0;
  let c = 0;
  for (const line of lines.slice(1)) {
    const f = splitLine(line);
    if (f[iDef] !== "1") continue;
    n += 1;
    if (f[iFlag] === "1") c += 1;
  }
  return { n, c, nLines: lines.length - 1 };
}

// Plain-loop re-implementation of the grouping contract, written
// against the spec rather than against the engine's code.
function regroup(rows) {
  const method = {};
  const decade = {};
  const fac = {};
  for (const r of rows) {
    const flagged = String(r.pl_controv_flag).trim() === "1";

    const m = r.discoverymethod ?? "";
    if (!method[m]) method[m] = { n: 0, controv: 0 };
    method[m].n += 1;
    if (flagged) method[m].controv += 1;

    const yRaw = String(r.disc_year ?? "").trim();
    const y = yRaw === "" ? NaN : Number(yRaw);
    const dk = Number.isFinite(y) ? String(Math.floor(y / 10) * 10) : "unknown";
    if (!decade[dk]) decade[dk] = { n: 0, controv: 0 };
    decade[dk].n += 1;
    if (flagged) decade[dk].controv += 1;

    const f = r.disc_facility ?? "";
    if (!fac[f]) fac[f] = { n: 0, controv: 0 };
    fac[f].n += 1;
    if (flagged) fac[f].controv += 1;
  }
  const top = Object.entries(fac)
    .filter(([, v]) => v.n >= 10)
    .map(([facility, v]) => ({ facility, n: v.n, controv: v.controv }))
    .sort((a, b) => (b.controv - a.controv) || (a.facility < b.facility ? -1 : 1));
  return { method, decade, top };
}

// Root-find the Wilson bounds straight from their defining equation
// (p_hat - p)^2 = z^2 p (1 - p) / n. Slow, obvious, and algebraically
// independent of the closed form in engine.mjs.
function bisectWilson(num, den) {
  const pHat = num / den;
  const f = (p) => (pHat - p) * (pHat - p) - (Z95 * Z95 * p * (1 - p)) / den;
  const root = (a, b) => {
    let fa = f(a);
    for (let i = 0; i < 200; i += 1) {
      const mid = (a + b) / 2;
      const fm = f(mid);
      if ((fa < 0) === (fm < 0)) { a = mid; fa = fm; } else { b = mid; }
    }
    return (a + b) / 2;
  };
  return { lo: root(0, pHat), hi: root(pHat, 1) };
}

// ---------- assertions -------------------------------------------------

const eq = (got, want, msg) => {
  if (got !== want) throw new Error(msg || ("expected " + want + ", got " + got));
};
const close = (got, want, tol, msg) => {
  if (!(Math.abs(got - want) <= tol)) {
    throw new Error(msg || ("expected " + want + " +/- " + tol + ", got " + got));
  }
};

const CHECKS = [
  ["Counts, recounted a second way", [
    ["row count matches a line-by-line recount of the raw text", (c) => {
      const b = bruteCounts(c.csvText);
      eq(c.stats.n_planets, b.n, "engine and line recount disagree on rows");
      eq(c.stats.n_planets, b.nLines, "quoted newline suspected: parser and line count differ");
    }],
    ["flagged count matches the independent field splitter", (c) => {
      const b = bruteCounts(c.csvText);
      eq(c.stats.n_controversial, b.c, "engine and brute recount disagree on flags");
    }],
    ["by_method matches a plain-loop regrouping, key for key", (c) => {
      eq(JSON.stringify(c.stats.by_method), JSON.stringify(regroup(c.rows).method),
        "by_method drifted from the spec re-implementation");
    }],
    ["by_decade matches a plain-loop regrouping, floor rule included", (c) => {
      eq(JSON.stringify(c.stats.by_decade), JSON.stringify(regroup(c.rows).decade),
        "by_decade drifted from the spec re-implementation");
    }],
    ["by_facility_top honours n >= 10 and the sort contract", (c) => {
      eq(JSON.stringify(c.stats.by_facility_top), JSON.stringify(regroup(c.rows).top),
        "by_facility_top drifted from the spec re-implementation");
    }],
    ["overall_rate carries exactly the counted pair", (c) => {
      eq(c.stats.overall_rate.num, c.stats.n_controversial, "numerator mismatch");
      eq(c.stats.overall_rate.den, c.stats.n_planets, "denominator mismatch");
    }],
  ]],
  ["The Wilson interval, anchored three ways", [
    ["0 of 10 lands on the closed form z^2/(n+z^2)", (c) => {
      const got = c.wilson(0, 10).hi;
      const want = (Z95 * Z95) / (10 + Z95 * Z95);
      close(got, want, 1e-12, "zero-numerator closed form missed");
    }],
    ["10 of 10 lands on the mirrored closed form n/(n+z^2)", (c) => {
      const got = c.wilson(10, 10).lo;
      const want = 10 / (10 + Z95 * Z95);
      close(got, want, 1e-12, "full-numerator closed form missed");
    }],
    ["5 of 9 matches a bisection of the defining equation", (c) => {
      const w = c.wilson(5, 9);
      const b = bisectWilson(5, 9);
      close(w.lo, b.lo, 1e-9, "lower bound off the bisection root");
      close(w.hi, b.hi, 1e-9, "upper bound off the bisection root");
    }],
    ["every grouped interval brackets its own raw rate", (c) => {
      const groups = [
        ...Object.values(c.stats.by_method),
        ...c.stats.by_facility_top,
        ...Object.values(c.stats.by_decade),
      ];
      if (groups.length === 0) throw new Error("no groups at all");
      for (const g of groups) {
        const iv = c.wilson(g.controv, g.n);
        const p = g.controv / g.n;
        if (!(iv.lo <= p + 1e-12 && p <= iv.hi + 1e-12)) {
          throw new Error("interval fails to bracket its own rate");
        }
        if (!(iv.lo >= 0 && iv.hi <= 1)) throw new Error("interval escapes [0,1]");
      }
    }],
  ]],
  ["The shipped page", [
    ["page states the snapshot date 2026-08-24", (c) => {
      if (!c.html.includes("2026-08-24")) throw new Error("snapshot date absent from the page");
    }],
    ["page names the Wilson 95% interval", (c) => {
      if (!c.html.includes("95%") || !c.html.toLowerCase().includes("wilson")) {
        throw new Error("interval labelling absent from the page");
      }
    }],
    ["meta description equals the frontmatter dek, verbatim", (c) => {
      const m = c.html.match(/<meta name="description" content="([^"]*)">/);
      const d = c.fm.match(/^dek: "(.*)"$/m);
      if (!m || !d) throw new Error("dek or meta description not found");
      eq(m[1], d[1], "shipped meta description differs from the frontmatter dek");
    }],
    ["shipped engine.mjs is byte-identical to the research engine", (c) => {
      if (Buffer.compare(c.engineResBuf, c.enginePubBuf) !== 0) {
        throw new Error("public engine copy has drifted from the research engine");
      }
    }],
    ["page wires instrument.js to the shared engine and its math", (c) => {
      if (!c.html.includes("./instrument.js")) throw new Error("instrument script tag missing");
      // Test the FACT, not one spelling of it. The first version of this check looked for
      // the literal string "from './engine.mjs'" and went red on a file that imported the
      // same bindings with double quotes, which is a check measuring a quote style. This
      // repo has now had three gates fall into that trap, so: parse the import.
      const imp = c.instrument.match(/import\s*\{([^}]*)\}\s*from\s*["']\.\/engine\.mjs["']/);
      if (!imp) throw new Error("instrument.js does not import from ./engine.mjs");
      const bound = imp[1].split(",").map((s) => s.trim().split(/\s+as\s+/)[0].trim());
      for (const token of ["wilsonInterval", "computeStats", "parseCSV"]) {
        if (!bound.includes(token)) throw new Error("instrument.js does not import " + token);
      }
    }],
    ["no em dash or decorative en dash in page, scripts or engine", (c) => {
      const files = [["index.html", c.html], ["instrument.js", c.instrument], ["engine.mjs", c.enginePub]];
      for (const [label, text] of files) {
        if (text.includes("\u2014")) throw new Error(label + " carries an em dash");
        if (text.includes("\u2013")) throw new Error(label + " carries an en dash");
      }
    }],
  ]],
];

// ---------- context, with optional corruption --------------------------

function buildCtx(mut) {
  const csvText = readText(new URL("data/exoplanet-ps.csv", HERE));
  let rows = parseCSV(csvText);
  if (mut === "flag-flip" && rows.length > 0) {
    rows = rows.map((r, i) =>
      i === 0
        ? { ...r, pl_controv_flag: String(r.pl_controv_flag).trim() === "1" ? "0" : "1" }
        : r
    );
  }
  const stats = computeStats(rows);
  if (mut === "rate-drift") stats.overall_rate.num += 1;
  if (mut === "drop-method") {
    const k = Object.keys(stats.by_method)[0];
    delete stats.by_method[k];
  }
  if (mut === "group-rule") stats.by_facility_top.reverse();

  let html = readText(new URL("index.html", PUB));
  if (mut === "html-date") html = html.replace(/2026-08-24/g, "2026-08-25");

  let enginePubBuf = readFileSync(new URL("engine.mjs", PUB));
  if (mut === "engine-copy") {
    enginePubBuf = Buffer.from(enginePubBuf.toString("utf8").replace("Z95", "Z9_5"));
  }

  let fm = readText(new URL("src/content/strata/" + SLUG + ".md", ROOT));
  if (mut === "dek-drift") fm = fm.replace('dek: "', 'dek: "Corrupted. ');

  const instrument = readText(new URL("instrument.js", PUB));

  const wilson =
    mut === "interval-drift"
      ? (num, den) => {
          const w = wilsonInterval(num, den);
          return { lo: Math.max(0, w.lo - 0.004), hi: Math.min(1, w.hi + 0.004), p: w.p };
        }
      : wilsonInterval;

  return {
    csvText, rows, stats, html, fm, instrument, wilson,
    engineResBuf: readFileSync(new URL("engine.mjs", HERE)),
    enginePubBuf,
    enginePub: enginePubBuf.toString("utf8"),
  };
}

function runCheck(fn, ctx) {
  try { fn(ctx); return true; } catch { return false; }
}

// ---------- runners -----------------------------------------------------

const mutateMode = process.argv.includes("--mutate");

if (!mutateMode) {
  let pass = 0;
  let fail = 0;
  console.log(SLUG + ": the check");
  for (const [heading, checks] of CHECKS) {
    console.log("\n" + heading);
    const ctx = buildCtx(null);
    for (const [name, fn] of checks) {
      const ok = runCheck(fn, ctx);
      console.log((ok ? "  [ok] " : "  [RED] ") + name);
      if (ok) pass += 1; else fail += 1;
    }
  }
  console.log(`\n${pass} / ${pass + fail} checks passed.`);
  process.exit(fail ? 1 : 0);
}

const MUTATIONS = [
  ["flip the first planet's controversial flag", "flag-flip",
    ["flagged count matches the independent field splitter"]],
  ["delete a discovery method from the engine's output", "drop-method",
    ["by_method matches a plain-loop regrouping, key for key"]],
  ["drift the overall numerator by one", "rate-drift",
    ["overall_rate carries exactly the counted pair"]],
  ["shift the snapshot date printed on the page", "html-date",
    ["page states the snapshot date 2026-08-24"]],
  ["corrupt the shipped engine copy", "engine-copy",
    ["shipped engine.mjs is byte-identical to the research engine"]],
  ["rewrite the frontmatter dek", "dek-drift",
    ["meta description equals the frontmatter dek, verbatim"]],
  ["sabotage the Wilson interval", "interval-drift",
    ["0 of 10 lands on the closed form z^2/(n+z^2)",
     "10 of 10 lands on the mirrored closed form n/(n+z^2)",
     "5 of 9 matches a bisection of the defining equation"]],
  ["reverse the facility ranking", "group-rule",
    ["by_facility_top honours n >= 10 and the sort contract"]],
];

console.log(SLUG + ": negative controls");
const lookup = new Map(CHECKS.flatMap(([, cs]) => cs));
let red = 0;
for (const [label, mut, aims] of MUTATIONS) {
  const ctx = buildCtx(mut);
  const results = aims.map((a) => runCheck(lookup.get(a), ctx));
  const goneRed = results.filter((r) => !r).length;
  const allRed = goneRed === aims.length;
  console.log(
    "  [" + (allRed ? "red" : "STILL GREEN") + "] " + label +
    ": " + goneRed + " of " + aims.length + " aimed checks went red"
  );
  if (allRed) red += 1;
}
console.log("  " + red + " of " + MUTATIONS.length + " controls went red as required.");
console.log(`\n${red} / ${MUTATIONS.length} checks passed.`);
process.exit(red === MUTATIONS.length ? 0 : 1);
