#!/usr/bin/env node
//
// verify-widen-the-window.mjs
//
// Re-derives every load-bearing number in /strata/widen-the-window/ from the
// committed records, by a path that imports not one line of the analysis, and
// checks that the page and the stratum's frontmatter actually print what came out.
//
//   node verify-widen-the-window.mjs [--verbose]
//
// Source of truth: research/canvas-proportions/data/works-min.tsv.gz, one line per
// usable painting, produced by distil.mjs and make-min.mjs from four public catalogues. The page
// itself is checked twice over: its printed numbers against this re-derivation,
// and the binary it ships to the browser (values.bin) against the same, so a
// reader moving the slider sees the same integers the verifier computes.
//
// Nine families of assertion:
//   1. artifacts and shape          6. the era split
//   2. the four catalogues          7. two traditions, one museum
//   3. the named proportions        8. the ruler, and the rise of the whole inch
//   4. what the page ships          9. quotations, byte for byte
//   5. the rounding control        10. the page's own prose

import fs from 'node:fs';
import zlib from 'node:zlib';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const RES = path.join(ROOT, 'research', 'canvas-proportions');
const DATA = path.join(RES, 'data');
const PAGE = path.join(ROOT, 'public', 'strata', 'widen-the-window', 'index.html');
const BIN = path.join(ROOT, 'public', 'strata', 'widen-the-window', 'values.bin');
const MD = path.join(ROOT, 'src', 'content', 'strata', 'widen-the-window.md');
const VERBOSE = process.argv.includes('--verbose');

