#!/usr/bin/env node
// research/eka/verify.mjs — offline verifier for "Eka–".
//
//   node research/eka/verify.mjs
//
// Re-derives, from the sourced dataset, everything the page asserts:
//   I.   every predicted/measured pair yields the percent error the page shows, and
//        each quantitative prediction lands inside the tolerance the prose claims;
//   II.  the tellurium–iodine run inverts under weight-order and is clean under
//        atomic-number order (the record-correction made checkable);
//   III. √(Kα frequency) is linear in atomic number to R² > 0.999, and visibly LESS
//        linear in atomic weight — with the SAME Te/I inversion showing up as a
//        backward step on the weight axis; the screening offset is near Moseley's Z−1;
//   IV.  the drift guard — the published page embeds this dataset byte-for-byte.
//
// "Show the check": the numbers are sourced in data.mjs; the arithmetic is here.

import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { META, PTABLE, PREDICTIONS, ORDERING, MOSELEY, MISSES } from "./data.mjs";

let PASS = 0, FAIL = 0;
const log = [];
function check(name, cond, got, want) {
  if (cond) { PASS++; log.push(`  ok   ${name}`); }
  else { FAIL++; log.push(`  FAIL ${name}\n         got:  ${got}\n         want: ${want}`); }
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const pctErr = (pred, meas) => (pred - meas) / meas * 100;

// ── I · the reckoning ───────────────────────────────────────────────────────
log.push("I. THE RECKONING — predicted vs measured, every error recomputed");
let quantCount = 0, tightCount = 0;
for (const el of PREDICTIONS) {
  check(`${el.foundName}: eka-name present`, !!el.ekaName, el.ekaName, "an eka- name");
  check(`${el.foundName}: discovery year present`, /^\d{4}$/.test(el.foundYear), el.foundYear, "a 4-digit year");
  for (const p of el.props) {
    if (p.kind === "quant") {
      quantCount++;
      const e = pctErr(p.predicted, p.found);
      // every quantitative prediction lands within the page's headline tolerance…
      check(`${el.foundName} · ${p.label}: |error| ≤ ${(META.toleranceClaim * 100).toFixed(0)}%  (got ${e.toFixed(2)}%)`,
        Math.abs(e) <= META.toleranceClaim * 100 + 1e-9, `${e.toFixed(2)}%`, `≤ ${META.toleranceClaim * 100}%`);
      if (Math.abs(e) <= META.tightClaim * 100 + 1e-9) tightCount++;
      // the predicted & found numbers are real numbers (so the browser can compute the bar)
      check(`${el.foundName} · ${p.label}: predicted & found are numeric`,
        Number.isFinite(p.predicted) && Number.isFinite(p.found), `${p.predicted}/${p.found}`, "two numbers");
      // every quant prediction carries a source
      check(`${el.foundName} · ${p.label}: carries a source`, typeof p.src === "string" && p.src.length > 8, p.src, "a citation");
    } else {
      check(`${el.foundName} · ${p.label}: qual pair present`,
        typeof p.predicted === "string" && typeof p.found === "string", `${p.predicted}/${p.found}`, "two strings");
    }
  }
}
// The prose promises nine within 10% and exactly seven within 3%.
const quantitative = PREDICTIONS.flatMap(el => el.props.filter(p => p.kind === "quant"));
check(`all ${quantCount} quantitative predictions within ${(META.toleranceClaim*100)}%`,
  quantCount === 9 && quantitative.every(p => Math.abs(pctErr(p.predicted, p.found)) <= META.toleranceClaim * 100 + 1e-9),
  quantCount, "nine, each within tolerance");
check(`seven of nine quantitative predictions within ~${(META.tightClaim*100)}%  (${tightCount}/${quantCount})`,
  tightCount === 7 && quantCount === 9, `${tightCount}/${quantCount}`, "7/9");
// the two loose predictions are exactly the two the page names: Sc oxide density and Ge specific heat
const sc = PREDICTIONS.find(e => e.key === "Sc");
const scOx = sc.props.find(p => p.label === "oxide density");
check("the loosest fit is scandium's oxide density, and it is ~9% (named on the page)",
  near(Math.abs(pctErr(scOx.predicted, scOx.found)), 9.3, 0.5), `${pctErr(scOx.predicted, scOx.found).toFixed(1)}%`, "≈ −9.3%");
const ge = PREDICTIONS.find(e => e.key === "Ge");
const geSh = ge.props.find(p => p.label === "specific heat");
check("the second-loosest is germanium's specific heat, ~4% (named on the page)",
  near(Math.abs(pctErr(geSh.predicted, geSh.found)), 3.9, 0.6), `${pctErr(geSh.predicted, geSh.found).toFixed(1)}%`, "≈ −3.9%");
// and the two loose ones are the ONLY ones above the tight band
const looseLabels = PREDICTIONS.flatMap(e => e.props.filter(p => p.kind === "quant" && Math.abs(pctErr(p.predicted, p.found)) > META.tightClaim * 100).map(p => `${e.key}:${p.label}`));
check("exactly those two predictions exceed the ~3% band",
  looseLabels.length === 2 && looseLabels.includes("Sc:oxide density") && looseLabels.includes("Ge:specific heat"),
  looseLabels.join(", "), "Sc:oxide density, Ge:specific heat");
// gallium's density is essentially exact (the corrected-by-mail anecdote)
const ga = PREDICTIONS.find(e => e.key === "Ga");
const gaD = ga.props.find(p => p.label === "density");
check("gallium density predicted 5.9 vs measured 5.904 — within 0.1%",
  Math.abs(pctErr(gaD.predicted, gaD.found)) < 0.1, `${pctErr(gaD.predicted, gaD.found).toFixed(3)}%`, "< 0.1%");

// ── I(b) · the table fragment is well-formed and shows exactly three gaps ─────
log.push("\nI(b). THE 1871 FRAGMENT — three gaps, each keyed to a prediction");
const gaps = PTABLE.flat().filter(c => c && c.gap);
check("exactly three gaps in the fragment", gaps.length === 3, gaps.length, 3);
for (const g of gaps) check(`gap '${g.key}' keys to a real prediction`, PREDICTIONS.some(p => p.key === g.key), g.key, "a prediction key");
check("every prediction key appears as a gap", PREDICTIONS.every(p => gaps.some(g => g.key === p.key)), "", "");

// ── II · the rule he broke (Te/I inversion) ─────────────────────────────────
log.push("\nII. THE RULE HE BROKE — weight inverts the Te/I pair, atomic number fixes it");
const E = ORDERING.elements;
const te = E.find(x => x.sym === "Te"), io = E.find(x => x.sym === "I");
check("tellurium is HEAVIER than iodine", te.W > io.W, `Te ${te.W} vs I ${io.W}`, "Te.W > I.W");
check("tellurium's atomic number is LOWER than iodine's", te.Z < io.Z, `Te ${te.Z} vs I ${io.Z}`, "Te.Z < I.Z");
// sort by weight → at least one cell lands out of atomic-number order (an inversion)
const byW = E.slice().sort((a, b) => a.W - b.W);
let weightInversions = 0;
for (let i = 1; i < byW.length; i++) if (byW[i].Z < byW[i - 1].Z) weightInversions++;
check("ordering by weight produces exactly one inversion (the Te/I flip)", weightInversions === 1, weightInversions, 1);
// sort by atomic number → no inversions, strictly ascending Z and the table order
const byZ = E.slice().sort((a, b) => a.Z - b.Z);
let numberInversions = 0;
for (let i = 1; i < byZ.length; i++) if (byZ[i].Z < byZ[i - 1].Z) numberInversions++;
check("ordering by atomic number produces zero inversions", numberInversions === 0, numberInversions, 0);
// and under weight-order the offending pair is specifically I-before-Te
const iIdx = byW.findIndex(x => x.sym === "I"), teIdx = byW.findIndex(x => x.sym === "Te");
check("under weight-order, iodine precedes the heavier tellurium", iIdx < teIdx, `I@${iIdx} Te@${teIdx}`, "I before Te");

// ── III · Moseley's line, fit live, reproduced here ─────────────────────────
log.push("\nIII. MOSELEY — √ν linear in Z (R²>0.999), less so in weight, same Te/I kink");
function fit(xs, ys) {
  const n = xs.length, sx = xs.reduce((a, b) => a + b, 0), sy = ys.reduce((a, b) => a + b, 0);
  const sxx = xs.reduce((a, b) => a + b * b, 0), sxy = xs.reduce((a, b, i) => a + b * ys[i], 0);
  const m = (n * sxy - sx * sy) / (n * sxx - sx * sx);
  const c = (sy - m * sx) / n;
  const yb = sy / n;
  const ssTot = ys.reduce((a, b) => a + (b - yb) ** 2, 0);
  const ssRes = ys.reduce((a, b, i) => a + (b - (m * xs[i] + c)) ** 2, 0);
  return { m, c, r2: 1 - ssRes / ssTot };
}
// confirm freqHz was derived as E/h (independent recompute), then fit √ν
const H = 6.62607015e-34, JKEV = 1.602176634e-16;
for (const r of MOSELEY.rows) {
  check(`${r.sym}: freqHz == Kα1 energy / h`, near(r.freqHz, r.ka1_keV * JKEV / H, r.freqHz * 1e-9),
    r.freqHz.toExponential(4), (r.ka1_keV * JKEV / H).toExponential(4));
}
const y = MOSELEY.rows.map(r => Math.sqrt(r.freqHz));
const fZ = fit(MOSELEY.rows.map(r => r.Z), y);
const fW = fit(MOSELEY.rows.map(r => r.W), y);
check(`√ν vs atomic number: R² > 0.999  (got ${fZ.r2.toFixed(6)})`, fZ.r2 > 0.999, fZ.r2.toFixed(6), "> 0.999");
check(`√ν vs atomic weight: R² lower than vs number  (${fW.r2.toFixed(6)} < ${fZ.r2.toFixed(6)})`, fW.r2 < fZ.r2, fW.r2.toFixed(6), `< ${fZ.r2.toFixed(6)}`);
// Moseley's law √ν = k(Z − σ): the line's Z-intercept (screening) is small, of order 1
const sigma = -fZ.c / fZ.m;
check(`Moseley screening offset σ is of order 1  (got ${sigma.toFixed(2)})`, sigma > 0.5 && sigma < 2.5, sigma.toFixed(2), "0.5 < σ < 2.5");
// the SAME Te/I inversion: on the weight axis, √ν steps BACKWARD from I to Te
const wByW = MOSELEY.rows.map((r, i) => ({ sym: r.sym, W: r.W, y: y[i] })).sort((a, b) => a.W - b.W);
let backSteps = [];
for (let i = 1; i < wByW.length; i++) if (wByW[i].y < wByW[i - 1].y) backSteps.push(`${wByW[i - 1].sym}→${wByW[i].sym}`);
check("on the weight axis √ν backsteps exactly once, at I→Te (the same inversion)",
  backSteps.length === 1 && backSteps[0] === "I→Te", backSteps.join(",") || "none", "I→Te");
const zByZ = MOSELEY.rows.map((r, i) => ({ sym: r.sym, Z: r.Z, y: y[i] })).sort((a, b) => a.Z - b.Z);
let zBack = 0; for (let i = 1; i < zByZ.length; i++) if (zByZ[i].y < zByZ[i - 1].y) zBack++;
check("on the atomic-number axis √ν never backsteps (monotonic)", zBack === 0, zBack, 0);

// ── IV · honest edge present ─────────────────────────────────────────────────
log.push("\nIV. THE HONEST EDGE — misses are named, including the flagged Pāṇini story");
check("at least four caveats/misses listed", MISSES.length >= 4, MISSES.length, "≥ 4");
check("technetium (eka-manganese, 43) names synthesis and trace natural production",
  MISSES.some(m => /technetium/i.test(m.what) && /43/.test(m.name + m.what) && /1937/.test(m.what) && /traces in nature/.test(m.what)), "", "technetium + 43 + 1937 + natural traces");
check("the Pāṇini homage is present AND flagged as a story, not a fact",
  MISSES.some(m => /Pāṇini/i.test(m.name + m.what) && /(conjecture|maybe|story|flag)/i.test(m.what + m.status)), "", "flagged");

// ── V · drift guard — the page embeds this dataset byte-for-byte ─────────────
log.push("\nV. DRIFT GUARD — the published page embeds this dataset verbatim");
const __dir = dirname(fileURLToPath(import.meta.url));
const pagePath = join(__dir, "..", "..", "public", "strata", "eka", "index.html");
let html = "";
try { html = readFileSync(pagePath, "utf8"); } catch { /* page may not be built yet */ }
if (html) {
  const prose = html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ");
  const words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
  const headline = `${words[tightCount]} of the ${words[quantCount]} numbers land within ${words[Math.round(META.tightClaim * 100)]} percent; all ${words[quantCount]} within ${words[Math.round(META.toleranceClaim * 100)]}.`;
  check("the visible quantitative headline agrees with the computed counts",
    prose.toLowerCase().includes(headline), "visible page prose", headline);
  const blocks = { META, PTABLE, PREDICTIONS, ORDERING, MOSELEY, MISSES };
  for (const [name, value] of Object.entries(blocks)) {
    const re = new RegExp(`<script id="data-${name}" type="application/json">([\\s\\S]*?)</script>`);
    const m = html.match(re);
    if (!m) { check(`page embeds data-${name}`, false, "missing", "present"); continue; }
    let embedded = null;
    try { embedded = JSON.parse(m[1]); } catch { /* */ }
    check(`page's data-${name} parses and equals data.mjs (drift guard)`,
      embedded !== null && JSON.stringify(embedded) === JSON.stringify(JSON.parse(JSON.stringify(value))),
      m[1].slice(0, 40) + "…", "byte-identical JSON");
  }
} else {
  log.push("  ..   page not built yet — run build-page.mjs then re-run for the drift guard");
}

// ── report ───────────────────────────────────────────────────────────────────
console.log(log.join("\n"));
console.log(`\n${PASS} passed, ${FAIL} failed.`);
process.exit(FAIL === 0 ? 0 : 1);
