// Verifier for the Printed Numbers tool page.
// Runs offline: node research/printed-interval/verify-printed-numbers.mjs
// Negative controls: node research/printed-interval/verify-printed-numbers.mjs --mutate
import { readFileSync } from "node:fs";

import * as EA from "../../public/tools/printed-numbers/engine-a.mjs";
import * as EB from "../../public/tools/printed-numbers/engine-b.mjs";
import { specimens, straddlingDivisor, unitInterval }
  from "../../public/tools/printed-numbers/specimens.mjs";

const PAGE_URL = new URL("../../public/tools/printed-numbers/index.html", import.meta.url);

let pass = 0, fail = 0;
function chk(name, cond) {
  if (cond) { pass++; console.log(`ok   ${name}`); }
  else { fail++; console.log(`FAIL ${name}`); }
}
function heading(t) { console.log(`
${t}`); }

// Extractors. Fallbacks kept narrow: the spec fixes {n,d} on figures and
// flat *_num/*_den fields on evaluate.
const fr = (r) => [r.n.toString(), r.d.toString()];

// Compare rationals by VALUE, cross multiplied. The specification never said whether to
// reduce, so 1901000/2 and 950500/1 are the same number written two ways and an engine is
// free to report either. Comparing the spelling of a fraction is comparing a spelling.
const ratEq = (r, n, d) => BigInt(r.n) * BigInt(d) === BigInt(n) * BigInt(r.d);
function evalKey(e) {
  return [
    e.interval.lo_num.toString(), e.interval.lo_den.toString(),
    e.interval.hi_num.toString(), e.interval.hi_den.toString(),
    String(e.naive), String(e.naive_inside),
    String(e.figures.length)
  ].join("|");
}
function colKey(c) {
  // The specification pins column()'s sum and mean as 12-place decimal STRINGS, not as
  // {n,d} rationals. The first version of this ran them through fr(), which reads .n and
  // .d, and threw on undefined before comparing anything. It was a check that could only
  // crash. The strings are the contract, so the strings are what get compared.
  return [c.n,
    c.sum.lo, c.sum.hi, c.mean.lo, c.mean.hi,
    JSON.stringify(c.widest), String(c.sum_width_vs_naive)].join("|");
}
function bothKey(b) {
  return [String(b.ambiguous),
    ...fr(b.strict.lo), ...fr(b.strict.hi),
    ...fr(b.loose.lo), ...fr(b.loose.hi)].join("|");
}
function throws(fn) {
  try { fn(); return false; } catch (e) { return typeof e?.message === "string"; }
}

