#!/usr/bin/env node
// verify-observed-and-assumed.mjs — the gate for /strata/observed-and-assumed/.
//
//   node research/gamelan-tuning/verify-observed-and-assumed.mjs
//
// Re-derives every number the page prints, re-measures all 54 audio clips through the
// same estimator the browser runs, re-reads Ellis against three transcriptions, and
// checks that the data block embedded in the page still equals what analyse.mjs
// produces right now. Exits non-zero on any failure.
//
// It also carries NEGATIVE CONTROLS: the estimator is fed synthesised tones of known
// frequency, including an inharmonic bar spectrum and a decaying one, so a broken
// estimator cannot pass by agreeing with itself.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { analyse, ELLIS, loadScala, loadDaMuSc, internalSteps, periodMeasured } from './analyse.mjs';
import { check as pageCheck } from './sync-page.mjs';
import { readSclDir, ladder, steps, parseScl, centsOf, mean, sd, median } from './scl.mjs';
import { readWav } from './wav.mjs';
import { AW } from './kit.mjs';
import { INSTRUMENTS, DEGREES, OCTAVE_KEY, clipName } from './prepare-audio.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const AUDIO = path.join(HERE, '..', '..', 'public', 'strata', 'observed-and-assumed', 'audio');
const PAGE = path.join(HERE, '..', '..', 'public', 'strata', 'observed-and-assumed', 'index.html');

let pass = 0, fail = 0;
const ok = (cond, msg) => { cond ? pass++ : fail++; console.log(`  ${cond ? '✓' : '✗ FAIL'}  ${msg}`); };
const near = (a, b, e, msg) => ok(Math.abs(a - b) <= e, `${msg}  (${a} vs ${b}, tol ${e})`);

const R = analyse();

// ---------------------------------------------------------------- 1. the parser
console.log('\n1. the Scala parser, on cases with known answers');
ok(Math.abs(centsOf('2/1').cents - 1200) < 1e-9, '2/1 is 1200 cents');
ok(Math.abs(centsOf('3/2').cents - 701.955) < 1e-3, '3/2 is 701.955 cents');
ok(Math.abs(centsOf('700.0').cents - 700) < 1e-9, 'a decimal token is read as cents, not as a ratio');
ok(Math.abs(centsOf('2').cents - 1200) < 1e-9, 'a bare integer is a ratio, so 2 is 1200 cents');
{
  const t = '! x.scl\n!\ndesc\n 3\n!\n 100.0\n 3/2\n 2/1\n';
  const s = parseScl(t, 'x');
  ok(s.count === 3 && Math.abs(s.degrees[1].cents - 701.955) < 1e-3, 'a mixed cents/ratio file parses');
  let threw = false;
  try { parseScl('! y\n!\ndesc\n 4\n!\n 100.0\n', 'y'); } catch (e) { threw = true; }
  ok(threw, 'a file that declares more degrees than it carries is rejected, not silently truncated');
}

