#!/usr/bin/env node
// verify-what-is-umami.mjs: checks /strata/what-is-umami/ ("Had We Nothing Sweeter Than Carrots").
//
//   node verify-what-is-umami.mjs            # the synergy law, the thresholds, the receptor model, the book counts, the prose
//   node verify-what-is-umami.mjs --mutate   # also break the engine on purpose; the checks must go red
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads the page's engine.mjs, index.html and series.json from https://artwaste.land into
// ./what-is-umami-files/ (the bytes your browser runs). Exit 0 = every check passed.
//
// What it does NOT check: the quotations, the published measurements (8x, 15-fold, 30-fold, the
// 0.012% and 0.00019% thresholds), or the Ngram capture against Google. Those were read by hand
// against the sources the page lists; the capture is research/umami/ngrams.json in the repository,
// and inside the repository this file re-derives series.json from it byte for byte.

import { existsSync, mkdirSync, writeFileSync, readFileSync, mkdtempSync, rmSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { tmpdir } from 'node:os';
import { execFileSync } from 'node:child_process';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'what-is-umami';
const MUTATE = process.argv.includes('--mutate');
const FILES = ['engine.mjs', 'index.html', 'series.json'];
let dir = join(here, 'public/strata', slug);
const inRepo = existsSync(join(dir, 'engine.mjs'));
if (!inRepo) {
  dir = resolve(`${slug}-files`); mkdirSync(dir, { recursive: true });
  for (const f of FILES) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);
const engineSrc = readFileSync(join(dir, 'engine.mjs'), 'utf8');
const html = readFileSync(join(dir, 'index.html'), 'utf8');
const series = JSON.parse(readFileSync(join(dir, 'series.json'), 'utf8'));
const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ')
  .replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/&middot;/g, '·').replace(/&amp;/g, '&').replace(/\s+/g, ' ');
