// listen.mjs: read the companion film's soundtrack and report what the two ears carry.
//
//   node listen.mjs film.mp4            (needs spine.mjs beside it, ffmpeg on PATH, Node 18+)
//   node listen.mjs film.mp4 --json
//
// It knows only spine.mjs: the clock and the mapping. It does not know the Kolakoski sequence, the
// coins, any count or any frequency the film plays; it hears them.
//
// Tape sections. In every slot it measures, in each ear, how much of the sound is at 220 Hz and how
// much at 440 Hz (a Hann-windowed single-frequency transform over the middle of the slot) and writes
// down a 1 or a 2. Then, from the digits alone:
//   - where the two ears first differ (the length of their agreement);
//   - whether the right ear is the left ear read as run lengths (1 repeated a times, 2 repeated b
//     times, 1 repeated c times, ...), over every slot played;
//   - in section I, whether one ear is its own run-length reading. Only one sequence of 1s and 2s that
//     starts with 1 has that property (the Kolakoski sequence), so this identifies it without knowing it;
//   - across the readings, whether the next reading's left ear is this reading's right ear, and whether
//     each agreement is the sum of the previous agreed digits plus one.
// Section III. In each step it measures the frequency of the 330 Hz voice in each ear by complex
// demodulation (find the strongest frequency near 330 Hz, multiply by a phasor at the frequency
// found, average in 100 ms blocks, fit a line to the unwrapped phase). The right ear minus the left is the beat. From the mapping, right = 220 x (average term),
// so (right - 330) / 110 = (2s - 1s) / n, and with n from the step's label it gives the count of 1s,
// with the error the measurement allows (never less than 2e-5 Hz, see U_FLOOR).
import { spawnSync } from 'node:child_process';
import * as S from './spine.mjs';

const file = process.argv[2];
const asJson = process.argv.includes('--json');
if (!file) { console.error('usage: node listen.mjs <film.mp4 | audio.wav> [--json]'); process.exit(2); }

const ff = spawnSync('ffmpeg', ['-v', 'error', '-i', file, '-f', 'f32le', '-acodec', 'pcm_f32le', '-ac', '2', '-ar', String(S.SR), '-'], { maxBuffer: 1 << 30 });
if (ff.status !== 0) { console.error(String(ff.stderr)); process.exit(2); }
const raw = new Float32Array(ff.stdout.buffer, ff.stdout.byteOffset, ff.stdout.byteLength / 4);
const N = raw.length / 2;
const ear = [new Float32Array(N), new Float32Array(N)];
for (let i = 0; i < N; i++) { ear[0][i] = raw[2 * i]; ear[1][i] = raw[2 * i + 1]; }

// power at frequency f over samples [a, b), Hann windowed
function power(x, a, b, f) {
  let re = 0, im = 0; const n = b - a, w = 2 * Math.PI * f / S.SR;
  for (let i = a; i < b; i++) { const h = 0.5 - 0.5 * Math.cos(2 * Math.PI * (i - a + 0.5) / n); re += h * x[i] * Math.cos(w * i); im -= h * x[i] * Math.sin(w * i); }
  return re * re + im * im;
}
const runRead = (s, n) => { const out = []; let sym = 1; for (const len of s) { for (let r = 0; r < len && out.length < n; r++) out.push(sym); sym = 3 - sym; if (out.length >= n) break; } return out; };
const firstDiff = (a, b) => { let q = 0; while (q < a.length && q < b.length && a[q] === b[q]) q++; return q; };

const tape = [];
for (const seg of S.SEGMENTS) {
  const d = [[], []]; let weakest = Infinity;
  for (let k = 0; k < seg.n; k++) {
    const [t0, t1] = S.slotTime(seg, k), T = t1 - t0;
    const a = Math.round((t0 + 0.15 * T) * S.SR), b = Math.round((t0 + 0.75 * T) * S.SR);
    for (const c of [0, 1]) {
      const p1 = power(ear[c], a, b, S.TONE(1)), p2 = power(ear[c], a, b, S.TONE(2));
      d[c].push(p1 > p2 ? 1 : 2);
      weakest = Math.min(weakest, Math.max(p1, p2) / (Math.min(p1, p2) + 1e-30));
    }
  }
  const agree = firstDiff(d[0], d[1]);
  const read = runRead(d[0], seg.n);
  const rightIsLeftRead = read.length >= seg.n && firstDiff(read, d[1]) >= seg.n;
  const leftIsOwnReading = firstDiff(runRead(d[0], seg.n), d[0]) >= seg.n && d[0][0] === 1;
  tape.push({ name: seg.name, j: seg.j, n: seg.n, L: d[0].join(''), R: d[1].join(''), agree, rightIsLeftRead, leftIsOwnReading, clarityDb: 10 * Math.log10(weakest) });
}
// the chain across readings, and the agreement law, from the digits alone
const reads = tape.filter((t) => t.j !== null);
for (let q = 0; q + 1 < reads.length; q++) {
  const a = reads[q], b = reads[q + 1];
  const m = Math.min(a.n, b.n);
  a.nextLeftIsThisRight = firstDiff(b.L.slice(0, m), a.R.slice(0, m)) >= m;
  if (a.agree < a.n && b.agree < b.n) {
    const sum = [...a.L.slice(0, a.agree)].reduce((s, c) => s + Number(c), 0);
    a.lawNext = sum + 1; a.lawHolds = b.agree === sum + 1;
  }
}