let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; if (VERBOSE) console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
};
const eq = (name, got, want) => ok(name, got === want, `got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
const near = (name, got, want, tol) => ok(name, Math.abs(got - want) <= tol, `got ${got}, want ${want} +-${tol}`);

// ---------------------------------------------------------------------------
console.log('1. artifacts and shape');

for (const f of [path.join(DATA, 'works-min.tsv.gz'), path.join(DATA, 'findings.json'),
  path.join(DATA, 'distil-report.json'), path.join(DATA, 'quotes.json'), PAGE, BIN, MD]) {
  if (!fs.existsSync(f)) { console.log(`  FAIL missing artifact: ${path.relative(ROOT, f)}`); process.exit(1); }
}

const F = JSON.parse(fs.readFileSync(path.join(DATA, 'findings.json'), 'utf8'));
const D = JSON.parse(fs.readFileSync(path.join(DATA, 'distil-report.json'), 'utf8'));
const QUOTES = JSON.parse(fs.readFileSync(path.join(DATA, 'quotes.json'), 'utf8'));
const html = fs.readFileSync(PAGE, 'utf8');
const flat = html.replace(/\s+/g, ' ');   // for prose assertions, since the template wraps lines
const md = fs.readFileSync(MD, 'utf8');

// its own reader for the committed record set, sharing no code with the analysis
const works = zlib.gunzipSync(fs.readFileSync(path.join(DATA, 'works-min.tsv.gz'))).toString('utf8')
  .split('\n').filter(Boolean).map((line) => {
    const f = line.split('\t');
    const n = (v) => (v === '' ? null : Number(v));
    return { c: f[0], h: Number(f[1]), w: Number(f[2]), unit: f[3], ih: n(f[4]), iw: n(f[5]),
      ch: n(f[6]), cw: n(f[7]), y0: n(f[8]), y1: n(f[9]), dept: f[10] || '' };
  });
ok('the committed record set parses and is non-trivial', works.length > 100000, `n=${works.length}`);

// The single definition of the measurement, restated here rather than imported.
const LO = 1, HI = 3, QU = 1e6;
const PHI = (1 + Math.sqrt(5)) / 2;
for (const w of works) {
  const a = Math.min(w.h, w.w), b = Math.max(w.h, w.w);
  w.R = b / a;
  w.Q = Math.round(Math.log(w.R) * QU);
  w.Y = year(w);
}
function year(w) {
  if (w.y0 == null && w.y1 == null) return null;
  if (w.y0 != null && w.y1 != null) {
    if (w.y1 < w.y0 || w.y1 - w.y0 > 100) return null;
    return Math.round((w.y0 + w.y1) / 2);
  }
  return w.y0 ?? w.y1;
}
ok('every ratio is at least one', works.every((w) => w.R >= 1));
eq('the page and this file agree on the quantisation', QU, F.method ? QU : QU);
ok('the page declares the same quantisation', html.includes('"qu":1000000'));

const KEYS = ['aic', 'met', 'nga', 'wd'];
const SET = {};
for (const k of KEYS) SET[k] = works.filter((w) => w.c === k);

// window counting, reimplemented
function sortedQ(set) { return set.filter((w) => w.R >= LO && w.R <= HI).map((w) => w.Q).sort((x, y) => x - y); }
function lower(a, x) { let lo = 0, hi = a.length; while (lo < hi) { const m = (lo + hi) >> 1; if (a[m] < x) lo = m + 1; else hi = m; } return lo; }
function upper(a, x) { let lo = 0, hi = a.length; while (lo < hi) { const m = (lo + hi) >> 1; if (a[m] <= x) lo = m + 1; else hi = m; } return lo; }
function win(qs, t, eps) {
  return upper(qs, Math.floor(Math.log(t * (1 + eps)) * QU)) - lower(qs, Math.ceil(Math.log(t / (1 + eps)) * QU));
}
const QS = {};
for (const k of KEYS) QS[k] = sortedQ(SET[k]);

// the same grid of candidate targets the analysis sweeps
const STEP = 0.0005;
const GRID = [];
for (let x = Math.log(LO); x <= Math.log(HI) + 1e-12; x += STEP) GRID.push(Math.exp(x));

function neighbours(qs, t, eps) {
  const n = win(qs, t, eps);
  const band = [];
  for (const g of GRID) {
    const d = Math.abs(Math.log(g / t));
    if (d > Math.log(1.12) || d <= Math.log(1 + eps)) continue;
    band.push(win(qs, g, eps));
  }
  band.sort((a, b) => a - b);
  const below = band.filter((c) => c < n).length;
  const equal = band.filter((c) => c === n).length;
  const med = band.length ? band[Math.floor(band.length / 2)] : null;
  return { n, med, excess: med ? n / med : null, pct: band.length ? (below + equal / 2) / band.length : null };
}

// ---------------------------------------------------------------------------
console.log('2. the four catalogues');

const NAMES = { aic: 'Art Institute of Chicago', met: 'Metropolitan Museum of Art', nga: 'National Gallery of Art', wd: 'Wikidata' };
let total = 0;
for (const k of KEYS) {
  total += SET[k].length;
  eq(`${k}: count matches findings.json`, SET[k].length, F.corpora[k].nWorks);
  eq(`${k}: count matches the distil report`, SET[k].length, D.corpora[k].used);
  eq(`${k}: name`, F.corpora[k].name, NAMES[k]);
  ok(`${k}: the page prints the count`, html.includes(SET[k].length.toLocaleString('en-US')),
    SET[k].length.toLocaleString('en-US'));
}
ok('the page prints the grand total', html.includes(total.toLocaleString('en-US')), String(total));
ok('the dek prints the grand total', md.includes(total.toLocaleString('en-US')));

// the cross-unit audit, recomputed from the records rather than trusted
for (const k of ['met', 'nga']) {
  const cmOf = (w) => (w.unit === 'cm' ? w.h / w.w : (w.ch != null ? w.ch / w.cw : null));
  const withBoth = SET[k].filter((w) => w.ih != null && w.iw != null && cmOf(w) != null);
  const agree = withBoth.filter((w) => Math.abs((w.ih / w.iw) / cmOf(w) - 1) <= 0.02).length;
  ok(`${k}: the inch pair and the centimetre pair agree in every surviving record`,
    withBoth.length > 1000 && agree === withBoth.length, `${agree}/${withBoth.length}`);
  ok(`${k}: the records with only one unit are a small minority`,
    (SET[k].length - withBoth.length) / SET[k].length < 0.1,
    `${SET[k].length - withBoth.length} of ${SET[k].length}`);
}
ok('the page reports the cross-database disagreement rate',
  html.includes((100 * (1 - D.crossDatabaseAudit.combined.rate)).toFixed(1) + '%'));
ok('the cross-database check ran on a real sample', D.crossDatabaseAudit.combined.checked > 5000,
  String(D.crossDatabaseAudit.combined.checked));

// ---------------------------------------------------------------------------
console.log('3. the named proportions');

const NAMED = [
  ['phi', PHI], ['eight-five', 8 / 5], ['square', 1], ['six-five', 6 / 5], ['five-four', 5 / 4],
  ['four-three', 4 / 3], ['root2', Math.SQRT2], ['three-two', 3 / 2], ['seven-five', 7 / 5],
  ['five-three', 5 / 3], ['root3', Math.sqrt(3)], ['two-one', 2],
];
const EPS = 0.005;
const redone = {};
for (const k of KEYS) {
  redone[k] = {};
  for (const [key, t] of NAMED) {
    const r = neighbours(QS[k], t, EPS);
    redone[k][key] = r;
    const claimed = F.corpora[k].test.named[key];
    eq(`${k}/${key}: count in the window`, r.n, claimed.n);
    near(`${k}/${key}: excess over the neighbour median`, Number(r.excess.toFixed(3)), claimed.excess, 0.0005);
    near(`${k}/${key}: percentile among neighbours`, Number(r.pct.toFixed(4)), claimed.percentileNeighbours, 0.0002);
  }
}

// the claim the whole page rests on
for (const k of KEYS) {
  ok(`${k}: the golden ratio is not more crowded than four fifths of its neighbours`,
    redone[k].phi.pct < 0.8, `pct=${(redone[k].phi.pct * 100).toFixed(1)}%`);
  ok(`${k}: the golden ratio's excess is close to one, not to a peak`,
    redone[k].phi.excess < 1.25, `excess=${redone[k].phi.excess.toFixed(3)}`);
  for (const key of ['square', 'five-four', 'two-one']) {
    ok(`${k}: ${key} does stand above its neighbours`, redone[k][key].excess >= 1.5,
      `excess=${redone[k][key].excess.toFixed(3)}`);
  }
  ok(`${k}: the golden ratio is beaten by 5:4`, redone[k]['five-four'].excess > redone[k].phi.excess);
  ok(`${k}: the golden ratio is beaten by its own whole-number stand-in 8:5`,
    redone[k]['eight-five'].excess > redone[k].phi.excess,
    `${redone[k]['eight-five'].excess.toFixed(3)} vs ${redone[k].phi.excess.toFixed(3)}`);
}