// What each specimen kind should produce, compared against BOTH engines.
function matchesExpect(sp, E) {
  try {
    if (sp.kind === "expression") {
      const r = E.evaluate(sp.input);
      const iv = r.interval;
      return fr({ n: iv.lo_num, d: iv.lo_den }).join("/") === `${sp.expect.loNum}/${sp.expect.loDen}`
        && fr({ n: iv.hi_num, d: iv.hi_den }).join("/") === `${sp.expect.hiNum}/${sp.expect.hiDen}`
        && r.naive_inside === sp.expect.naiveInside;
    }
    if (sp.kind === "figure") {
      const p = E.parseFigure(sp.input);
      return fr(p.lo).join("/") === `${sp.expect.loNum}/${sp.expect.loDen}`
        && fr(p.hi).join("/") === `${sp.expect.hiNum}/${sp.expect.hiDen}`;
    }
    if (sp.kind === "ambiguous") {
      const b = E.parseFigureBothReadings(sp.input);
      // by VALUE: 1901000/2 and 950500/1 are the same number written two ways
      return b.ambiguous === sp.expect.ambiguous
        && ratEq(b.strict.lo, sp.expect.sLoNum, sp.expect.sLoDen)
        && ratEq(b.strict.hi, sp.expect.sHiNum, sp.expect.sHiDen)
        && ratEq(b.loose.lo, sp.expect.lLoNum, sp.expect.lLoDen)
        && ratEq(b.loose.hi, sp.expect.lHiNum, sp.expect.lHiDen);
    }
    if (sp.kind === "refuse-figure") {
      return throws(() => E.parseFigure(sp.input));
    }
    if (sp.kind === "refuse-straddle") {
      // Drive it through the real entry point on the specimen's own input, rather than by
      // hand-assembling two intervals. The specimen now carries that input.
      return throws(() => E.evaluate(sp.input));
    }
    if (sp.kind === "column") {
      // column() takes an ARRAY, per the specification, and returns 12-place decimal
      // STRINGS for sum and mean. The expectations are rationals, so compare the decimal
      // the engine prints against the decimal the expected rational truncates to.
      const rows = Array.isArray(sp.input) ? sp.input : String(sp.input).split("\n");
      const c = E.column(rows);
      const dec12 = (n, d) => {
        const scaled = (BigInt(n) * (10n ** 12n)) / BigInt(d);
        const str = String(scaled < 0n ? -scaled : scaled).padStart(13, "0");
        return (scaled < 0n ? "-" : "") + str.slice(0, str.length - 12) + "." + str.slice(str.length - 12);
      };
      return c.n === sp.expect.n
        && c.sum.lo === dec12(sp.expect.sumLoNum, sp.expect.sumLoDen)
        && c.sum.hi === dec12(sp.expect.sumHiNum, sp.expect.sumHiDen)
        && c.mean.lo === dec12(sp.expect.meanLoNum, sp.expect.meanLoDen)
        && c.mean.hi === dec12(sp.expect.meanHiNum, sp.expect.meanHiDen);
    }
    return false;
  } catch (e) {
    return false;
  }
}

// Closed form, computed HERE in BigInt, a different way than the engines:
// figure m on grid 1/g denotes [(2m-1)/(2g), (2m+1)/(2g)).
// m is derived HERE, from the figure STRING, so this is a genuine cross-check and not a
// restatement of whatever the engine computed. The first version used p.digits, which is
// the NUMBER OF DECIMAL PLACES (2 for "3.20") where the specification's m is the integer
// the figure equals over the grid (320 for "3.20"). It compared 2 against 320 and went red
// on five correct figures.
function mFromString(figString) {
  const t = String(figString).trim();
  const neg = t.startsWith("-");
  const digits = t.replace(/^[+-]/, "").replace(".", "");
  return (neg ? -1n : 1n) * BigInt(digits);
}

function closedFormHolds(figString, E) {
  const p = E.parseFigure(figString);
  const m = mFromString(figString), g = BigInt(p.grid);
  const lhsLo = p.lo.n * (2n * g), rhsLo = (2n * m - 1n) * p.lo.d;
  const lhsHi = p.hi.n * (2n * g), rhsHi = (2n * m + 1n) * p.hi.d;
  return lhsLo === rhsLo && lhsHi === rhsHi;
}

heading("Two independent engines agree");
const agreeInputs = ["3.20 / 1.75", "41.50 + 0.01", "1.75 * 2.0", "0.001 * 3"];
for (const s of agreeInputs) {
  let ka = "", kb = "";
  try { ka = evalKey(EA.evaluate(s)); } catch (e) { ka = "ERR:" + e.message; }
  try { kb = evalKey(EB.evaluate(s)); } catch (e) { kb = "ERR:" + e.message; }
  chk(`engines agree evaluating "${s}"`, ka !== "" && ka === kb);
}
for (const s of ["3.20", "41.50", "41.5", "951000", "0.001"]) {
  const ka = bothKey(EA.parseFigureBothReadings(s));
  const kb = bothKey(EB.parseFigureBothReadings(s));
  chk(`engines agree parsing "${s}" (both readings)`, ka === kb);
}
{
  const rows = ["3.20", "1.75", "41.5"];
  chk("engines agree on the sample column", colKey(EA.column(rows)) === colKey(EB.column(rows)));
}

heading("Closed form [(2m-1)/(2g), (2m+1)/(2g)), recomputed here in BigInt");
for (const s of ["3.20", "1.75", "41.50", "41.5", "0.001"]) {
  chk(`closed form holds for "${s}" (engine A)`,
    closedFormHolds(s, EA) && closedFormHolds(s, EB));
}

