#!/usr/bin/env node
/** Offline verifier for /strata/the-window-you-cannot-win/.
 *  Part A recomputes every published number with the shared engine.
 *  Part B re-derives the bound and the sweep from scratch, independently of stats.json.
 *  Part C checks the page carries the artefacts and the engine byte for byte.
 */
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as E from './engine.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const PAGE = join(here, '../../public/strata/the-window-you-cannot-win/index.html');
const S = JSON.parse(readFileSync(join(here, 'stats.json'), 'utf8'));
let pass = 0, fail = 0;
const ok = (n, c, d = '') => { if (c) { pass++; console.log(`  ok   ${n}${d ? '  ' + d : ''}`); }
  else { fail++; console.log(`  FAIL ${n}${d ? '  ' + d : ''}`); } };
const near = (a, b, t) => Math.abs(a - b) <= t;

console.log('\nPart A — the bound and the windows');
ok('the published bound is 1/(4pi)', near(S.bound, 1 / (4 * Math.PI), 1e-12), S.bound.toFixed(8));
for (const w of S.windows) {
  ok(`${w.label}: product equals sigma_t * sigma_f`,
     near(w.product, w.sigma_t * w.sigma_f, 1e-12));
  ok(`${w.label}: never below the floor`, w.product >= S.bound - 1e-9,
     `ratio ${w.ratio.toFixed(4)}`);
}
const g = S.windows.filter(w => /Gauss/.test(w.label));
ok('a barely-truncated Gaussian attains the floor',
   Math.min(...g.map(w => w.ratio)) < 1.0005, `min ratio ${Math.min(...g.map(w => w.ratio)).toFixed(5)}`);
ok('truncating a Gaussian harder costs you', (() => {
  const a5 = g.find(w => /5/.test(w.label)), a3 = g.find(w => /3/.test(w.label));
  return a3.ratio > a5.ratio;
})());
ok('the rectangular window is an order of magnitude worse',
   S.windows.find(w => /Rect/i.test(w.label)).ratio > 10,
   `${S.windows.find(w => /Rect/i.test(w.label)).ratio.toFixed(1)}x`);
ok('Hann sits above the floor but close to it', (() => {
  const h = S.windows.find(w => /Hann/.test(w.label));
  return h.ratio > 1 && h.ratio < 1.1;
})());

console.log('\nPart A2 — the boundary');
ok('sixteen pairs were swept', S.boundary.length === 16);
ok('boundary rows are sorted by product',
   S.boundary.every((b, i) => i === 0 || S.boundary[i - 1].product <= b.product));
ok('every product equals df times dt',
   S.boundary.every(b => near(b.product, b.df * b.gapMs / 1000, 5e-3)));
ok('a pair with no window lists no windows',
   S.boundary.every(b => b.anyWindow === (b.windows.length > 0)));
const no = S.boundary.filter(b => !b.anyWindow).map(b => b.product);
const yes = S.boundary.filter(b => b.anyWindow).map(b => b.product);
ok('the two sets do not overlap', Math.max(...no) < Math.min(...yes),
   `no-window <= ${Math.max(...no)}, with-window >= ${Math.min(...yes)}`);
ok('stats.json agrees the separation is clean', S.separation.clean === true);
ok('the boundary sits near a product of one',
   Math.max(...no) <= 1 && Math.min(...yes) >= 0.8);
ok('monotone in separation on every window length',
   S.monotone.acrossSeparation.ok === S.monotone.acrossSeparation.rows,
   `${S.monotone.acrossSeparation.ok}/${S.monotone.acrossSeparation.rows}`);
ok('monotone in window length on every separation',
   S.monotone.acrossWindowLength.ok === S.monotone.acrossWindowLength.rows,
   `${S.monotone.acrossWindowLength.ok}/${S.monotone.acrossWindowLength.rows}`);