// ------------------------------------------------------- 2. the pitch estimator
console.log('\n2. the pitch estimator, against synthesised tones of known frequency');
function synth(hz, rate, secs, partials, decay) {
  const n = Math.round(rate * secs);
  const x = new Float64Array(n);
  for (let i = 0; i < n; i++) {
    const t = i / rate;
    let v = 0;
    for (const p of partials) v += p.a * Math.sin(2 * Math.PI * hz * p.r * t) * Math.exp(-(decay ? decay * p.r : 0) * t);
    x[i] = v * 0.3;
  }
  return x;
}
const HARM = [{ r: 1, a: 1 }, { r: 2, a: 0.4 }, { r: 3, a: 0.2 }];
const BAR = R.barSpectrum.partialRatios.slice(0, 4).map((r, i) => ({ r, a: 1 / (1 + i) }));
for (const f of [220, 440.0, 519.45, 1207.75]) {
  const y = AW.estimateFundamental(synth(f, 44100, 1.2, HARM), 44100, { fmin: 100, fmax: 6000 });
  near(y.hz, f, 0.6, `harmonic tone at ${f} Hz is recovered`);
}
for (const f of [261.0, 905.0]) {
  const y = AW.estimateFundamental(synth(f, 44100, 1.2, BAR), 44100, { fmin: 100, fmax: 6000 });
  near(y.hz, f, 0.6, `INHARMONIC bar spectrum at ${f} Hz is recovered`);
}
{
  const y = AW.estimateFundamental(synth(330, 44100, 1.5, BAR, 2.2), 44100, { fmin: 100, fmax: 6000 });
  near(y.hz, 330, 1.0, 'a DECAYING bar tone at 330 Hz is recovered (higher modes die first)');
}
{
  // The negative control that matters: a bar whose second mode is LOUDER than its
  // first. The naive estimator must be fooled and the fundamental estimator must not.
  const loud2 = R.barSpectrum.partialRatios.slice(0, 3).map((r, i) => ({ r, a: i === 1 ? 1.3 : 1 }));
  const x = synth(300, 44100, 1.2, loud2);
  const n1 = AW.estimatePitch(x, 44100, { fmin: 100, fmax: 6000 });
  const n2 = AW.estimateFundamental(x, 44100, { fmin: 100, fmax: 6000 });
  ok(Math.abs(n1.hz - 300) > 100, 'the NAIVE estimator is fooled when the second mode is louder (as it should be)');
  near(n2.hz, 300, 0.8, 'the fundamental estimator is not fooled');
}
{
  // Silence must throw rather than return a confident wrong number.
  let threw = false;
  try { AW.estimateFundamental(new Float64Array(200), 44100); } catch (e) { threw = true; }
  ok(threw, 'too short a signal throws instead of inventing a pitch');
}

// ------------------------------------------------- 3. Ellis, against every copy
console.log('\n3. Ellis p. 518, against three independent transcriptions');
for (const c of R.ellis.checks) ok(c.agrees, c.what);
ok(R.ellis.allChecksPass, 'all Ellis checks pass');
{
  const l = ELLIS.row94.ladder;
  const st = [];
  for (let i = 1; i < l.length; i++) st.push(l[i] - l[i - 1]);
  ok(JSON.stringify(st) === JSON.stringify(R.ellis.row94Steps), 'row 94 steps are differences of row 94, not typed in twice');
  ok(st.some((x) => x !== 240), 'row 94 is not five equal steps');
  ok(ELLIS.row95.ladder.every((v, i) => v === 240 * i), 'row 95 IS five equal steps');
  ok(/properly 0 240 480 720 960 1200/.test(ELLIS.properly), 'the p. 526 quotation contains the assumed ladder and the word properly');
  const html = fs.readFileSync(PAGE, 'utf8');
  ok(html.includes('Observed, and Assumed'), 'the page carries its own title');
}

// ------------------------------- 4. our own measurement, re-run from the clips
console.log('\n4. re-measuring all 54 shipped clips through the same estimator the page runs');
{
  let worst = 0, worstKey = '';
  let n = 0;
  for (const inst of INSTRUMENTS) {
    const rec = R.ourMeasurement.instruments.find((i) => i.prefix === inst.prefix);
    for (const d of [...DEGREES, OCTAVE_KEY]) {
      const file = clipName(inst.prefix, d);
      const p = path.join(AUDIO, file);
      ok(fs.existsSync(p), `clip ${file} is present`);
      const w = readWav(p);
      const f = AW.estimateFundamental(w.samples, w.sampleRate, { fmin: 100, fmax: 6000 });
      const want = d === OCTAVE_KEY ? rec.octaveKeyHz : rec.keys.find((k) => k.degree === d).hz;
      // Compare in Hz, not cents: the reported figure is rounded to two decimals, and
      // half of that last digit is worth 0.07 cents at 130 Hz but 0.004 cents at 1800.
      const diff = Math.abs(f.hz - want);
      if (diff > worst) { worst = diff; worstKey = file; }
      n++;
    }
  }
  ok(n === 54, `54 clips measured (got ${n})`);
  ok(worst <= 0.005, `every re-measurement reproduces the reported figure to the last printed digit (worst ${worst.toFixed(5)} Hz, ${worstKey})`);
}
{
  const O = R.ourMeasurement;
  ok(O.instruments.length === 9, 'nine instruments');
  ok(O.stepCount === 36, '36 internal steps');
  near(O.rmsFrom240, Math.sqrt(mean(O.instruments.flatMap((i) => i.steps).map((x) => (x - 240) ** 2))), 0.05,
    'the headline rms is the rms of the steps actually listed');
  ok(O.partialTraps.length === 1, 'exactly one key where the loudest partial is not the fundamental');
  near(O.partialTraps[0].loudestOverFundamental, R.barSpectrum.partialRatios[1], 0.06,
    'that key\'s loudest partial sits near the ideal bar\'s second mode');
}

