// verify-your-room.mjs: the room meter at /tools/your-room/, checked offline.
//
//   node verify-your-room.mjs        (about a minute)
//
// The tool hands a stranger a number about their own house. Four things have to
// be true for that to be honest, and each is a family below.
//
//   1. THE PAGE RUNS THE BENCHED ENGINE. dsp/measure/synth/sweep in
//      public/tools/your-room/ are byte-for-byte the files in
//      research/natural-reverberation/ that clap-bench.mjs measured. If the page
//      could drift from them, every accuracy figure it prints would be about a
//      different instrument.
//   2. THE CHAIN WORKS END TO END. A real surveyed room is put through the
//      tool's own sweep, deconvolution and measurement, in Node, and has to come
//      back with the reverberation time it started with. This is the tool's path,
//      not a simplified version of it.
//   3. IT REFUSES RATHER THAN GUESSES. Handed noise, silence, and a recording far
//      too short to contain a decay, the reported estimator must return no answer.
//      A meter that always answers is the failure this whole design is against.
//   4. THE PAGE'S CLAIMS COME FROM THE FILES. Every figure the page prints about
//      its own accuracy is read out of clap-bench.json at runtime, so the page
//      must not carry a competing hand-typed copy, and the artifact must contain
//      the fields the page reads.
import { readFileSync, existsSync } from 'fs';
import { measureIR, OCTAVE_CENTRES } from './research/natural-reverberation/measure.mjs';
import { sweepPair, deconvolve, convolve, findTransients, auditRecording } from './research/natural-reverberation/sweep.mjs';
import { readZip, readEntry } from './research/natural-reverberation/zipread.mjs';
import { readWav } from './research/natural-reverberation/wav.mjs';

const ROOT = new URL('./', import.meta.url).pathname;
const TOOL = ROOT + 'public/tools/your-room/';
const LAB = ROOT + 'research/natural-reverberation/';

let pass = 0, fail = 0;
const log = [];
const ok = (c, m) => { (c ? pass++ : fail++); log.push(`  ${c ? '✓' : '✗ FAIL'} ${m}`); };

const I500 = OCTAVE_CENTRES.indexOf(500), I1K = OCTAVE_CENTRES.indexOf(1000);
const tMid = (m) => {
  const a = m.bands.octave[I500].rt60, b = m.bands.octave[I1K].rt60;
  return a !== null && b !== null ? (a + b) / 2 : null;
};

// ── family 1: the page runs the benched engine ──────────────────────────────
log.push('\n[1] the page runs the engine the bench measured (byte for byte):');
for (const f of ['dsp.mjs', 'measure.mjs', 'synth.mjs', 'sweep.mjs']) {
  const a = existsSync(TOOL + f) ? readFileSync(TOOL + f) : null;
  const b = readFileSync(LAB + f);
  ok(a !== null && a.equals(b), `${f} in the tool is identical to research/natural-reverberation/${f}`);
}
const page = readFileSync(TOOL + 'index.html', 'utf8');
ok(/from '\.\/measure\.mjs'/.test(page), 'the page imports measure.mjs from its own directory (not a copy elsewhere)');
ok(/from '\.\/sweep\.mjs'/.test(page), 'the page imports sweep.mjs from its own directory');
ok(!/MediaRecorder/.test(page),
  'the page never uses MediaRecorder: a lossy encode is entitled to move a short decay, so it captures raw samples');
ok(/echoCancellation:\s*false/.test(page) && /noiseSuppression:\s*false/.test(page) && /autoGainControl:\s*false/.test(page),
  'the page asks for echo cancellation, noise suppression and automatic gain to be OFF');
ok(/constraintsHonoured/.test(page),
  'and reads back whether the browser actually honoured that, rather than assuming it');

// ── family 2: the whole chain, on a real room ───────────────────────────────
log.push('\n[2] the tool\'s own chain recovers a known room (sweep → deconvolve → measure):');
{
  const zip = readZip(readFileSync(LAB + 'data/Audio.zip'));
  const spaces = JSON.parse(readFileSync(LAB + 'data/spaces.json', 'utf8'));
  // Three real rooms spanning the range, picked deterministically.
  const usable = spaces.filter((s) => s.rt60Broadband !== null).sort((a, b) => a.rt60Broadband - b.rt60Broadband);
  const picks = [usable[Math.round(usable.length * 0.15)], usable[Math.round(usable.length * 0.5)], usable[usable.length - 3]];
  let checked = 0;
  for (const sp of picks) {
    const wav = readWav(readEntry(zip, `Audio/${sp.file}`));
    const fs = wav.sampleRate;
    const ref = measureIR(wav.samples, fs);
    const want = tMid(ref);
    if (want === null) continue;
    checked++;
    const { sweep, inverse } = sweepPair(fs, 6, 40, Math.min(16000, fs / 2 - 100));
    const rec = convolve(sweep, wav.samples);
    const ir = deconvolve(rec, inverse, fs, Math.max(1.5, want * 4));
    const got = tMid(measureIR(ir, fs));
    const err = got === null ? null : Math.abs(got / want - 1) * 100;
    ok(got !== null && err < 25,
      `${sp.category}${sp.detail ? ' (' + sp.detail + ')' : ''}: ${want.toFixed(3)} s in, ${got === null ? 'refused' : got.toFixed(3) + ' s'} back${err === null ? '' : ` (${err.toFixed(1)}% off)`}`);
  }
  ok(checked >= 2, `at least two real rooms were exercised end to end (${checked})`);
}