console.log('\nPart B — recomputed from scratch, not read from the artefact');
{
  const sp = E.spreads(E.WINDOWS.gaussian(4096, 5), S.fs);
  ok('Gaussian spread product recomputes to the floor',
     near(sp.product / E.GABOR_BOUND, 1, 1e-3), (sp.product / E.GABOR_BOUND).toFixed(6));
  // Analytic cross-check. For a Gaussian window exp(-t^2/(2 sd^2)) the spreads
  // are second moments of the ENERGY |w|^2, which is itself Gaussian with
  // standard deviation sd/sqrt(2). So sigma_t = sd/(sqrt2 fs) and
  // sigma_f = fs/(2 pi sqrt2 sd), whose product is exactly 1/(4pi).
  const N = 4096, sd = ((N - 1) / 2) / 5, R2 = Math.SQRT2;
  const st = sd / (R2 * S.fs), sf = S.fs / (2 * Math.PI * R2 * sd);
  ok('sigma_t matches sd/(sqrt2 fs) analytically', near(sp.sigma_t, st, st * 0.01),
     `${(sp.sigma_t * 1000).toFixed(3)} ms vs ${(st * 1000).toFixed(3)}`);
  ok('sigma_f matches fs/(2 pi sqrt2 sd) analytically', near(sp.sigma_f, sf, sf * 0.02),
     `${sp.sigma_f.toFixed(3)} Hz vs ${sf.toFixed(3)}`);
  ok('the analytic pair multiplies to the floor', near(st * sf, E.GABOR_BOUND, 1e-12));

  for (const key of ['hard', 'easy']) {
    const c = S.showcase[key];
    const opt = { fs: S.fs, dur: 1.2, f1: 440, df: c.df, clickGap: c.gapMs / 1000,
                  clickAt: 0.72, toneAt: 0.05, toneLen: 0.55 };
    const sw = E.sweep(E.makeSignal(opt), { ...opt, windowName: 'gaussian' }, S.lengths);
    ok(`${key} pair: the sweep reproduces exactly`,
       JSON.stringify(sw.map(s => [s.N, s.tones, s.clicks])) ===
       JSON.stringify(c.sweep.map(s => [s.N, s.tones, s.clicks])));
    // Monotonicity is only meaningful above the numerical floor: once a valley
    // has collapsed to a thousandth of the peak, the ordering of the remaining
    // digits is arithmetic noise, not physics.
    const FLOOR = 5e-3;
    const dips = sw.map(s => s.toneDip).filter(d => d > FLOOR);
    ok(`${key} pair: tone dips fall as the window lengthens`,
       dips.every((d, i) => i === 0 || d <= dips[i - 1] + 1e-9),
       `${dips.length} points above the ${FLOOR} floor`);
    const cd = sw.map(s => s.clickDip).filter(d => d > FLOOR);
    ok(`${key} pair: click dips rise as the window lengthens`,
       cd.every((d, i) => i === 0 || d >= cd[i - 1] - 1e-9));
  }
  const hard = S.showcase.hard;
  ok('the hard pair really has no winning window', !hard.sweep.some(s => s.both));
  ok('but it resolves each thing separately somewhere',
     hard.sweep.some(s => s.tones) && hard.sweep.some(s => s.clicks));
  ok('the easy pair really does have one', S.showcase.easy.sweep.some(s => s.both));

  // zero-padding must not change a verdict: it interpolates, it does not resolve
  const o = { fs: S.fs, dur: 1.2, f1: 440, df: 120, clickGap: 0.05, clickAt: 0.72,
              toneAt: 0.05, toneLen: 0.55 };
  const x = E.makeSignal(o);
  const a = E.tonesResolved(x, { ...o, N: 512, hop: 64, windowName: 'gaussian', pad: 4 });
  const b = E.tonesResolved(x, { ...o, N: 512, hop: 64, windowName: 'gaussian', pad: 16 });
  ok('quadrupling the zero-padding changes no verdict', a.resolved === b.resolved,
     `dips ${a.dip.toFixed(3)} vs ${b.dip.toFixed(3)}`);

  // the FFT itself, against a known transform
  const n = 64, re = new Float64Array(n), im = new Float64Array(n);
  for (let i = 0; i < n; i++) re[i] = Math.cos(2 * Math.PI * 5 * i / n);
  E.fft(re, im);
  let peak = 0;
  for (let k = 1; k < n / 2; k++) if (Math.hypot(re[k], im[k]) > Math.hypot(re[peak], im[peak])) peak = k;
  ok('the FFT puts a pure cosine in its own bin', peak === 5, `bin ${peak}`);
}

