#!/usr/bin/env node
// verify.mjs: the Tier A offline mirror for ten-millionths-of-a-second.
//
//   node research/ten-millionths-of-a-second/verify.mjs
//
// It imports the SHIPPED module, not a copy of it, and re-derives every number the page
// prints from the committed lab files. Nothing here opens a browser; the browser half is
// verify-ten-millionths-of-a-second.mjs at the repo root.
//
// The assertions worth reading are the ones that can go red without anybody touching the
// arithmetic of a published threshold:
//   * real rendered audio from three browser engines, replayed through the shipped
//     estimator, must give back the delay that was asked for;
//   * the whole-sample negative control must NOT give it back, and must instead land on
//     half a sample of whatever rate that engine was running;
//   * the machine listener's null and noise controls must be refused;
//   * the trace that once got through the reduction must still get through the OLD rule and
//     must be refused by the shipped one.

import { readFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as I from '../../public/strata/ten-millionths-of-a-second/itd.mjs';
import { DATA } from '../../public/strata/ten-millionths-of-a-second/data.js';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const rd = (p) => JSON.parse(readFileSync(join(HERE, 'data', p), 'utf8'));

let n = 0; let bad = 0;
const ok = (name, cond, extra = '') => {
  n += 1; if (!cond) bad += 1;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? `   ${extra}` : ''}`);
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;

console.log('\n-- synthesis, against the estimators -------------------------------');
for (const sr of [44100, 48000, 96000]) {
  for (const [f, tau] of [[500, 3], [700, 10], [700, -10], [1000, 25], [1400, 40], [3900, 100]]) {
    const p = I.synthPair({ sampleRate: sr, freq: f, itdUs: tau, mode: 'fine' });
    const ph = I.lagByPhase(p.L, p.R, sr, f);
    ok(`${sr} Hz, ${f} Hz carrier, ${tau} us in gives ${tau} us back`, near(ph.us, tau, 0.01), `${ph.us.toFixed(5)} us`);
    ok(`${sr} Hz, ${f} Hz carrier: no level difference is introduced`, Math.abs(ph.ildDb) < 1e-6);
  }
}
{
  const sr = 48000;
  const p = I.synthPair({ sampleRate: sr, freq: 700, itdUs: 10, mode: 'fine' });
  const cc = I.lagByCorrelation(p.L, p.R, sr, I.ceilingUs(700));
  ok('the correlation estimator, which shares no code with the phase one, agrees', near(cc.us, 10, 0.02), `${cc.us.toFixed(4)} us`);
}
{
  // The alias the correlation estimator used to fall into, kept as a regression, and now run
  // BOTH WAYS: the retired estimator is in the shipped module and is called here on the same
  // samples, so the fix has a live failing case rather than a story about one.
  const period = 1e6 / 3900;
  for (const sr of [44100, 48000]) {
    const p = I.synthPair({ sampleRate: sr, freq: 3900, itdUs: 100, mode: 'fine', modHz: 300, modDepth: 1, durMs: 300, rampMs: 50 });
    const at = Math.round(0.15 * sr);
    const w = { L: p.L.subarray(at, at + 1024), R: p.R.subarray(at, at + 1024) };
    const cc = I.lagByCorrelation(w.L, w.R, sr, I.ceilingUs(3900));
    ok(`${sr}: REGRESSION, the shipped correlation estimator answers 100 us at 3900 Hz`,
      near(cc.us, 100, 1), `${cc.us.toFixed(2)} us`);
  }
  // On the full-length stimulus (which is what the page prints), at 44.1 kHz the retired
  // estimator still lands about one carrier period low, and at 48 kHz it does not: the two
  // extra samples reach 158.7 us at one rate and 145.8 at the other, and the alias is at
  // 256.4. Both halves are asserted, because the page states both.
  for (const sr of [44100, 48000]) {
    const p = I.synthPair({ sampleRate: sr, freq: 3900, itdUs: 100, mode: 'fine', modHz: 300, modDepth: 1, durMs: 300, rampMs: 50 });
    const legacy = I.lagByCorrelationLegacy(p.L, p.R, sr, I.ceilingUs(3900)).us;
    const shipped = I.lagByCorrelation(p.L, p.R, sr, I.ceilingUs(3900)).us;
    const shouldAlias = sr === 44100;
    ok(`${sr}: the RETIRED estimator ${shouldAlias ? 'still falls into the alias' : 'happens to be right, which is why 48 kHz alone would never have caught this'}`,
      shouldAlias ? (legacy < 0 && Math.abs(legacy - (100 - period)) < 4) : near(legacy, 100, 1),
      `retired ${legacy.toFixed(3)} us, shipped ${shipped.toFixed(3)} us, one period low is ${(100 - period).toFixed(1)}`);
    const reach = ((Math.floor(I.ceilingUs(3900) * 1e-6 * sr) + 2) / sr) * 1e6;
    const aliasAt = period - 100;   // how far from zero the false peak sits, in us
    ok(`${sr}: and the reason is arithmetic: the retired search reached ${reach.toFixed(1)} us against a false peak ${aliasAt.toFixed(1)} us away`,
      (reach > aliasAt) === shouldAlias, `${reach.toFixed(3)} us`);
  }
}

console.log('\n-- the fine structure and the envelope are separable ---------------');
for (const sr of [44100, 48000]) {
  const carrier = I.synthPair({ sampleRate: sr, freq: 3900, itdUs: 100, mode: 'fine', modHz: 300, modDepth: 1 });
  const envel = I.synthPair({ sampleRate: sr, freq: 3900, itdUs: 100, mode: 'envelope', modHz: 300, modDepth: 1 });
  ok(`${sr}: carrier condition carries 100 us in the carrier`, near(I.lagByPhase(carrier.L, carrier.R, sr, 3900).us, 100, 0.01));
  ok(`${sr}: carrier condition carries nothing in the envelope`, Math.abs(I.envelopeLagUs(carrier.L, carrier.R, sr, 300)) < 0.05,
    `${I.envelopeLagUs(carrier.L, carrier.R, sr, 300).toFixed(5)}`);
  ok(`${sr}: envelope condition carries 100 us in the envelope`, near(I.envelopeLagUs(envel.L, envel.R, sr, 300), 100, 0.1),
    `${I.envelopeLagUs(envel.L, envel.R, sr, 300).toFixed(4)}`);
  ok(`${sr}: envelope condition carries nothing in the carrier`, Math.abs(I.lagByPhase(envel.L, envel.R, sr, 3900).us) < 0.01);
}

console.log('\n-- the whole-sample negative control -------------------------------');
for (const sr of [44100, 48000]) {
  const half = 5e5 / sr;
  const under = I.synthPair({ sampleRate: sr, freq: 700, itdUs: half * 0.9, mode: 'quantised' });
  ok(`${sr}: under half a sample (${half.toFixed(2)} us) the two channels are bit-identical`, I.channelsIdentical(under.L, under.R));
  const over = I.synthPair({ sampleRate: sr, freq: 700, itdUs: half * 1.1, mode: 'quantised' });
  ok(`${sr}: just over it, the delay jumps to a whole sample`, near(I.lagByPhase(over.L, over.R, sr, 700).us, 2 * half, 0.01));
}
{
  // the tell that makes the whole-sample control a control rather than a near miss: its
  // answer is a fact about the sample rate and nothing else, so it MOVES between rates,
  // where a threshold about a listener would not
  const a = I.synthPair({ sampleRate: 44100, freq: 700, itdUs: 30, mode: 'quantised' });
  const b = I.synthPair({ sampleRate: 48000, freq: 700, itdUs: 30, mode: 'quantised' });
  const ga = I.lagByPhase(a.L, a.R, 44100, 700).us;
  const gb = I.lagByPhase(b.L, b.R, 48000, 700).us;
  ok('the same requested delay comes out of the whole-sample control differently at 44.1 and 48 kHz',
    Math.abs(ga - gb) > 1.5, `${ga.toFixed(3)} against ${gb.toFixed(3)} us`);
  const fa = I.lagByPhase(...(() => { const p = I.synthPair({ sampleRate: 44100, freq: 700, itdUs: 30, mode: 'fine' }); return [p.L, p.R, 44100, 700]; })()).us;
  const fb = I.lagByPhase(...(() => { const p = I.synthPair({ sampleRate: 48000, freq: 700, itdUs: 30, mode: 'fine' }); return [p.L, p.R, 48000, 700]; })()).us;
  ok('and the page\'s own synthesis comes out the same at both rates, which is the difference',
    Math.abs(fa - fb) < 0.01, `${fa.toFixed(4)} against ${fb.toFixed(4)} us`);
}

console.log('\n-- the committed engine captures, replayed --------------------------');
let windows = 0;
for (const engine of ['chromium', 'firefox', 'webkit']) {
  const lab = rd(join('engines', `${engine}.json`));
  const shipped = DATA.engines.find((e) => e.engine === engine);
  ok(`${engine}: the page ships this engine's capture`, !!shipped);
  ok(`${engine}: version, rate and window match the lab file`,
    shipped.version === lab.engineVersion && shipped.sampleRate === lab.device.sampleRate
    && shipped.windowSamples === lab.windowSamples, `${shipped.version} at ${shipped.sampleRate} Hz`);
  for (const [name, c] of Object.entries(lab.captures)) {
    windows += 1;
    const s = shipped.captures[name];
    ok(`${engine}/${name}: the shipped audio is byte-identical to the lab capture`, s && s.L === c.L && s.R === c.R);
    const L = I.base64ToF32(c.L); const R = I.base64ToF32(c.R);
    if (c.mode === 'fine' && !c.modHz) {
      const got = I.lagByPhase(L, R, c.sampleRate, c.freq).us;
      ok(`${engine}/${name}: real rendered audio gives back ${c.itdUs} us`, near(got, c.itdUs, 0.02), `${got.toFixed(5)} us`);
    } else if (c.mode === 'quantised') {
      const expect = (Math.round(c.itdUs * 1e-6 * c.sampleRate) / c.sampleRate) * 1e6;
      const got = I.lagByPhase(L, R, c.sampleRate, c.freq).us;
      ok(`${engine}/${name}: NEGATIVE CONTROL came back as ${expect.toFixed(3)} us, not the ${c.itdUs} us asked for`,
        near(got, expect, 0.01), `${got.toFixed(4)} us`);
    } else if (c.mode === 'delaynode') {
      const m = I.lagByPhase(L, R, c.sampleRate, c.freq);
      const pred = I.linearInterpIldDb(c.freq, c.sampleRate, c.itdUs);
      ok(`${engine}/${name}: the DelayNode's measured level error ${m.ildDb.toFixed(4)} dB matches the linear-interpolation prediction ${pred.toFixed(4)} dB`,
        near(m.ildDb, pred, 0.002));
    } else if (c.mode === 'envelope') {
      ok(`${engine}/${name}: the envelope carries ${c.itdUs} us`, near(I.envelopeLagUs(L, R, c.sampleRate, c.modHz), c.itdUs, 0.5));
    } else if (c.mode === 'noise') {
      ok(`${engine}/${name}: NEGATIVE CONTROL, the estimator does not report ${c.itdUs} us from unrelated noise`,
        !near(I.lagByPhase(L, R, c.sampleRate, 700).us, c.itdUs, 1));
    }
  }
  // the browser did not touch the samples: passthrough windows equal what node synthesises
  const rate = lab.device.sampleRate;
  const start = Math.round((lab.windowAtMs / 1000) * rate);
  let exact = 0; let checked = 0;
  for (const [, c] of Object.entries(lab.captures)) {
    if (c.mode === 'delaynode' || c.bufferRate !== rate) continue;
    const p = I.synthPair({
      sampleRate: rate, freq: c.freq, itdUs: c.itdUs, mode: c.mode, modHz: c.modHz || 0,
      modDepth: c.modDepth, seed: c.seed || 1, durMs: lab.durMs, rampMs: lab.rampMs,
    });
    const L = I.base64ToF32(c.L); const R = I.base64ToF32(c.R);
    let same = true;
    for (let i = 0; i < L.length; i++) if (L[i] !== p.L[start + i] || R[i] !== p.R[start + i]) { same = false; break; }
    checked += 1; if (same) exact += 1;
  }
  ok(`${engine}: all ${checked} passthrough windows are bit-identical to what node synthesises`, exact === checked, `${exact}/${checked}`);
}
ok('thirty six audio windows were replayed', windows === 36, String(windows));

