#!/usr/bin/env node
// verify-audio.mjs — prove the film's soundtrack keeps the spectral promise.
//
// The film puts the words "no energy at or below 200 Hz" on screen during the
// CUT phase. For that to be HONEST about the artefact we ship, the rendered
// audio.wav must actually carry no energy there. This script re-measures the
// finished WAV with the Goertzel algorithm (a single-bin DFT) and an
// autocorrelation, on the exact section the page-cut plays, and checks:
//   (a) energy at 200 Hz and below is at the numerical floor (≤ −55 dB
//       relative to a present partial) — the missing fundamental is missing;
//   (b) the waveform nonetheless repeats at ≈200 Hz (the residue period);
//   (c) the de Boer sweep's envelope (beat) rate stays 200 Hz while its
//       residue period climbs — sanity on the (3) demonstration.
// Run AFTER make-audio.mjs:  node verify-audio.mjs

import { readFileSync } from 'node:fs';

const SR = 44100;
const buf = readFileSync(new URL('./audio.wav', import.meta.url).pathname);
const nSamp = (buf.length - 44) / 4;
function L(i) { return buf.readInt16LE(44 + i * 4) / 32767; }

// Goertzel power at frequency f over [i0, i0+n)
function power(f, i0, n) {
  const c = Math.cos(2 * Math.PI * f / SR);
  let q1 = 0, q2 = 0;
  for (let k = 0; k < n; k++) { const q0 = 2 * c * q1 - q2 + L(i0 + k); q2 = q1; q1 = q0; }
  return (q1 * q1 + q2 * q2 - 2 * c * q1 * q2) / n;
}
function db(x) { return 10 * Math.log10(Math.max(x, 1e-30)); }

// autocorrelation fundamental within [loHz, hiHz]
function periodHz(i0, n, loHz = 120, hiHz = 400) {
  let energy = 0; for (let k = 0; k < n; k++) { const x = L(i0 + k); energy += x * x; }
  let bestLag = -1, bestR = -1;
  for (let lag = Math.round(SR / hiHz); lag <= Math.round(SR / loHz); lag++) {
    let r = 0; for (let k = 0; k + lag < n; k++) r += L(i0 + k) * L(i0 + k + lag);
    r /= energy; if (r > bestR) { bestR = r; bestLag = lag; }
  }
  return { hz: SR / bestLag, r: bestR };
}

const checks = [];
function check(name, pass, detail) { checks.push({ name, pass, detail }); console.log(`  ${pass ? 'PASS' : 'FAIL'}  ${name}  [${detail}]`); }

console.log('The Pitch That Isn\'t There — audio spectral-honesty checks');
console.log('=========================================================\n');

// (a)+(b) the CUT section, 30..46 s — fundamental removed
{
  const i0 = 30 * SR, n = 16 * SR;
  const p400 = power(400, i0, n);   // a present partial (reference)
  const p200 = power(200, i0, n);   // the missing fundamental
  const p100 = power(100, i0, n);   // an octave below
  const rel200 = db(p200 / p400), rel100 = db(p100 / p400);
  const per = periodHz(i0, n);
  console.log('CUT section 30–46 s (partials 400/600/800/1000/1200; f0=200 removed):');
  console.log(`    200 Hz energy : ${rel200.toFixed(1)} dB rel. to the 400 Hz partial`);
  console.log(`    100 Hz energy : ${rel100.toFixed(1)} dB rel.`);
  console.log(`    waveform period : ${per.hz.toFixed(2)} Hz  (autocorr r=${per.r.toFixed(3)})\n`);
  check('(a) 200 Hz energy at the floor (≤ −55 dB)', rel200 <= -55, `${rel200.toFixed(1)} dB`);
  check('(a) sub-200 (100 Hz) at the floor (≤ −55 dB)', rel100 <= -55, `${rel100.toFixed(1)} dB`);
  check('(b) waveform still repeats at f0 ≈ 200 Hz', Math.abs(per.hz - 200) < 2, `${per.hz.toFixed(2)} Hz`);
}

// (c) de Boer sweep — Δ=0 at ~101 s vs Δ=80 at ~122 s
{
  // residue period should climb 200 → 208 Hz; envelope (200 Hz spacing) constant.
  const segs = [[101.5, 0, 200], [122.0, 80, 208]];
  let ok = true, detail = [];
  for (const [tc, d, expect] of segs) {
    const i0 = Math.round(tc * SR), n = 3 * SR;
    // the residue lives near (2000+Δ)/10; search a tight band around it
    const per = periodHz(i0, n, expect - 12, expect + 12);
    detail.push(`Δ=${d}:${per.hz.toFixed(1)}Hz`);
    if (Math.abs(per.hz - expect) > 4) ok = false;
  }
  console.log('de Boer residue period (autocorr in a band around the prediction):');
  console.log(`    ${detail.join('   ')}\n`);
  check('(c) residue period climbs ~200 → ~208 Hz across the Δ sweep', ok, detail.join(' '));
}

let pass = 0; for (const c of checks) if (c.pass) pass++;
console.log(`\n${pass}/${checks.length} audio checks passed.`);
process.exit(pass === checks.length ? 0 : 1);