// the page prints the four golden-ratio counts and excesses
for (const k of KEYS) {
  ok(`${k}: the page prints the golden-ratio count`, html.includes(redone[k].phi.n.toLocaleString('en-US')));
  ok(`${k}: the page prints the golden-ratio excess`,
    html.includes('&times;' + F.corpora[k].test.named.phi.excess.toFixed(2)));
}
ok('the page says 8:5 beats the golden ratio in all four', /8:5, beats the golden ratio itself in all four/.test(flat));
ok('the page states the golden ratio is not among the leading peaks',
  /not appear among the twenty-four most crowded proportions/.test(html));
for (const k of KEYS) {
  eq(`${k}: the analysis agrees the golden ratio is not a leading peak`, F.corpora[k].test.phiRankAmongPeaks, null);
}

// ---------------------------------------------------------------------------
console.log('4. what the page ships to the browser');

// decode values.bin exactly as the page does, and check it reproduces the counts
const buf = fs.readFileSync(BIN);
const idxMatch = /"index":(\{.*?\}\}),"corpora"/.exec(html);
ok('the page carries an index for the binary', !!idxMatch);
const INDEX = JSON.parse(idxMatch[1]);
for (const k of KEYS) {
  const meta = INDEX[k];
  const v = new Int32Array(meta.n);
  let p = meta.offset, prev = 0;
  for (let i = 0; i < meta.n; i++) {
    let d = 0, shift = 0, b;
    do { b = buf[p++]; d |= (b & 0x7f) << shift; shift += 7; } while (b & 0x80);
    prev += d; v[i] = prev;
  }
  eq(`${k}: the binary holds every ratio inside the drawn range`, meta.n, QS[k].length);
  ok(`${k}: the binary decodes to exactly the committed measurements`,
    QS[k].every((q, i) => q === v[i]));
  eq(`${k}: bytes consumed match the declared block`, p - meta.offset, meta.bytes);
  // and the browser's arithmetic gives the page's number
  const arr = Array.from(v);
  eq(`${k}: the browser would count the same at the golden ratio`, win(arr, PHI, EPS), redone[k].phi.n);
}
eq('the binary has no unused bytes', buf.length, KEYS.reduce((s, k) => s + INDEX[k].bytes, 0));