console.log('\nPart C — the page carries these artefacts');
const html = readFileSync(PAGE, 'utf8');
const prose = html.replace(/\s+/g, ' ');
const slot = html.match(/<script id="stats-data" type="application\/json">([\s\S]*?)<\/script>/);
ok('the page has the stats slot', !!slot);
ok('the embedded stats are byte-identical to stats.json',
   slot && slot[1] === readFileSync(join(here, 'stats.json'), 'utf8').trim());
const eng = createHash('sha256').update(readFileSync(join(here, 'engine.mjs'))).digest('hex');
const shipped = createHash('sha256')
  .update(readFileSync(join(here, '../../public/strata/the-window-you-cannot-win/engine.mjs')))
  .digest('hex');
ok('the shipped engine is byte-identical to the研究 one'.replace('研究', 'research '),
   eng === shipped, eng.slice(0, 16));
ok('the page loads that engine rather than a copy of the maths',
   prose.includes("import * as E from '/strata/the-window-you-cannot-win/engine.mjs'"));
ok('the page states the threshold is a convention',
   prose.includes('"Resolved" is a threshold, and thresholds are choices'));
ok('the page separates the exact floor from the empirical boundary',
   prose.includes('The floor is exact; the boundary at one is not'));
ok('the page says zero-padding buys no resolution',
   prose.includes('It buys no resolution whatsoever'));
ok('the page owns the two detector bugs',
   prose.includes('The measurement was wrong twice before it was right'));
ok('the page cites Gabor 1946 with pages', prose.includes('93 (1946) 429-457'));

// ── the live-audio mode, and the fence around it ───────────────────────────
// This mode is the one part of the page that produces no checked number, so what is
// verified here is the FENCE: that it uses the same engine, that it refuses to show
// a verdict it cannot earn, that it will not paint silence, and that it says all three.
ok('the live-audio control exists', html.includes('id="sig-mic"'));
ok('live audio goes through the same shared engine, not a second FFT',
   /E\.stft\(micBuf/.test(html) && !/function\s+fft\s*\(/.test(html));
ok('the verdicts are hidden while live audio is on',
   /\$\('verdict'\)\.hidden = live/.test(html) || /\$\('verdict'\)\.hidden = true/.test(html));
ok('there is a silence guard, not just a prose promise',
   /micRms < 1e-4/.test(html) && /micState = 'silent'/.test(html));
ok('silence blanks the canvas rather than stretching the noise floor',
   /clearSpec\(\); return;/.test(html) && /function clearSpec/.test(html));
ok('the page says why the verdicts are hidden there',
   prose.includes('a verdict there would be a guess wearing a measurement'));
ok('the page says silence is refused rather than drawn',
   prose.includes('Silence is refused rather than drawn'));
ok('the page says the audio never leaves the browser',
   prose.includes('nothing leaves your browser') && prose.includes('never uploaded and never stored'));
ok('the capture cannot hang forever on a dead device', /never hang on a silent device/.test(html));
ok('the microphone track is stopped after capture', /getTracks\(\)\.forEach\(\(t\) => t\.stop\(\)\)/.test(html));

ok('closing tags present', html.trimEnd().endsWith('</html>'));

console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'}  ${pass}/${pass + fail}`);
process.exit(fail === 0 ? 0 : 1);