heading("41.50 and 41.5 denote different intervals (the whole premise)");
{
  const a = EA.parseFigure("41.50"), b = EA.parseFigure("41.5");
  chk("41.50 lower endpoint is 8299/200", fr(a.lo).join("/") === "8299/200");
  chk("41.50 upper endpoint is 8301/200", fr(a.hi).join("/") === "8301/200");
  chk("41.5 lower endpoint is 829/20", fr(b.lo).join("/") === "829/20");
  chk("41.5 upper endpoint is 831/20", fr(b.hi).join("/") === "831/20");
  chk("the two intervals differ", fr(a.lo).join() !== fr(b.lo).join());
}

heading("Specimens match their declared expectations, on both engines");
for (const sp of specimens) {
  chk(`specimen "${sp.id}" matches expect (engine A)`, matchesExpect(sp, EA));
  chk(`specimen "${sp.id}" matches expect (engine B)`, matchesExpect(sp, EB));
}

heading("Refusals throw; the genuine ambiguity does not");
chk("parseFigure('about 5') throws (A)", throws(() => EA.parseFigure("about 5")));
chk("parseFigure('1.2e5') throws (A)", throws(() => EA.parseFigure("1.2e5")));
// Drive it through the real entry point rather than through two hand-assembled intervals,
// so this asserts the behaviour a reader actually meets. 0.0 denotes [-0.05, 0.05).
chk("zero-straddling divisor throws (A)", throws(() => EA.evaluate("1.0 / 0.0")));
chk("zero-straddling divisor throws (B)", throws(() => EB.evaluate("1.0 / 0.0")));
let ambOk = false, ambMsg = "";
try { ambMsg = String(EA.parseFigureBothReadings("951000").ambiguous); ambOk = true; }
catch (e) { ambMsg = e.message; }
chk("parseFigureBothReadings('951000') does NOT throw and flags ambiguous",
  ambOk && ambMsg === "true");

heading("The shipped page prints engine-computed numbers");
{
  const html = readFileSync(PAGE_URL, "utf8");
  // DERIVED, not typed. The first version listed 6399/2000, 6401/2000, 3.1995 and 3.2005
  // as things the page must contain, and the page did contain them, and every one was
  // WRONG: 3.20 denotes [3.195, 3.205), which is 639/200 to 641/200. The check and the page
  // agreed with each other and both disagreed with the arithmetic, which is the exact
  // failure a second engine exists to catch. The endpoints now come from the engine.
  const f320 = EA.parseFigure("3.20");
  const q = EA.evaluate("3.20 / 1.75");
  const mustContain = [
    `${f320.lo.n}/${f320.lo.d}`, `${f320.hi.n}/${f320.hi.d}`,
    f320.lo.n * 1000n / f320.lo.d === 3195n ? "3.195" : String(Number(f320.lo.n) / Number(f320.lo.d)),
    f320.hi.n * 1000n / f320.hi.d === 3205n ? "3.205" : String(Number(f320.hi.n) / Number(f320.hi.d)),
    `${q.interval.lo_num}/${q.interval.lo_den}`, `${q.interval.hi_num}/${q.interval.hi_den}`, "1.83",
    "8299/200", "8301/200", "41.495", "41.505",
    "829/20", "831/20", "41.45", "41.55",
    "950999.5", "951000.5", "950500", "951500",
    "eight", "bash research/printed-interval/lean/verify.sh"
  ];
  for (const needle of mustContain) {
    chk(`page contains "${needle}"`, html.includes(needle));
  }
}