// section III
const TAU = 2 * Math.PI;
function offset(x, t0, t1) {
  // 1. coarse: the strongest frequency between 300 and 360 Hz (Hann-windowed transform on a 0.5 Hz grid
  //    over the first half second, then golden-section refinement on the full window)
  const a = Math.round(t0 * S.SR), b = Math.round(t1 * S.SR);
  let best = 330, bp = -1;
  for (let f = 300; f <= 360; f += 0.5) { const p = power(x, a, Math.min(b, a + S.SR / 2), f); if (p > bp) { bp = p; best = f; } }
  let lo = best - 1, hi = best + 1; const g = (Math.sqrt(5) - 1) / 2;
  for (let it = 0; it < 30; it++) { const m1 = hi - g * (hi - lo), m2 = lo + g * (hi - lo); if (power(x, a, b, m1) > power(x, a, b, m2)) hi = m2; else lo = m1; }
  const fc = (lo + hi) / 2;
  // 2. fine: demodulate at fc in 100 ms blocks, unwrap the phase, fit a line: frequency = fc + slope / 2 pi
  const B = Math.round(0.1 * S.SR), nb = Math.floor((b - a) / B);
  const ph = [], tt = []; let prev = null, unwrap = 0;
  for (let k = 0; k < nb; k++) {
    let re = 0, im = 0;
    for (let i = a + k * B; i < a + (k + 1) * B; i++) { const w = TAU * fc * i / S.SR; re += x[i] * Math.cos(w); im -= x[i] * Math.sin(w); }
    let p = Math.atan2(im, re);
    if (prev !== null) { while (p + unwrap - prev > Math.PI) unwrap -= TAU; while (p + unwrap - prev < -Math.PI) unwrap += TAU; }
    p += unwrap; prev = p; ph.push(p); tt.push((a + (k + 0.5) * B) / S.SR);
  }
  const n = ph.length, mt = tt.reduce((s, v) => s + v, 0) / n, mp = ph.reduce((s, v) => s + v, 0) / n;
  let sxy = 0, sxx = 0; for (let k = 0; k < n; k++) { sxy += (tt[k] - mt) * (ph[k] - mp); sxx += (tt[k] - mt) ** 2; }
  const slope = sxy / sxx; let rss = 0; for (let k = 0; k < n; k++) rss += (ph[k] - mp - slope * (tt[k] - mt)) ** 2;
  const se = Math.sqrt(rss / Math.max(1, n - 2) / sxx);
  return { df: fc - 330 + slope / TAU, se: se / TAU };
}
const U_FLOOR = 2e-5;   // Hz
const steps = [];
for (const st of S.STEPS) {
  const t0 = st.t0 + S.READ_MARGIN + (st === S.STEPS[0] ? S.FADE_IN : 0);
  const t1 = st.t1 - S.READ_MARGIN - (st === S.STEPS.at(-1) ? S.FADE_OUT : 0);
  const L = offset(ear[0], t0, t1), R = offset(ear[1], t0, t1);
  // the fit's own error bar, but never less than U_FLOOR: on the noiseless WAV the fitted bar was
  // measured to understate the real error by up to about 1.4e-5 Hz (one step of ten), so it gets a floor
  const beat = R.df - L.df, se = Math.max(U_FLOOR, Math.hypot(R.se, L.se));
  const row = { name: st.name, left: 330 + L.df, right: 330 + R.df, beat, se };
  if (/^n\d+$/.test(st.name)) {
    const n = 10 ** Number(st.name.slice(1));
    const delta = beat * n / (S.F1 / 2), deltaSe = se * n / (S.F1 / 2);
    row.n = n; row.delta = delta; row.deltaSe = deltaSe;
    row.ones = deltaSe < 0.25 ? Math.round((n - Math.round(delta)) / 2) : null;   // a whole count, only when the file resolves one
  }
  steps.push(row);
}

const out = { file, tape, steps };
if (asJson) { console.log(JSON.stringify(out)); process.exit(0); }
const K = tape[0];
console.log(`section I (${K.n} terms): ears agree for ${K.agree} of ${K.n}; right ear is left read as run lengths: ${K.rightIsLeftRead ? 'yes' : 'NO'}; left ear is its own run-length reading: ${K.leftIsOwnReading ? 'YES (so it is the Kolakoski sequence)' : 'no'}`);
console.log(`   left ear begins ${K.L.slice(0, 24)}`);
for (const t of tape.slice(1)) console.log(`${(t.j === 0 ? 'coins' : 'read ' + t.j).padEnd(8)} ears agree for ${String(t.agree).padStart(3)} of ${t.n}${t.agree === t.n ? ' (no split)' : ''}; right = left read as runs: ${t.rightIsLeftRead ? 'yes' : 'NO'}` +
  (t.nextLeftIsThisRight !== undefined ? `; next left = this right: ${t.nextLeftIsThisRight ? 'yes' : 'NO'}` : '') + (t.lawNext !== undefined ? `; sum of agreed digits + 1 = ${t.lawNext} ${t.lawHolds ? '= next agreement' : '!= next agreement'}` : ''));
console.log(`weakest digit decision: ${Math.min(...tape.map((t) => t.clarityDb)).toFixed(1)} dB`);
for (const s of steps) console.log(`${s.name.padEnd(7)} left ${s.left.toFixed(5)} Hz  right ${s.right.toFixed(6)} Hz  beat ${s.beat.toExponential(3)} ± ${s.se.toExponential(1)} Hz` +
  (s.n ? `  →  2s − 1s at n = 10^${Math.log10(s.n)}: ${s.delta.toPrecision(6)} ± ${s.deltaSe.toPrecision(2)}${s.ones !== null ? `, 1s = ${s.ones.toLocaleString('en-GB')}` : ' (too fine for this file to resolve)'}` : ''));