console.log('\n-- the machine listener, on real engine audio -----------------------');
for (const engine of ['chromium', 'firefox', 'webkit']) {
  const lab = rd(join('machine', `${engine}.json`));
  const half = lab.halfSampleUs;
  const fine = I.reduceStaircase(lab.traces.fine, I.MACHINE_RULES);
  ok(`${engine}: the machine reaches below a nanosecond on the page's own synthesis`,
    fine.converged && fine.thresholdUs < 0.01, fine.converged ? `${(fine.thresholdUs * 1000).toFixed(3)} ns` : fine.reason);
  const q = I.reduceStaircase(lab.traces.quantised, I.MACHINE_RULES);
  ok(`${engine}: NEGATIVE CONTROL, whole samples stall it within a factor of two of half a sample (${half.toFixed(2)} us)`,
    q.converged && q.thresholdUs > half / 2 && q.thresholdUs < half * 2, q.converged ? `${q.thresholdUs.toFixed(3)} us` : q.reason);
  ok(`${engine}: and that stall is four orders of magnitude away from the working one, so the control is not a near miss`,
    q.thresholdUs / fine.thresholdUs > 1000, `${(q.thresholdUs / fine.thresholdUs).toExponential(2)}`);
  for (const badMode of ['null', 'noise']) {
    const v = I.reduceStaircase(lab.traces[badMode], I.MACHINE_RULES);
    ok(`${engine}: NEGATIVE CONTROL, the ${badMode} generator is refused and emits no number`,
      !v.converged && v.thresholdUs === null, v.reason);
  }
  const shipped = DATA.engines.find((e) => e.engine === engine).machine;
  ok(`${engine}: the machine traces the page ships are the lab's traces`,
    JSON.stringify(shipped) === JSON.stringify(lab.traces));
}