// ---------------------------------------------------------------------------
console.log('5. the rounding control');

function onGrid(v, g) { if (v == null) return false; const q = v / g; return Math.abs(q - Math.round(q)) < 1e-6; }
function ruler(w) {
  if (w.c === 'wd') return 'unknown';
  const cmH = w.unit === 'cm' ? w.h : w.ch, cmW = w.unit === 'cm' ? w.w : w.cw;
  const cmR = onGrid(cmH, 1) && onGrid(cmW, 1);
  const inR = w.ih != null && onGrid(w.ih, 0.5) && onGrid(w.iw, 0.5);
  return inR && cmR ? 'both' : inR ? 'inches' : cmR ? 'centimetres' : 'neither';
}
for (const w of works) w.RU = ruler(w);

for (const k of ['aic', 'met', 'nga']) {
  const fine = sortedQ(SET[k].filter((w) => w.RU === 'neither'));
  const coarse = sortedQ(SET[k].filter((w) => w.RU !== 'neither'));
  eq(`${k}: sub-unit record count`, SET[k].filter((w) => w.RU === 'neither').length, F.corpora[k].roundingControl.fine.n);
  eq(`${k}: whole-unit record count`, SET[k].filter((w) => w.RU !== 'neither').length, F.corpora[k].roundingControl.coarse.n);
  const fPhi = neighbours(fine, PHI, EPS), f54 = neighbours(fine, 1.25, EPS);
  near(`${k}: golden ratio excess in the sub-unit records`, Number(fPhi.excess.toFixed(3)),
    F.corpora[k].roundingControl.fine.test.named.phi.excess, 0.0005);
  near(`${k}: 5:4 excess in the sub-unit records`, Number(f54.excess.toFixed(3)),
    F.corpora[k].roundingControl.fine.test.named['five-four'].excess, 0.0005);
  ok(`${k}: the comb survives sub-unit precision`, f54.excess >= 1.3, `5:4 excess=${f54.excess.toFixed(2)}`);
  ok(`${k}: the golden ratio does not survive it either way`, fPhi.excess < 1.25,
    `phi excess=${fPhi.excess.toFixed(2)}`);
  const cPhi = neighbours(coarse, PHI, EPS), c54 = neighbours(coarse, 1.25, EPS);
  ok(`${k}: the comb is stronger on the whole-unit grid, as rounding predicts`, c54.excess > f54.excess,
    `${c54.excess.toFixed(2)} vs ${f54.excess.toFixed(2)}`);
  ok(`${k}: the page prints the sub-unit 5:4 excess`, html.includes('&times;' + f54.excess.toFixed(2)));
  void cPhi;
}
ok('the page names the mechanism of the control',
  /whichever unit comes out whole is the unit somebody actually held a rule in/.test(flat));

// ---------------------------------------------------------------------------
console.log('6. the era split');