// ----------------------------------------- 5. the sign test, recomputed by hand
console.log('\n5. the sign test');
{
  for (const s of R.ourMeasurement.signTest) {
    const above = s.values.filter((v) => v > 240).length;
    ok(above === s.above240, `${s.step}: the reported count of steps above 240 is the count in the listed values`);
    near(s.mean, mean(s.values), 0.06, `${s.step}: the reported mean is the mean of the listed values`);
  }
  const decisive = R.ourMeasurement.signTest.filter((s) => s.pTwoSided < 0.01);
  ok(decisive.length >= 2, `at least two steps are significant at p < 0.01 (got ${decisive.length})`);
  const notSig = R.ourMeasurement.signTest.filter((s) => s.pTwoSided > 0.05);
  ok(notSig.length >= 1, `and at least one step is NOT significant, which the page states (got ${notSig.length})`);
  // Sanity on the binomial: 9 of 9 must give 2/2^9.
  // The reported p is rounded to three significant figures, so compare at that precision.
  near(R.ourMeasurement.signTest.find((s) => s.above240 === 9).pTwoSided, 2 / 512, 1e-5,
    'a 9-of-9 split gives the exact two-sided binomial probability');
}

// ----------------------------------------------- 6. Surjodiningrat, recomputed
console.log('\n6. Surjodiningrat 1972, from the committed DaMuSc extract');
{
  const S = R.surjodiningrat;
  const dam = loadDaMuSc().filter((r) => r.RefID === '12' && r.stepsCents.length === 5);
  ok(dam.length === 28, `28 slendro gamelans in the extract (got ${dam.length})`);
  ok(S.n === dam.length, 'the analysis uses all of them');
  const pooled = dam.flatMap((r) => r.stepsCents.slice(0, -1));
  near(S.stepMean, mean(pooled), 0.05, 'pooled internal-step mean');
  near(S.stepSd, sd(pooled), 0.05, 'pooled internal-step standard deviation');
  ok(S.withinFive <= S.withinTen, 'the within-5 count cannot exceed the within-10 count');
  ok(S.withinFive < S.n && S.withinTen < S.n, 'not every gamelan is five equal steps');
  const periods = dam.map((r) => r.stepsCents.reduce((a, b) => a + b, 0));
  near(S.periodMean, mean(periods), 0.05, 'mean period');
  ok(S.periodOver1200 === periods.filter((p) => p > 1200).length, 'the count of stretched octaves is the count in the data');
  // The extract must still carry its own provenance.
  const src = fs.readFileSync(path.join(HERE, 'data', 'damusc-sources.csv'), 'utf8');
  ok(/Surjodiningrat/.test(src) && /Gadjah Mada/.test(src), 'the committed source record names Surjodiningrat and Gadjah Mada');
  ok(/0\.1 percent/.test(src), 'and carries the study\'s own stated precision');
}

// -------------------------------------------------- 7. the compilation corpus
console.log('\n7. the Scala compilation and its curation');
{
  const rows = loadScala();
  ok(rows.length === 241, `241 curated entries (got ${rows.length})`);
  const scls = readSclDir(path.join(HERE, 'data', 'scl'));
  ok(scls.length === rows.length, 'every shipped .scl file has a curation row and vice versa');
  for (const r of rows) ok(!!r.note && r.note.trim().length > 3, `${r.name} carries a recorded reason`) && 0;
  const core = rows.filter((r) => r.cls === 'MEASURED' && r.system === 'slendro' && r.scale.count === 5);
  ok(core.length === R.scala.n, 'the core count matches');
  ok(R.scala.periodWrittenAsRatio === core.filter((r) => !periodMeasured(r)).length,
    'the count of entries whose period was supplied rather than measured');
  ok(R.scala.periodWrittenAsRatio > 0,
    'at least one entry has a supplied period, which is why internal steps are used throughout');
  // Nothing in the analysis may touch the closing step.
  for (const s of R.scala.sets) ok(s.internal.length === 4, `${s.id}: four internal steps, the closing one excluded`) && 0;
}