console.log('\n-- the incident, both ways ------------------------------------------');
{
  const inc = rd('incident-null-passed.json');
  const loose = { ...I.MACHINE_RULES, catchEvery: 0, maxThresholdFraction: 0 };
  const before = I.reduceStaircase(inc.trace, loose);
  const after = I.reduceStaircase(inc.trace, I.MACHINE_RULES);
  ok('under the rule as it was, the null trace still produces a number, so the fix has a failing case behind it',
    before.converged && near(before.thresholdUs, inc.oldVerdict.thresholdUsApprox, 1),
    `${before.converged ? before.thresholdUs.toFixed(1) : 'refused'} us from a stimulus whose true delay is ${inc.groundTruthUs}`);
  ok('under the shipped rule it is refused', !after.converged && after.thresholdUs === null, after.reason);
  ok('the page ships that trace verbatim', JSON.stringify(DATA.incident.trace) === JSON.stringify(inc.trace));
}

console.log('\n-- the reduction, against known thresholds ---------------------------');
{
  const obs = rd(join('simulated', 'observers.json'));
  for (const o of obs.observers) {
    const rec = o.traces.map((t) => I.reduceStaircase(t));
    ok(`a listener whose true threshold is ${o.trueThresholdUs} us is recovered in all three committed traces`,
      rec.every((v) => v.converged && v.thresholdUs / o.trueThresholdUs > 0.4 && v.thresholdUs / o.trueThresholdUs < 2.5),
      rec.map((v) => (v.converged ? v.thresholdUs.toFixed(1) : 'refused')).join(', '));
    // re-derive the summary the page prints, rather than trusting the file
    let refused = 0; const ratios = [];
    for (let seed = 1; seed <= obs.seedsPerThreshold; seed++) {
      const st = I.runSimulated({ freq: obs.freqHz, sampleRate: obs.sampleRate, seed, pCorrect: I.simObserver(o.trueThresholdUs) });
      const v = I.reduceStaircase(I.traceOf(st));
      if (v.converged) ratios.push(v.thresholdUs / o.trueThresholdUs); else refused += 1;
    }
    ok(`and the committed refusal count for ${o.trueThresholdUs} us re-derives exactly`, refused === o.refused, `${refused} of ${obs.seedsPerThreshold}`);
    ok(`and so does its within-a-factor-of-two rate`,
      Math.abs(ratios.filter((r) => r > 0.5 && r < 2).length / ratios.length - o.withinFactorTwo) < 1e-12);
  }
  ok('the pooled window the page prints is the one in the lab file',
    DATA.simulated.pooled.ratioP025 === obs.pooled.ratioP025 && DATA.simulated.pooled.ratioP975 === obs.pooled.ratioP975);
}