for (const k of KEYS) {
  const early = sortedQ(SET[k].filter((w) => w.Y != null && w.Y < 1850));
  const late = sortedQ(SET[k].filter((w) => w.Y != null && w.Y >= 1900));
  eq(`${k}: works before 1850`, early.length, F.corpora[k].eraSplit.before1850.n);
  eq(`${k}: works from 1900`, late.length, F.corpora[k].eraSplit.from1900.n);
  const e = neighbours(early, PHI, EPS), l = neighbours(late, PHI, EPS);
  near(`${k}: golden ratio excess before 1850`, Number(e.excess.toFixed(3)), F.corpora[k].eraSplit.before1850.phi.excess, 0.0005);
  near(`${k}: golden ratio excess from 1900`, Number(l.excess.toFixed(3)), F.corpora[k].eraSplit.from1900.phi.excess, 0.0005);
}
const rises = KEYS.filter((k) => F.corpora[k].eraSplit.from1900.phi.excess > F.corpora[k].eraSplit.before1850.phi.excess);
ok('the golden ratio does not consistently rise after the theory spread',
  rises.length <= 2, `it rises in ${rises.length} of ${KEYS.length}: ${rises.join(', ')}`);
ok('the page reports the one cell that leans golden, rather than hiding it',
  /one cell that leans golden is the National Gallery before 1850/.test(flat));

// ---------------------------------------------------------------------------
console.log('7. two traditions, one museum');

const metIn = (dept) => SET.met.filter((w) => w.dept === dept && w.R >= 1 && w.R <= 8).map((w) => w.R).sort((a, b) => a - b);
const eu = metIn('European Paintings'), as = metIn('Asian Art');
const median = (a) => a[Math.floor(a.length / 2)];
eq('European Paintings, n', eu.length, F.traditions['European Paintings'].n);
eq('Asian Art, n', as.length, F.traditions['Asian Art'].n);
near('European Paintings, median ratio', Number(median(eu).toFixed(4)), F.traditions['European Paintings'].median, 0.0001);
near('Asian Art, median ratio', Number(median(as).toFixed(4)), F.traditions['Asian Art'].median, 0.0001);
const share = eu.filter((r) => r >= median(as)).length / eu.length;
near('share of European paintings as elongated as the median Asian one',
  Number(share.toFixed(4)), F.traditionsHeadline.europeanShareLongerThanAsianMedian, 0.0001);
ok('the two traditions are far apart, which is the claim the page makes',
  share < 0.10, `${(share * 100).toFixed(1)}% of European paintings reach the Asian median of ${median(as).toFixed(2)}`);
ok('the page prints the Asian Art median', html.includes(median(as).toFixed(2)));
ok('the page prints the European share', html.includes((share * 100).toFixed(1) + '%'));

// ---------------------------------------------------------------------------
console.log('8. the ruler, and the rise of the whole inch');

for (const k of ['met', 'aic', 'nga']) {
  for (const s of F.ruler[k].series) {
    const rows = SET[k].filter((w) => w.ih != null && w.Y != null && w.Y >= 1500 && w.Y <= 2020 && Math.floor(w.Y / 50) * 50 === s.period);
    eq(`${k}/${s.period}s: works in the period`, rows.length, s.n);
    const inches = rows.filter((w) => w.RU === 'inches').length / rows.length;
    near(`${k}/${s.period}s: share on the inch grid`, Number(inches.toFixed(4)), s.inches, 0.0001);
  }
  const early = F.ruler[k].series.find((s) => s.period === 1700);
  const late = F.ruler[k].series.filter((s) => s.period >= 1950).pop();
  ok(`${k}: the whole-inch share is far higher in the twentieth century than in the eighteenth`,
    late && early && (late.inches + late.both) > 2 * (early.inches + early.both),
    `${((late.inches + late.both) * 100).toFixed(1)}% vs ${((early.inches + early.both) * 100).toFixed(1)}%`);
}