// ------------------------------------------------------- 8. the like-for-like
console.log('\n8. the comparison with European temperaments');
{
  const H = R.headline;
  for (const k of Object.keys(H)) {
    near(H[k].relative, H[k].cents / H[k].unit, 1e-4, `${k}: the fraction is the cents divided by the step`);
  }
  ok(H.surjodiningrat.relative < H.temperaments.relative,
    `the best gamelan corpus is MORE equal than the temperaments (${(H.surjodiningrat.relative * 100).toFixed(2)}% vs ${(H.temperaments.relative * 100).toFixed(2)}%)`);
  ok(H.surjodiningrat.cents > H.temperaments.cents,
    'and in raw cents it is the larger departure, which the page also says');
  ok(R.temperaments.n >= 15, `the comparison set has ${R.temperaments.n} temperaments`);
  const names = R.temperaments.sets.map((s) => s.id);
  for (const must of ['werck3', 'vallotti', 'kirnberger3', 'meanquar'])
    ok(names.includes(must), `the comparison set includes ${must}`);
}

// --------------------------------------------------- 9. the hierarchy, ordered
console.log('\n9. the hierarchy of scatter');
{
  const h = R.hierarchy;
  ok(h.length === 4, 'four quantities');
  const last = h[h.length - 1];
  ok(h.slice(0, -1).every((x) => x.cents < last.cents),
    `the departure from five-equal (${last.cents} c) is larger than every other scatter here`);
  near(last.cents, R.surjodiningrat.medianRmsFrom240, 1e-9, 'and it is the Surjodiningrat median, not a separate number');
  near(h[0].cents, R.ourMeasurement.withinGamelanRms, 1e-9, 'the within-gamelan figure is our own measurement');
}

// -------------------------------------------------------------- 10. the octave
console.log('\n10. the octave');
{
  const O = R.octave;
  ok(O.ourOctaves.length === 9, 'nine measured octaves of our own');
  near(O.ourMean, mean(O.ourOctaves.map((o) => o.cents)), 0.05, 'their mean is the mean of the listed values');
  ok(O.ourMean > 1200, 'our own mean octave is wider than 1200');
  ok(O.surjodiningratMean > 1200, 'so is Surjodiningrat\'s');
  ok(O.ourOver1200 >= 7, `${O.ourOver1200} of 9 of our instruments are stretched`);
  // The page prints three figures that disagree; make sure it still prints all three.
  const html = fs.readFileSync(PAGE, 'utf8');
  ok(html.includes('1219') && html.includes('1208'), 'the page still prints the two figures it could not reconcile');
}

// ----------------------------------------------- 11. the bar spectrum, re-solved
console.log('\n11. the bar spectrum');
{
  // Re-solve the equation here, independently of analyse.mjs, and compare. Plugging the
  // page's ROUNDED roots back into cos(x)cosh(x) would not work as a test: cosh grows
  // exponentially, so at x = 20 a rounding of 5e-5 moves the product by thousands. The
  // roots have to be compared as roots.
  const f = (x) => Math.cos(x) * Math.cosh(x) - 1;
  const solve = (n) => {
    const guess = ((2 * n + 1) * Math.PI) / 2;
    let lo = guess - 0.6, hi = guess + 0.6;
    for (let i = 0; i < 300; i++) { const m = (lo + hi) / 2; if (f(lo) * f(m) <= 0) hi = m; else lo = m; }
    return (lo + hi) / 2;
  };
  const roots = R.barSpectrum.roots;
  roots.forEach((x, i) => near(x, solve(i + 1), 5e-5, `root ${i + 1} of cos(x)cosh(x) = 1 re-solves to the reported ${x}`));
  // and the bracket really does contain a sign change, so the bisection is not fooling itself
  for (let n = 1; n <= roots.length; n++) {
    const g = ((2 * n + 1) * Math.PI) / 2;
    ok(f(g - 0.6) * f(g + 0.6) < 0, `the bracket around ${g.toFixed(3)} contains a sign change`);
  }
  near(R.barSpectrum.partialRatios[1], 2.7565, 1e-3, 'the second partial ratio is the textbook 2.7565');
  near(R.barSpectrum.partialRatios[2], 5.4039, 1e-3, 'the third is 5.4039');
  ok(R.barSpectrum.partialRatios[0] === 1, 'the first is 1 by construction');
}