// A figure is only "stated" if it sits in the same sentence (or table row) as what it is a figure of.
const rows = [...html.matchAll(/<tr>([\s\S]*?)<\/tr>/g)].map((m) => m[1].replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' '));
const sentences = text.split(/(?<=[.!?;:])\s+(?=[A-Z0-9“(])/).concat(rows);
const stated = (needles) => sentences.some((s) => needles.every((n) => s.includes(n)));

// ---- independent arithmetic, written without the engine ----
const G = 1218;
const law = (u, v) => u + G * u * v;
function bruteBest(c) { // best share of IMP in a total c, by scanning 200,001 splits
  let best = { f: 0, t: -1 };
  for (let k = 0; k <= 200000; k++) {
    const f = k / 200000, t = law(c * (1 - f), c * f) / c;
    if (t > best.t) best = { f, t };
  }
  return best;
}
// first year after which b leads a in every remaining year
const crossoverRef = (a, b, y0) => { let last = -1; a.forEach((v, i) => { if (b[i] <= v) last = i; }); return y0 + last + 1; };

async function suite(E, { quiet = false } = {}) {
  let pass = 0, fail = 0;
  const check = (name, ok, detail = '') => {
    if (ok) pass++; else fail++;
    if (!quiet) console.log(`${ok ? 'ok  ' : 'FAIL'} ${name}${detail ? '  (' + detail + ')' : ''}`);
    return ok;
  };
  const near = (a, b, tol) => Math.abs(a - b) <= tol;

  // ------------------------------------------------------------ 1. the law and the best split
  check('the engine\'s law is y = u + 1218uv at 400 mixtures', (() => {
    for (let a = 0; a < 20; a++) for (let b = 0; b < 20; b++) {
      const u = a * 0.007, v = b * 0.0013;
      if (!near(E.equivalent(u, v), law(u, v), 1e-12)) return false;
    }
    return true;
  })());
  let worstF = 0, worstT = 0;
  for (const c of [0.005, 0.01, 0.02, 0.05, 0.1]) {
    const b = E.bestSplit(c), r = bruteBest(c);
    worstF = Math.max(worstF, Math.abs(b.f - r.f)); worstT = Math.max(worstT, Math.abs(b.times - r.t) / r.t);
  }
  check('bestSplit agrees with a brute-force scan of 200,001 splits at five totals', worstF < 2e-5 && worstT < 1e-8, `share ${worstF.toExponential(1)}, strength ${worstT.toExponential(1)}`);
  check('the stated closed form: u = (1 + 1218c) / 2436 is the MSG in the best split', (() => {
    for (const c of [0.01, 0.05, 0.1]) if (!near(c * (1 - E.bestSplit(c).f), (1 + G * c) / 2436, 1e-12)) return false;
    return stated(['u = (1 + 1218c) / 2436']);
  })());
  const t01 = E.bestSplit(0.01).times, t05 = E.bestSplit(0.05).times, t10 = E.bestSplit(0.1).times;
  check('the prose\'s best-split strengths: 3.6x at 0.01, 15.7x at 0.05, 31.0x at 0.1 g per 100 ml',
    t01.toFixed(1) === '3.6' && t05.toFixed(1) === '15.7' && t10.toFixed(1) === '31.0' &&
    stated(['0.01 g per 100 ml', '3.6 times', '15.7 times', '31.0 times']), `${t01.toFixed(3)}, ${t05.toFixed(3)}, ${t10.toFixed(3)}`);
  check('inosinate alone scores zero under the working law (the page\'s claim)', E.equivalent(0, 0.5) === 0 && stated(['Inosinate alone, by the law, tastes of nothing']));

  // ------------------------------------------------------------ 2. thresholds against the law
  const v02 = E.mMToV(0.2);
  const mw = 12.011 * 10 + 1.008 * 11 + 14.007 * 4 + 22.990 * 2 + 15.999 * 8 + 30.974 + 7.5 * 18.015;
  check('the 7.5-hydrate of disodium inosinate weighs 527.28 g/mol (atomic weights recomputed)', near(E.MW_IMP_HYDRATE, mw, 0.05), mw.toFixed(2));
  check('0.2 mM of it is 0.0105 g per 100 ml, and the law predicts a 13.8-fold threshold fall',
    v02.toFixed(4) === '0.0105' && E.thresholdDrop(v02).toFixed(1) === '13.8' && stated(['0.2 mM (0.0105 g per 100 ml', '13.8 times']), E.thresholdDrop(v02).toFixed(3));
  check('0.25 g per 100 ml predicts 305.5, and the table measured 0.012% to 0.00019%, which is 63',
    E.thresholdDrop(0.25) === 305.5 && Math.round(0.012 / 0.00019) === 63 && stated(['305.5 times', '63 times', '0.012% to 0.00019%']));
  check('"twenty-four times that dose": 0.25 / 0.0105 rounds to 24', Math.round(0.25 / v02) === 24 && stated(['twenty-four times that dose']), (0.25 / v02).toFixed(2));
  check('"five times larger": 305.5 / 63 rounds to 5', Math.round(305.5 / (0.012 / 0.00019)) === 5 && stated(['five times larger']));

  // ------------------------------------------------------------ 3. the three printed forms
  check('J. Nutr. 2000\'s form makes 0.01 g of inosinate alone taste like 12 g of MSG',
    near(E.LAWS.jnutr2000.f(0, 0.01), 12.18, 1e-9) && stated(['0.01 g of inosinate on its own taste like 12 g of MSG']));
  const rec = E.LAWS.record1967.f(0.025, 0.025); // g per 100 ml; x10 = g per litre; /1000 = kg per litre
  check('the 1.218e8 constant makes 0.25 g of each per litre taste like 761 kg of MSG per litre',
    Math.floor(rec * 10 / 1000) === 761 && stated(['a quarter of a gram of each in a litre', '761 kilograms']), `${(rec * 10 / 1000).toFixed(1)} kg/L`);
  check('the working form in LAWS is the engine\'s law', near(E.LAWS.used.f(0.03, 0.004), E.equivalent(0.03, 0.004), 1e-15));

  // ------------------------------------------------------------ 4. the receptor model
  let worstLimit = 0;
  for (const alpha of [2, 10, 30, 100]) for (const i of [1e-4, 1e-3]) {
    // the gap from the linear form is second order in i: (alpha - 1) i^2 at most, so divide it out
    const g = 1e-12, lim = E.occupancy(g, i, alpha) / E.occupancy(g, 0, alpha);
    worstLimit = Math.max(worstLimit, Math.abs(lim - (1 + (alpha - 1) * i)) / ((alpha - 1) * i * i));
  }
  check('small doses: the allosteric model reduces to 1 + (alpha - 1) i, Yamaguchi\'s form, to second order in i', worstLimit <= 1 + 1e-6, `gap / ((alpha-1) i^2) at most ${worstLimit.toFixed(4)}`);
  check('large nucleotide: the low-glutamate factor levels off at alpha', near(E.occupancy(1e-9, 1e7, 30) / E.occupancy(1e-9, 0, 30), 30, 1e-4));
  check('large glutamate: both curves reach 1', E.occupancy(1e9, 0, 30) > 0.999999 && E.occupancy(1e9, 1, 30) > 0.999999);
  check('ec50Shift is where the curve with the nucleotide crosses one half', (() => {
    for (const [i, a] of [[1, 30], [0.3, 10]]) {
      const g = 1 / E.ec50Shift(i, a);
      if (!near(E.occupancy(g, i, a), 0.5, 1e-12)) return false;
    }
    return true;
  })());

  // ------------------------------------------------------------ 5. the book counts
  const y0 = series.yearStart;
  const c45 = E.crossover(series.four, series.five, y0), cUM = E.crossover(series.msg, series.umami, y0);
  check('the engine\'s crossover matches an independent one on both pairs', c45 === crossoverRef(series.four, series.five, y0) && cUM === crossoverRef(series.msg, series.umami, y0), `${c45}, ${cUM}`);
  const leads = series.four.map((v, i) => (series.five[i] > v ? y0 + i : null)).filter((x) => x && x < c45);
  check('"five" leads in every year from 2014, and before that only in 1901, 1926 and 2011',
    c45 === 2014 && leads.join(',') === '1901,1926,2011' && stated(['From 2014 on', 'every year']) && stated(['2011, and 1901 and 1926']), leads.join(','));
  // before 1913 both words sit at the floor (misdated books) and 'umami' noise-leads there; the page says 'above the floor'
  const floorYears = series.msg.map((v, i) => (y0 + i < 1950 && series.umami[i] > v ? y0 + i : null)).filter(Boolean);
  const firstUmami = series.msg.findIndex((v, i) => y0 + i > 1950 && series.umami[i] > v) + y0;
  check('"umami" first passes "monosodium glutamate" in 2009 and leads every year from 2012',
    firstUmami === 2009 && cUM === 2012 && floorYears.every((y) => y < 1913) && stated(['first passes “monosodium glutamate” above the chart\'s floor in 2009', 'every year since 2012']), `${firstUmami}, ${cUM}; floor leads ${floorYears.join(',')}`);
  check('the floor is real: both controls read above zero in 1900, before either could exist',
    series.msg[0] > 0 && series.ajinomoto[0] > 0 && stated(['most visibly in 1900']), `${series.msg[0]}, ${series.ajinomoto[0]}`);
  check('"umami" is near zero until the late 1970s: under 3 per billion every year 1908 to 1975, over 9 in 1979',
    series.umami.slice(8, 76).every((v) => v < 3) && series.umami[79] > 9 && stated(['near zero until the late 1970s']));

  return { pass, fail };
}

const E = await import(pathToFileURL(join(dir, 'engine.mjs')).href);
const res = await suite(E);
let bad = res.fail > 0;

// Inside the repository: series.json must be exactly what the committed raw capture reduces to.
if (inRepo && existsSync(join(here, 'research/umami/build-series.mjs'))) {
  const before = readFileSync(join(dir, 'series.json'), 'utf8');
  execFileSync(process.execPath, [join(here, 'research/umami/build-series.mjs')], { stdio: 'ignore' });
  const after = readFileSync(join(dir, 'series.json'), 'utf8');
  const same = before === after;
  console.log(`${same ? 'ok  ' : 'FAIL'} series.json is byte-identical to a rebuild from research/umami/ngrams.json`);
  if (!same) bad = true;
}
console.log(`\n${res.pass} passed, ${res.fail} failed`);

if (MUTATE) {
  const mutants = [
    ['gamma 1218 read as 1281', [/export const GAMMA_IMP = 1218;/, 'export const GAMMA_IMP = 1281;']],
    ['the product term summed instead', [/u \+ gamma \* u \* v/, 'u + gamma * (u + v)']],
    ['best split loses its 1 +', [/\(1 \+ gamma \* c\) \/ \(2 \* gamma\)/, '(gamma * c) / (2 * gamma)']],
    ['the hydrate weighed as the anhydrous salt', [/MW_IMP_HYDRATE = 527\.28/, 'MW_IMP_HYDRATE = 392.17']],
    ['nucleotide activates the receptor alone', [/\(g \* \(1 \+ alpha \* i\)\) \/ \(1 \+ g \+ i \+ alpha \* g \* i\)/, '(g * (1 + alpha * i) + i) / (1 + g + i + alpha * g * i)']],
    ['crossover takes the first lead, not the lasting one', [/if \(b\[i\] <= a\[i\]\) last = i;/, 'if (b[i] > a[i]) { last = i - 1; break; }']],
    ['threshold drop squared', [/=> 1 \+ gamma \* v;/, '=> (1 + gamma * v) ** 2;']],
  ];
  console.log('\n--mutate: each planted fault must turn at least one check red');
  const mdir = mkdtempSync(join(tmpdir(), 'umami-mutants-'));
  let k = 0;
  for (const [name, [re, rep]] of mutants) {
    if (!re.test(engineSrc)) { console.log(`FAIL mutant "${name}": pattern not found in engine`); bad = true; continue; }
    const f = join(mdir, `engine-${k++}.mjs`);
    writeFileSync(f, engineSrc.replace(re, rep));
    const M = await import(pathToFileURL(f).href);
    const r = await suite(M, { quiet: true });
    const caught = r.fail > 0;
    console.log(`${caught ? 'ok  ' : 'FAIL'} mutant caught: ${name}  (${r.fail} checks red)`);
    if (!caught) bad = true;
  }
  rmSync(mdir, { recursive: true, force: true });
}
process.exit(bad ? 1 : 0);