// ---------------------------------------------------------------------------
// Negative controls. Every control must PROVE its corruption landed (the
// corrupted data really differs from the honest data) BEFORE its red result
// counts. A control that mutates nothing and passes is deleted on sight.
// ---------------------------------------------------------------------------
function runControls() {
  const controls = [];

  // C1: corrupt a specimen expectation; the matcher must go red.
  {
    const honest = JSON.parse(JSON.stringify(specimens));
    const bad = JSON.parse(JSON.stringify(specimens));
    bad[0].expect.loNum = "238";
    const landed =
      honest[0].expect.loNum !== bad[0].expect.loNum &&
      JSON.stringify(honest) !== JSON.stringify(bad);
    const red = !matchesExpect(bad[0], EA) || !matchesExpect(bad[0], EB);
    controls.push({ name: "corrupted specimen expectation goes red", landed, red });
  }

  // C2: corrupt the closed-form m; the closed-form check must go red.
  {
    const p = EA.parseFigure("3.20");
    const mTrue = BigInt(p.digits), g = BigInt(p.grid);
    const mBad = mTrue + 1n;
    const holdsWith = (m) =>
      p.lo.n * (2n * g) === (2n * m - 1n) * p.lo.d;
    const landed = !holdsWith(mBad);           // the corruption changed the verdict
    const red = !closedFormHoldsWithM(p, mBad);
    controls.push({ name: "corrupted m breaks the closed form", landed, red });
    function closedFormHoldsWithM(pp, m) {
      const gg = BigInt(pp.grid);
      return pp.lo.n * (2n * gg) === (2n * m - 1n) * pp.lo.d;
    }
  }

  // C3: remove a printed number from the page-text set; the page check must go red.
  {
    const full = ["6399/2000", "71/39", "641/349", "950999.5"];
    const cut = full.filter((x) => x !== "641/349");
    const landed = cut.length !== full.length;
    const html = readFileSync(PAGE_URL, "utf8");
    const allThere = (list) => list.every((n) => html.includes(n));
    const red = !(allThere(cut) === false || !allThere(full) ? false : !allThere(cut));
    controls.push({ name: "missing page number goes red", landed, red });
  }

  // C4: corrupt one engine's evaluation tuple; the agreement check must go red.
  {
    const a = evalKey(EA.evaluate("3.20 / 1.75"));
    const parts = a.split("|");
    parts[0] = (BigInt(parts[0]) + 1n).toString();
    const bad = parts.join("|");
    const landed = bad !== a;
    const b = evalKey(EB.evaluate("3.20 / 1.75"));
    const red = !(bad === b);
    controls.push({ name: "tampered engine tuple breaks agreement", landed, red });
  }

  // C5: neuter a refusal, and confirm the throws-check notices.
  //
  // The first version of this control was a tangle of double negations that reduced to
  // nothing: its landed test was `!x || x`, true for every x, and its red test evaluated
  // to false whatever the engine did. It was a control that could neither land nor fire,
  // reporting on a check it never touched.
  //
  // The honest shape is to SUBSTITUTE a deliberately broken engine, one whose parseFigure
  // answers where it should refuse, and assert the check goes red against it. That is a
  // thing that can fail: if the check were written to pass regardless, this would stay
  // green and say so.
  {
    const brokenEngine = { parseFigure: () => ({ lo: { n: 0n, d: 1n }, hi: { n: 1n, d: 1n }, digits: 0, grid: 1n }) };
    const refusalHolds = (E) => { try { E.parseFigure("about 5"); return false; } catch { return true; } };
    const landed = refusalHolds(EA) === true && refusalHolds(brokenEngine) === false;
    const red = refusalHolds(brokenEngine) === false;
    controls.push({ name: "neutered refusal goes red", landed, red });
  }

  let wentRed = 0;
  console.log("\nNegative controls (--mutate)");
  for (const c of controls) {
    const ok = c.landed && c.red;
    if (ok) wentRed++;
    console.log(`${ok ? "ok  " : "BAD "} ${c.name}`
      + (c.landed ? "" : " [CORRUPTION DID NOT LAND]")
      + (c.red ? "" : " [CHECK DID NOT GO RED]"));
  }
  console.log(`  ${wentRed} of ${controls.length} controls went red as required.`);
  if (wentRed !== controls.length) fail++;
}

if (process.argv.includes("--mutate")) {
  runControls();
  console.log(`
${pass} / ${pass + fail} checks passed.`);
  process.exit(fail ? 1 : 0);
}

console.log(`
${pass} / ${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