console.log('\n-- the reduction, against listeners with nothing to find --------------');
{
  const ctl = rd(join('simulated', 'controls.json'));
  let leaked = 0;
  for (let seed = 1; seed <= ctl.controls.chance.seeds; seed++) {
    const st = I.runSimulated({ freq: ctl.freqHz, sampleRate: ctl.sampleRate, seed, pCorrect: I.chanceObserver() });
    if (I.reduceStaircase(I.traceOf(st)).converged) leaked += 1;
  }
  ok('the coin-flip leak rate re-derives from scratch', leaked === ctl.controls.chance.converged,
    `${leaked} of ${ctl.controls.chance.seeds}`);
  ok('and it is under one run in a hundred', leaked / ctl.controls.chance.seeds < 0.01,
    `${(100 * leaked / ctl.controls.chance.seeds).toFixed(3)} per cent`);
  for (const key of ['chance', 'alwaysCorrect', 'aboveEverything']) {
    const c = ctl.controls[key];
    ok(`NEGATIVE CONTROL: all three committed "${c.label}" traces are refused`,
      c.traces.every((t) => { const v = I.reduceStaircase(t); return !v.converged && v.thresholdUs === null; }),
      c.traces.map((t) => I.reduceStaircase(t).refusal).join(', '));
  }
  ok('a listener who presses the same key every time is never given a number',
    ctl.controls.alwaysCorrect.converged === 0);
  ok('and the honest cost is stated: a true threshold of 300 us is refused most of the time',
    1 - ctl.controls.nearCap.rate > 0.7, `${(100 * (1 - ctl.controls.nearCap.rate)).toFixed(1)} per cent refused`);
}

