// listen.mjs: read the film's soundtrack and nothing else.
//
//   node listen.mjs film.mp4          (needs spine.mjs beside it, and ffmpeg on PATH for an mp4)
//   node listen.mjs audio.wav --json
//
// It knows the film's clock and its one mapping, both in spine.mjs: a cell with n sides is the
// n-th harmonic of F0 in the LEFT ear, as loud as its share; the RIGHT ear is one sine at
// (average sides) x F0. It does not know any network, site or count. From the sound alone it reads:
//
//   1. the right ear's pitch in every steady window, divided by F0: the average number of sides;
//   2. the left ear's harmonics, fitted by least squares: the shares, and from them a second,
//      independent route to the average (the chord's loudness-weighted centre) and the spread;
//   3. in section VI, each short pip: one patch of cells, or one set of independent draws, and
//      asks how far below the run's own centre the Causeway's average lies, in that run's spreads.
//
// The pitch route is exact through compression (a frequency is a count of cycles); the loudness
// route is good to a few per cent. The verdicts use the pitch; the loudness route is the cross-check.
import { readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as SP from './spine.mjs';

export const TOL_EXACT = 0.0005;   // |average - whole number| below this reads as exact
export const BEYOND = 3;           // a gap of more than 3 of the run's own spreads is beyond its chance

export function readAudio(file) {
  let L, R;
  if (file.endsWith('.wav')) {
    const b = readFileSync(file), n = (b.length - 44) / 4;
    L = new Float64Array(n); R = new Float64Array(n);
    for (let i = 0; i < n; i++) { L[i] = b.readInt16LE(44 + 4 * i) / 32767; R[i] = b.readInt16LE(46 + 4 * i) / 32767; }
  } else {
    const raw = execFileSync('ffmpeg', ['-v', 'error', '-i', file, '-vn', '-f', 'f32le', '-ac', '2', '-ar', String(SP.SR), '-'], { maxBuffer: 1 << 30 });
    const f = new Float32Array(raw.buffer, raw.byteOffset, raw.length / 4), n = f.length / 2;
    L = new Float64Array(n); R = new Float64Array(n);
    for (let i = 0; i < n; i++) { L[i] = f[2 * i]; R[i] = f[2 * i + 1]; }
  }
  return { L, R };
}

// |DTFT| of a Hann-windowed stretch at frequency f
function mag(x, a, n, f) {
  let re = 0, im = 0;
  const w = (2 * Math.PI * f) / SP.SR;
  for (let i = 0; i < n; i++) { const h = 0.5 - 0.5 * Math.cos((2 * Math.PI * (i + 0.5)) / n), v = x[a + i] * h; re += v * Math.cos(w * i); im -= v * Math.sin(w * i); }
  return Math.hypot(re, im);
}
// the frequency of the one tone in x over [t0, t1]: coarse grid on a short stretch, then golden section on all of it
export function tone(x, t0, t1, fmin = 140, fmax = 800) {
  const a = Math.round(t0 * SP.SR), n = Math.round((t1 - t0) * SP.SR), m = Math.min(n, Math.round(0.08 * SP.SR));
  let best = fmin, bm = -1;
  for (let f = fmin; f <= fmax; f += 2) { const v = mag(x, a, m, f); if (v > bm) { bm = v; best = f; } }
  let lo = best - 3, hi = best + 3;
  for (let step = 0; step < 3; step++) {            // narrow on the short stretch, then on the whole window
    const len = step === 0 ? m : n, g = 0.6180339887;
    let c = hi - g * (hi - lo), d = lo + g * (hi - lo), fc = mag(x, a, len, c), fd = mag(x, a, len, d);
    for (let it = 0; it < 60; it++) {
      if (fc > fd) { hi = d; d = c; fd = fc; c = hi - g * (hi - lo); fc = mag(x, a, len, c); } else { lo = c; c = d; fc = fd; d = lo + g * (hi - lo); fd = mag(x, a, len, d); }
    }
    const mid = (lo + hi) / 2, span = step === 0 ? 0.5 : 0.05; lo = mid - span; hi = mid + span;
  }
  return (lo + hi) / 2;
}

// least-squares fit of every harmonic of F0 to x over [t0, t1]; returns the amplitude of each
function solve(A, b) {
  const n = b.length;
  for (let i = 0; i < n; i++) {
    let p = i; for (let r = i + 1; r < n; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
    [A[i], A[p]] = [A[p], A[i]]; [b[i], b[p]] = [b[p], b[i]];
    for (let r = i + 1; r < n; r++) { const f = A[r][i] / A[i][i]; for (let c = i; c < n; c++) A[r][c] -= f * A[i][c]; b[r] -= f * b[i]; }
  }
  const x = new Array(n).fill(0);
  for (let i = n - 1; i >= 0; i--) { let s = b[i]; for (let c = i + 1; c < n; c++) s -= A[i][c] * x[c]; x[i] = s / A[i][i]; }
  return x;
}
export function harmonics(x, t0, t1) {
  const a = Math.round(t0 * SP.SR), n = Math.round((t1 - t0) * SP.SR), H = SP.HARMONICS, k = 2 * H.length;
  const AtA = Array.from({ length: k }, () => new Array(k).fill(0)), Atb = new Array(k).fill(0), row = new Array(k);
  for (let i = 0; i < n; i++) {
    const t = (a + i) / SP.SR;
    for (let j = 0; j < H.length; j++) { const w = 2 * Math.PI * H[j] * SP.F0 * t; row[2 * j] = Math.cos(w); row[2 * j + 1] = Math.sin(w); }
    for (let p = 0; p < k; p++) { Atb[p] += row[p] * x[a + i]; for (let q = p; q < k; q++) AtA[p][q] += row[p] * row[q]; }
  }
  for (let p = 0; p < k; p++) for (let q = 0; q < p; q++) AtA[p][q] = AtA[q][p];
  const c = solve(AtA, Atb);
  return Object.fromEntries(H.map((h, j) => [h, Math.hypot(c[2 * j], c[2 * j + 1])]));
}
export function chordStats(amp) {
  const tot = Object.values(amp).reduce((s, v) => s + v, 0);
  const share = Object.fromEntries(Object.entries(amp).map(([h, v]) => [h, v / tot]));
  let mean = 0, m2 = 0;
  for (const [h, p] of Object.entries(share)) mean += +h * p;
  for (const [h, p] of Object.entries(share)) m2 += p * (+h - mean) ** 2;
  return { share, mean, sigma: Math.sqrt(m2), hex: share[6] };
}

export function read(file) {
  const { L, R } = readAudio(file);
  const win = ([a, b], name) => {
    const f = tone(R, a, b), ch = chordStats(harmonics(L, a, b));
    return { name, from: a, to: b, hz: f, mean: f / SP.F0, chordMean: ch.mean, sigma: ch.sigma, hex: ch.hex };
  };
  // the mapping, checked on the sound: the left ear's loudest partial must sit on a whole harmonic of F0
  const [a0, b0] = SP.W.oreilly, fl = tone(L, a0, b0), hNum = Math.round(fl / SP.F0);
  const out = { file: path.basename(file), f0: { loudestLeft: fl, harmonic: hNum, impliedF0: fl / hNum } };
  out.steady = [
    win(SP.W.oreilly, "O'Reilly's area"), win(SP.W.hetenyi, 'Hetényi, 32 sites'), win(SP.W.square, 'the uncracked square'),
    win(SP.W.pulled, 'every T pulled'),
    ...SP.W.wrapped.map((w, i) => win(w, `random points, wrapped ${i + 1}`)),
    ...SP.W.bounded.map((w, i) => win(w, `the same points, not wrapped ${i + 1}`)),
    ...SP.W.discs.map((w, i) => win(w, `discs, ${Math.round(SP.PHIS[i] * 100)}% of the floor`)),
    win(SP.W.causeway, "the Causeway (O'Reilly)"),
    ...SP.W.recounts.map((w, i) => win(w, `recount ${i + 1}`)),
  ];
  out.cracks = SP.W_CRACK.map(([a, b]) => tone(R, a, b) / SP.F0);
  const pipRun = (t0) => Array.from({ length: SP.NPIPS }, (_, i) => { const [a, b] = SP.pipWindow(t0, i); const ch = chordStats(harmonics(L, a, b)); return { mean: tone(R, a, b) / SP.F0, chordMean: ch.mean }; });
  const causeway = tone(R, ...SP.W.causeway2) / SP.F0;
  const runStats = (pips) => {
    const xs = pips.map((p) => p.mean), n = xs.length, m = xs.reduce((s, x) => s + x, 0) / n;
    const sd = Math.sqrt(xs.reduce((s, x) => s + (x - m) ** 2, 0) / (n - 1)), gap = (m - causeway) / sd;
    return { n, centre: m, sd, min: Math.min(...xs), max: Math.max(...xs), atOrBelow: xs.filter((x) => x <= causeway).length, gapInSpreads: gap, verdict: gap > BEYOND ? 'BEYOND CHANCE' : 'WITHIN CHANCE', chordGap: Math.max(...pips.map((p) => Math.abs(p.chordMean - p.mean))) };
  };
  out.causeway = causeway;
  const first = pipRun(SP.NAIVE0), second = pipRun(SP.REAL0);
  out.firstRun = runStats(first);
  out.secondRun = runStats(second);
  out.pips = { first: first.map((p) => p.mean), second: second.map((p) => p.mean) };
  // the verdicts the film's argument rests on, from the pitch route
  const byName = (s) => out.steady.find((w) => w.name.startsWith(s));
  out.verdicts = {
    cracksExactlyFour: out.cracks.every((m) => Math.abs(m - 4) < TOL_EXACT),
    squareExactlyFour: Math.abs(byName('the uncracked').mean - 4) < TOL_EXACT,
    wrappedExactlySix: out.steady.filter((w) => /^random points, wrapped|^discs/.test(w.name)).every((w) => Math.abs(w.mean - 6) < TOL_EXACT),
    unwrappedBelowSix: out.steady.filter((w) => /not wrapped/.test(w.name)).every((w) => 6 - w.mean > 0.05),
    pulledShortOfSix: 6 - byName('every T').mean > 0.1,
    chordAgreesWithVoice: Math.max(...out.steady.map((w) => Math.abs(w.chordMean - w.mean))),
    firstRun: out.firstRun.verdict, secondRun: out.secondRun.verdict,
  };
  return out;
}

if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  const file = process.argv[2];
  if (!file) { console.error('usage: node listen.mjs <film.mp4 | audio.wav> [--json]'); process.exit(2); }
  const r = read(file);
  if (process.argv.includes('--json')) { console.log(JSON.stringify(r, null, 1)); process.exit(0); }
  console.log(`${r.file}: left ear's loudest partial ${r.f0.loudestLeft.toFixed(4)} Hz = harmonic ${r.f0.harmonic} of ${r.f0.impliedF0.toFixed(5)} Hz (declared ${SP.F0})\n`);
  console.log('window'.padEnd(40) + 'right ear (Hz)'.padStart(15) + 'average, by pitch'.padStart(19) + 'by chord'.padStart(10) + 'spread'.padStart(8) + 'hexagons'.padStart(10));
  for (const w of r.steady) console.log(w.name.padEnd(40) + w.hz.toFixed(4).padStart(15) + w.mean.toFixed(5).padStart(19) + w.chordMean.toFixed(3).padStart(10) + w.sigma.toFixed(2).padStart(8) + (100 * w.hex).toFixed(1).padStart(9) + '%');
  console.log(`\nII, one-second windows while 300 cracks land: average by pitch ${Math.min(...r.cracks).toFixed(5)} to ${Math.max(...r.cracks).toFixed(5)}`);
  console.log(`VI, the Causeway's average by pitch: ${r.causeway.toFixed(4)}`);
  for (const [k, s] of [['first run of pips', r.firstRun], ['second run of pips', r.secondRun]]) {
    console.log(`   ${k}: ${s.n} pips, centre ${s.centre.toFixed(4)}, spread ${s.spread ?? s.sd.toFixed(4)}, ${s.atOrBelow} at or below the Causeway; it lies ${s.gapInSpreads.toFixed(1)} spreads below the centre: ${s.verdict}`);
  }
  console.log('\nverdicts:', JSON.stringify(r.verdicts));
}