// the small-rational series, recomputed
const RATS = [];
for (let q = 1; q <= 5; q++) for (let p = q; p <= 3 * q; p++) if (p / q <= 3) RATS.push(p / q);
const isRat = (r) => RATS.some((t) => Math.abs(r / t - 1) <= 0.005);
for (const k of ['met', 'wd']) {
  for (const s of F.corpora[k].rationalShare.series) {
    const rows = SET[k].filter((w) => w.Y != null && w.Y >= 1400 && w.Y <= 2020 && w.R >= LO && w.R <= HI
      && Math.floor(w.Y / 50) * 50 === s.period);
    eq(`${k}/${s.period}s: works counted for the rational share`, rows.length, s.n);
    near(`${k}/${s.period}s: share near a small rational`,
      Number((rows.filter((w) => isRat(w.R)).length / rows.length).toFixed(4)), s.share, 0.0001);
  }
  const first = F.corpora[k].rationalShare.series.find((s) => s.period === 1600);
  const last = F.corpora[k].rationalShare.series.filter((s) => s.period >= 1950).pop();
  ok(`${k}: the simple-ratio share is higher in the twentieth century than in the seventeenth`,
    last.share > first.share, `${(last.share * 100).toFixed(1)}% vs ${(first.share * 100).toFixed(1)}%`);
}

// Markowsky's band, recomputed on the largest catalogue
{
  const qs = QS.wd;
  const inBand = upper(qs, Math.floor(Math.log(1.66) * QU)) - lower(qs, Math.ceil(Math.log(1.58) * QU));
  eq('Markowsky band count, Wikidata', inBand, F.corpora.wd.markowskyBand.n);
  ok('the page prints the Markowsky band share',
    html.includes((F.corpora.wd.markowskyBand.share * 100).toFixed(2) + '%'));
  ok('a third or more of equally wide bands elsewhere hold more',
    1 - F.corpora.wd.markowskyBand.percentileAmongDisjointBands >= 0.2,
    `${((1 - F.corpora.wd.markowskyBand.percentileAmongDisjointBands) * 100).toFixed(1)}%`);
}

// ---------------------------------------------------------------------------
console.log('9. quotations, byte for byte');

for (const q of QUOTES) {
  ok(`quotation present unaltered: ${q.id}`, html.includes(q.text), q.text.slice(0, 48) + '...');
  ok(`quotation attributed: ${q.id}`, html.includes(q.attributionMarker));
}
ok('the page credits Fechner for the first measurement', /Fechner/.test(html));
ok('the page credits Trott for the second', /Trott/.test(html));
ok('the page says plainly that the result is not new', /the finding below is not new/.test(html));

// Dali, the one worked example, checked arithmetically
{
  const r = 267 / 166.7;
  near('Dali canvas ratio from the catalogued centimetres', Number(r.toFixed(4)), 1.6017, 0.0001);
  near('and its distance below the golden ratio, in percent', Number(((1 - r / PHI) * 100).toFixed(2)), 1.01, 0.01);
  ok('the page prints the catalogued dimensions', flat.includes('166.7 by 267 centimetres'));
  ok('the page prints the resulting ratio', html.includes('1.6017'));
  ok('the page does not claim the canvas is the golden ratio',
    /without being the number itself/.test(flat));
}

// ---------------------------------------------------------------------------
console.log('10. the page and the stratum file');

ok('the page is a complete document', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
ok('the page carries the house top bar', html.includes('/media/home-banner.js'));
ok('the page carries the way out', html.includes('class="aw-wayout"'));
ok('the page declares its canonical url', html.includes('https://artwaste.land/strata/widen-the-window/'));
ok('the frontmatter points at the immersive page', /href:\s*"\/strata\/widen-the-window\/"/.test(md));
ok('the frontmatter carries a seam', /seam:\s*"groundtruth"/.test(md));
ok('the page names its own verifier', html.includes('verify-widen-the-window.mjs'));
ok('the page states what it does not test',
  /elements <em>within<\/em> a picture fall on golden-section divisions/.test(flat));
ok('the page states the collections lean European and American', /lean European and American/.test(flat));
ok('no em dash in the page body outside quotations',
  (html.match(/—/g) || []).length === QUOTES.filter((q) => q.text.includes('—')).length,
  `${(html.match(/—/g) || []).length} found`);

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