console.log('\n-- the sources -------------------------------------------------------');
{
  const strip = (s) => (s || '').replace(/<[^>]+>/g, '').replace(/&#(\d+);/g, (_, x) => String.fromCharCode(Number(x)))
    .replace(/&amp;/g, '&').replace(/[   ]/g, ' ').trim();
  for (const s of DATA.sources) {
    const raw = JSON.parse(readFileSync(join(HERE, 'data', 'sources', `${s.key}.json`), 'utf8'));
    ok(`${s.key}: doi, volume, issue, pages and year come from the deposit`,
      raw.doi === s.doi && raw.volume === s.volume && raw.issue === s.issue && raw.page === s.pages
      && raw.publishedPrint['date-parts'][0][0] === s.year,
      `${s.journal} ${s.volume}(${s.issue}) ${s.pages}, ${s.year}`);
    ok(`${s.key}: the authors come from the deposit`,
      JSON.stringify(s.authors) === JSON.stringify(raw.author.map((a) => `${a.given} ${a.family}`)));
    const abs = strip(raw.abstract);
    ok(`${s.key}: every sentence the page quotes appears verbatim in the deposited abstract`,
      s.quoted.every((q) => abs.includes(q)), `${s.quoted.length} sentence(s)`);
    ok(`${s.key}: the deposited abstract still hashes to what the page was built against`,
      I.fnv1a(abs) === s.abstractDigest);
  }
  const P = DATA.published;
  const kq = DATA.sources.find((s) => s.key === 'klumpp-eady-1956').quoted.join(' ');
  ok('the three Klumpp and Eady figures are in the quoted text',
    kq.includes(`(1) ${P.klumppNoiseUs} microseconds`) && kq.includes(`(2) ${P.klumppToneUs} microseconds`)
    && kq.includes(`(3) ${P.klumppClickUs} microseconds`) && kq.includes('ten listeners'));
  const mq = DATA.sources.find((s) => s.key === 'mills-1958').quoted.join(' ');
  ok('the Mills crossover and threshold figures are in the quoted text',
    mq.includes(`below about ${P.millsCrossoverHz} cps`) && /about\s*10\s*μsec/.test(mq) && mq.includes(`about ${P.millsIldDb} db`));
  const bq = DATA.sources.find((s) => s.key === 'brughera-2013').quoted.join(' ');
  ok('the Brughera limit is in the quoted text', bq.includes(`unmeasurably high just above ${P.brugheraLimitHz} Hz`)
    && bq.includes('four human listeners'));
  const hq = DATA.sources.find((s) => s.key === 'henning-1974').quoted.join(' ');
  ok('the Henning carrier and modulation are in the quoted text',
    hq.includes(`${P.henningModHz}-Hz modulation of a ${P.henningCarrierHz}-Hz carrier`));
  ok('the 1958 and 2013 crossovers are the same number, fifty five years apart',
    P.millsCrossoverHz === P.brugheraLimitHz);
  // ...and the two are not methodologically independent, which the page now says. Mills'
  // own abstract sources the crossover from a comparison with dichotic (headphone) data, and
  // Zwislocki and Feldman's headphone measurement of the same limit, in the same volume of
  // the same journal as Klumpp and Eady, puts it 100 cps lower. Both facts are in the repo,
  // so both have to be on the page.
  ok('Mills derived his crossover by comparison with headphone data of the era, in his own words',
    mq.includes('reported for dichotic stimulation') || strip(JSON.parse(readFileSync(join(HERE, 'data', 'sources', 'mills-1958.json'), 'utf8')).abstract).includes('reported for dichotic stimulation'));
  const zq = DATA.sources.find((s) => s.key === 'zwislocki-feldman-1956').quoted.join(' ');
  ok('the third, DISAGREEING measurement of the same limit is quoted on the page rather than left in data/',
    zq.includes('Around 1300 cps the jnd becomes so great that it cannot be measured'), zq.slice(-70));
  // The access disclosure: measured, committed, and asserted here rather than remembered.
  const acc = JSON.parse(readFileSync(join(HERE, 'data', 'sources', 'access.json'), 'utf8'));
  ok('all seven publisher landing pages were measured, and all seven refused',
    Object.keys(acc.records).length === 7 && Object.values(acc.records).every((r) => r.landingStatus === 403),
    Object.values(acc.records).map((r) => r.landingStatus).join(', '));
  ok('exactly three of the seven have a second bibliographic record in PubMed, and Mills is not one of them',
    Object.values(acc.records).filter((r) => r.pubmedId).length === 3 && !acc.records['mills-1958'].pubmedId,
    Object.entries(acc.records).filter(([, r]) => r.pubmedId).map(([k]) => k).join(', '));
  ok('and the DOI redirect independently carries volume, issue and first page for the six JASA papers',
    DATA.sources.filter((s) => (s.landing || '').includes('/jasa/article/')).length === 6
    && DATA.sources.filter((s) => (s.landing || '').includes('/jasa/article/')).every((s) => {
      const m = /\/jasa\/article\/(\d+)\/(\d+)\/(\d+)\//.exec(s.landing);
      return m && m[1] === s.volume && m[2] === s.issue && m[3] === s.pages.split('-')[0];
    }));
  ok('no quoted sentence carries an em dash, so the publish gate has nothing to catch',
    !DATA.sources.some((s) => s.quoted.join(' ').includes('\u2014')));
}

console.log('\n-- the head model ----------------------------------------------------');
{
  const c = I.speedOfSound(20);
  ok('speed of sound at 20 C is 343 m/s to within a metre per second', near(c, 343, 1), `${c.toFixed(2)}`);
  const r = I.radiusFromCircumference(57);
  const maxUs = I.woodworthUs(r, Math.PI / 2, c);
  ok('a 57 cm head gives a largest interaural delay between 600 and 750 us', maxUs > 600 && maxUs < 750, `${maxUs.toFixed(1)} us`);
  ok('the inversion round-trips to 90 degrees', near(I.azimuthForUs(r, maxUs, c), 90, 0.05));
  const oneDeg = I.woodworthUs(r, Math.PI / 180, c);
  ok('one degree off the midline is between 8 and 10 us on that head', oneDeg > 8 && oneDeg < 10, `${oneDeg.toFixed(2)} us`);
  ok('and the published floor is about one degree', near(I.azimuthForUs(r, DATA.published.millsUs, c), 1.1, 0.4),
    `${I.azimuthForUs(r, DATA.published.millsUs, c).toFixed(2)} degrees`);
}

console.log('\n-- the ceilings and the rules ----------------------------------------');
for (const f of [500, 700, 1000, 1200, 1400, 3900]) {
  ok(`${f} Hz: the ceiling never exceeds 0.45 of a period`, I.ceilingUs(f) <= (0.45 / f) * 1e6 + 1e-9, `${I.ceilingUs(f).toFixed(1)} us`);
}

console.log('\n-- the sweep\'s own confound, measured --------------------------------');
{
  // Ask the question the brief insists on: is there a reader-reachable setting where the
  // central comparison is true by construction? There is, and it is the top of the sweep. The
  // ceiling falls with the carrier period, the reportable range falls with the ceiling, and a
  // listener with a perfectly FLAT threshold gets refused more often at 1400 Hz than at 500
  // with no help from their ears at all. This measures how much, so the page can say it.
  const FREQS = [500, 700, 1000, 1200, 1400];
  for (const f of FREQS) {
    ok(`${f} Hz: the largest reportable threshold is ${I.maxReportableUs(f).toFixed(1)} us`,
      I.maxReportableUs(f) === Math.min(I.RULES.catchUs, I.ceilingUs(f)) * I.RULES.maxThresholdFraction);
  }
  ok('and it falls monotonically across the sweep, which is the confound the page names',
    FREQS.every((f, i) => i === 0 || I.maxReportableUs(f) <= I.maxReportableUs(FREQS[i - 1])),
    FREQS.map((f) => `${f}:${I.maxReportableUs(f).toFixed(0)}`).join(' '));
  const SEEDS = 300;
  for (const trueUs of [150, 200, 250]) {
    const rate = {};
    for (const f of FREQS) {
      let c = 0;
      for (let seed = 1; seed <= SEEDS; seed++) {
        const st = I.runSimulated({ freq: f, sampleRate: 48000, seed, pCorrect: I.simObserver(trueUs) });
        if (I.reduceStaircase(I.traceOf(st)).converged) c += 1;
      }
      rate[f] = c / SEEDS;
    }
    ok(`a FLAT ${trueUs} us simulated listener, identical at every frequency, is still refused more often at 1400 Hz than at 500`,
      rate[1400] < rate[500], FREQS.map((f) => `${f}:${(100 * rate[f]).toFixed(0)}%`).join(' '));
  }
  // The control that makes the above mean something: well below the reportable ceiling the
  // effect goes away, so this is a ceiling artefact and not the reduction simply being worse
  // at high frequencies.
  const easy = {};
  for (const f of FREQS) {
    let c = 0;
    for (let seed = 1; seed <= SEEDS; seed++) {
      const st = I.runSimulated({ freq: f, sampleRate: 48000, seed, pCorrect: I.simObserver(30) });
      if (I.reduceStaircase(I.traceOf(st)).converged) c += 1;
    }
    easy[f] = c / SEEDS;
  }
  ok('CONTROL: a flat 30 us listener, far below every reportable ceiling, is reported just as often at 1400 Hz as at 500',
    Math.abs(easy[1400] - easy[500]) < 0.1, FREQS.map((f) => `${f}:${(100 * easy[f]).toFixed(0)}%`).join(' '));
}
ok('the rules the page ships are the module\'s rules', JSON.stringify(DATA.rules) === JSON.stringify(I.RULES));
ok('and so are the machine\'s', JSON.stringify(DATA.machineRules) === JSON.stringify(I.MACHINE_RULES));
ok('and the published anchors', JSON.stringify(DATA.published) === JSON.stringify(I.PUBLISHED));

console.log('\n-- the files ---------------------------------------------------------');
for (const f of ['01-fetch-sources.mjs', '02-capture-engines.mjs', '03-machine-staircases.mjs',
  '04-simulated-observers.mjs', '05-build-page-data.mjs', 'verify.mjs', 'README.md']) {
  ok(`research/ten-millionths-of-a-second/${f} exists`, existsSync(join(HERE, f)));
}
ok('verify-ten-millionths-of-a-second.mjs exists at the repo root', existsSync(join(ROOT, 'verify-ten-millionths-of-a-second.mjs')));

console.log(`\n${bad === 0 ? 'ALL CHECKS PASS' : `${bad} FAILED`}   ${n - bad}/${n}`);
process.exit(bad === 0 ? 0 : 1);