// ── family 3: it refuses rather than guesses ────────────────────────────────
log.push('\n[3] handed something unmeasurable, it refuses:');
{
  const fs = 32000;
  const rnd = (() => { let a = 12345; return () => { a = (a * 1103515245 + 12345) & 0x7fffffff; return a / 0x7fffffff; }; })();

  const noise = new Float64Array(fs * 2);
  for (let i = 0; i < noise.length; i++) noise[i] = rnd() * 2 - 1;
  ok(tMid(measureIR(noise, fs)) === null, 'white noise with no impulse in it returns no T_mid');

  const silence = new Float64Array(fs);
  ok(tMid(measureIR(silence, fs)) === null, 'silence returns no T_mid');

  const clickOnly = new Float64Array(Math.round(fs * 0.02));
  clickOnly[0] = 1;
  ok(tMid(measureIR(clickOnly, fs)) === null, 'a 20 ms recording, far too short to hold a decay, returns no T_mid');

  // And the audit catches the two things that make a recording unusable before
  // any measurement is attempted.
  const clipped = new Float64Array(fs);
  for (let i = 0; i < clipped.length; i++) clipped[i] = i < 200 ? 1 : (rnd() - 0.5) * 0.01;
  ok(auditRecording(clipped, fs).clipped, 'a recording pinned at full scale is reported as clipped');
  const tiny = new Float64Array(fs);
  for (let i = 0; i < tiny.length; i++) tiny[i] = (rnd() - 0.5) * 0.001;
  ok(auditRecording(tiny, fs).tooQuiet, 'a recording with nothing loud in it is reported as too quiet');

  // The transient finder must find a clap and must not invent one in speech-like
  // noise that never jumps.
  const withClap = new Float64Array(fs * 3);
  for (let i = 0; i < withClap.length; i++) withClap[i] = (rnd() - 0.5) * 0.004;
  for (let i = 0; i < 120; i++) withClap[fs + i] += (rnd() * 2 - 1) * Math.exp(-i / 40);
  for (let i = 0; i < fs; i++) withClap[fs + 120 + i] += (rnd() - 0.5) * 0.5 * Math.exp(-i / (fs * 0.08));
  ok(findTransients(withClap, fs).length === 1, 'one clap in a quiet recording is found exactly once');
  const noClap = new Float64Array(fs * 3);
  for (let i = 0; i < noClap.length; i++) noClap[i] = (rnd() - 0.5) * 0.3;
  ok(findTransients(noClap, fs).length === 0, 'steady loud noise yields no transients (a loud moment is not an impulse)');
}

// ── family 4: the page's claims come from the artifacts ─────────────────────
log.push('\n[4] the page prints the bench, it does not describe it:');
{
  const bench = JSON.parse(readFileSync(LAB + 'data/clap-bench.json', 'utf8'));
  ok(Array.isArray(bench.snrs) && bench.snrs.length > 0, `clap-bench.json carries ${bench.snrs.length} signal-to-noise levels`);
  for (const kind of ['clap', 'sweep']) {
    const rows = bench.sources[kind];
    ok(Array.isArray(rows) && rows.length === bench.snrs.length, `  ${kind}: one row per level`);
    ok(rows.every((r) => typeof r.answered === 'number' && typeof r.n === 'number'), `  ${kind}: every row reports how many rooms answered`);
  }
  // The finding the page leans on: the sweep keeps answering where the clap stops.
  const worst = Math.min(...bench.snrs);
  const s = bench.sources.sweep.find((r) => r.snrDb === worst);
  const c = bench.sources.clap.find((r) => r.snrDb === worst);
  ok(s.answered > c.answered,
    `at the worst level benched (${worst} dB) the sweep answers ${s.answered}/${s.n} and the clap ${c.answered}/${c.n}, which is why the page recommends the sweep`);
  // The bias the page refuses to print: broadband keeps answering when T_mid cannot.
  const collapsed = bench.sources.clap.filter((r) => r.broadbandAnswered > r.answered);
  ok(collapsed.length > 0,
    `the broadband summary answers more often than T_mid at ${collapsed.length} of ${bench.snrs.length} levels, which is the survivorship bias the tool declines to report`);

  const rooms = readFileSync(TOOL + 'rooms.js', 'utf8');
  ok(/window\.YOUR_ROOM_DATA/.test(rooms), 'rooms.js publishes YOUR_ROOM_DATA');
  const data = JSON.parse(rooms.slice(rooms.indexOf('{'), rooms.lastIndexOf('}') + 1));
  ok(data.rooms.length > 100 && data.rooms.every((r) => typeof r.t === 'number'),
    `the comparison set is ${data.rooms.length} surveyed spaces, each with the same estimator the tool reports`);
  ok(!!data.bench && !!data.bench.sources, 'the bench travels with the data the page loads, so the page cannot print stale accuracy');
  ok(!/\b0\.95[0-9]?x\b/.test(page) && !/answered at 40 dB and/.test(page.replace(/still answering at 40/, '')),
    'the page carries no hand-typed copy of a bench figure it also prints from the file');
  // No survey audio may reach the reader through this tool.
  ok(!/Audio\.zip|\.wav/i.test(rooms), 'rooms.js ships no survey audio and no filenames pointing at any');
  ok(!/[—]/.test(page.replace(/<!--[\s\S]*?-->/g, '')), 'the page carries no em dashes (the house rule)');
}

console.log('YOUR ROOM: offline verification of /tools/your-room/');
console.log(log.join('\n'));
console.log(`\n${pass}/${pass + fail} checks passed.`);
if (fail > 0) { console.log('\nVERIFICATION FAILED'); process.exit(1); }
console.log('\nALL CHECKS PASS');