// ------------------------------------------------- 12. the honesty apparatus
console.log('\n12. the checks that came out against us');
{
  ok(R.shapeCheck.disagreements.length === 1, 'exactly one entry fails the shape check, and it is reported');
  ok(R.shapeCheck.disagreements[0].id === 'slendro_ang2', 'it is the Banyuwangi angklung');
  const withIt = R.sensitivity.find((v) => v.label === 'C. the Scala core, 23 sets');
  const without = R.sensitivity.find((v) => v.label === 'C, minus the one shape-check failure');
  ok(withIt && without, 'the sensitivity table reports the answer with and without it');
  ok(R.samePairs.length === 4 && R.reproducibility.pairs === 3,
    'four name-matched pairs, one of which is the same measurement copied and is excluded');
  const copied = R.samePairs.find((p) => p.maxDiff <= 2);
  ok(!!copied, 'the copied pair is identified rather than counted as independent');
  ok(R.reproducibility.medianRms > 0, 'a reproducibility figure is reported');
  ok(R.reproducibility.medianRms < R.surjodiningrat.medianRmsFrom240,
    'and it is smaller than the departure from equal, which is the point of reporting it');
  ok(/upper bound on precision/.test(R.reproducibility.caveat), 'with its caveat attached to the number');
}

// -------------------------------------------------- 13. the page cannot drift
console.log('\n13. the page against the computation');
{
  const c = pageCheck();
  ok(c.ok, `the data block embedded in the page equals analyse.mjs output (${c.pageBytes} vs ${c.wantBytes} bytes)`);
  const html = fs.readFileSync(PAGE, 'utf8');
  ok(!html.includes('__FINDINGS_JSON__'), 'the placeholder was replaced');
  ok(html.includes('/_kit/barpitch.js'), 'the page loads the same estimator this verifier loads');
  const kit = fs.readFileSync(path.join(HERE, '..', '..', 'public', '_kit', 'barpitch.js'), 'utf8');
  ok(kit.includes('estimateFundamental') && kit.includes('decodeWav'), 'the kit exports what both sides need');
  // A page that quotes a source must quote it exactly as the analysis holds it.
  // The page wraps its blockquotes, so collapse whitespace before looking for a phrase.
  const flat = html.replace(/\s+/g, ' ');
  ok(flat.includes('did not measure all individual frequencies, but rather measured only a single octave span'),
    'the Vitale and Sethares quotation is present, verbatim');
  ok(flat.includes('In a cognitive sense, the Sundanese salendro tone system is equidistant'),
    'the van Zanten quotation is present, verbatim');
  ok(flat.includes(ELLIS.properly.replace(/\s+/g, ' ')), 'the Ellis p. 526 quotation on the page is the one the analysis holds');
}

// ------------------------------------------------------------- 14. the mutations
// A verifier that passes on a corrupted input is not a verifier. Break things.
console.log('\n14. negative controls: the gate must fail on a broken input');
{
  const mutate = (fn) => { try { fn(); return 'no error'; } catch (e) { return 'threw'; } };
  ok(mutate(() => parseScl('! z\n!\ndesc\n 2\n!\n banana\n 2/1\n', 'z')) === 'threw',
    'an unparseable degree is rejected');
  // If a clip were swapped for another key, the re-measurement in step 4 would move by
  // far more than its tolerance. Prove the tolerance can actually detect that.
  const a = readWav(path.join(AUDIO, 'SBSL1.wav'));
  const b = readWav(path.join(AUDIO, 'SBSL2.wav'));
  const fa = AW.estimateFundamental(a.samples, a.sampleRate, { fmin: 100, fmax: 6000 }).hz;
  const fb = AW.estimateFundamental(b.samples, b.sampleRate, { fmin: 100, fmax: 6000 }).hz;
  ok(Math.abs(1200 * Math.log2(fb / fa)) > 200,
    'two adjacent keys differ by far more than the 0.01-cent tolerance, so a swapped clip could not pass');
  // And the page-drift check must actually notice a changed byte.
  const want = JSON.stringify(analyse());
  ok(want !== want.replace('240', '241'), 'the page-drift comparison is byte exact');
}

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