#!/usr/bin/env node
// verify.mjs — the mathematics behind "The Wheel That Spins Backward".
//
// The wagon-wheel effect under a camera or a strobe is *pure temporal sampling*,
// and it is exact within the stated instantaneous-sampling model. This file checks
// selected numerical cases and, when the page is present, its complete fold() and
// two numerical sentences. It does not check every displayed value or prose claim.
//
//   node research/aliasing-wagon-wheel/verify.mjs          # run all checks
//
// THE MODEL.  A wheel whose pattern has S-fold rotational symmetry (S identical
// spokes) looks unchanged after turning by 1/S of a revolution. So if it turns at
// f_rot revolutions/second (signed: + forward, - backward), its *appearance* repeats
// at the spoke-passing frequency
//        f_app = S * f_rot           (cycles/second of the visible pattern).
// A camera/strobe takes fs snapshots/second. Sampling a periodic signal of frequency
// f_app at rate fs makes it indistinguishable from its alias — f_app folded into the
// principal band (-fs/2, fs/2]:
//        fold(f, fs) = f - fs*round(f/fs).
// The apparent spoke frequency is fold(f_app, fs); the apparent wheel speed is that
// over S. Sign of the fold = apparent direction (+ forward, - BACKWARD, 0 frozen).
//
// FREE CHOICES, named: S is the rotational symmetry order of the *indistinguishable*
// pattern (a single painted spoke makes S=1; n identical spokes make S=n). We sample
// instantaneously (zero shutter/strobe width); a finite exposure blurs but does not
// move the stop/reverse speeds. The continuous-light ("under steady daylight, not a
// camera") wagon-wheel illusion is a SEPARATE and still-contested phenomenon about
// whether the brain samples discretely — it is NOT what this file proves and the page
// flags it as open. Everything here is the camera/strobe case, which is unambiguous.

let pass = 0, fail = 0;
const approx = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;
function ok(name, cond) { if (cond) { pass++; } else { fail++; console.error('  FAIL:', name); } }

// ── the one formula everything rests on ──────────────────────────────────────
// fold f into the half-open Nyquist band (-fs/2, fs/2]. Both band edges map to +fs/2.
function fold(f, fs) {
  let r = f - fs * Math.round(f / fs);
  if (r <= -fs / 2) r += fs;
  if (r > fs / 2) r -= fs;
  return r;
}
// Apparent wheel speed (rev/s) seen through a camera at fs fps.
const apparent = (f_rot, S, fs) => fold(S * f_rot, fs) / S;
function direction(f_rot, S, fs, eps = 1e-9) {
  const a = apparent(f_rot, S, fs);
  return Math.abs(a) <= eps ? 'frozen' : (a > 0 ? 'forward' : 'BACKWARD');
}

console.log('THE WHEEL THAT SPINS BACKWARD — verifier\n');

// ── Claim 1. fold always lands inside the Nyquist band (-fs/2, fs/2]. ─────────
{
  const fs = 24;
  let worst = 0;
  for (let f = -500; f <= 500; f += 0.013) {
    const r = fold(f, fs);
    worst = Math.max(worst, Math.abs(r));
    if (!(r > -fs / 2 - 1e-9 && r <= fs / 2 + 1e-9)) { fail++; console.error('  FAIL: band at f=', f); break; }
  }
  ok('fold lands in (-fs/2, fs/2] across a dense sweep', worst <= fs / 2 + 1e-9);
  // fold is an identity inside the band, and idempotent
  ok('fold is identity for |f| < fs/2', approx(fold(7, 24), 7) && approx(fold(-11, 24), -11));
  ok('fold is idempotent', approx(fold(fold(1000, 24), 24), fold(1000, 24)));
}

// ── Claim 2. STOP (frozen wheel) ⟺ f_rot is an integer multiple of fs/S. ──────
// This is the strobe "freeze": every snapshot catches the pattern in the same pose.
{
  const fs = 24, S = 12;            // a 12-spoke wheel filmed at 24 fps
  const stopSpeed = fs / S;         // = 2.0 rev/s : first freeze
  ok('first freeze at f_rot = fs/S = 2.0 rev/s', approx(stopSpeed, 2.0));
  for (let k = -3; k <= 3; k++) {
    ok(`k=${k}: f_rot = k*fs/S freezes`, approx(apparent(k * stopSpeed, S, fs), 0));
  }
  // and ONLY there: halfway between freezes the apparent speed is the band edge (max ambiguity)
  ok('halfway between freezes → apparent = ±fs/(2S) (max)',
     approx(Math.abs(apparent(stopSpeed * 0.5, S, fs)), fs / (2 * S)));
}

// ── Claim 3. BACKWARD ⟺ true speed sits just below a freeze speed. ───────────
// The headline illusion: the wheel turns forward, the screen shows it reversing.
{
  const fs = 24, S = 12, stop = fs / S;     // freeze at 2.0 rev/s
  const d = 0.1;
  ok('just under a freeze (1.9 rev/s) → BACKWARD', direction(stop - d, S, fs) === 'BACKWARD');
  ok('just over a freeze (2.1 rev/s) → forward',   direction(stop + d, S, fs) === 'forward');
  // exact apparent value just under: fold(12*1.9, 24) = fold(22.8,24) = -1.2 → /12 = -0.1 rev/s
  ok('1.9 rev/s shows exactly -0.1 rev/s (backward)', approx(apparent(1.9, S, fs), -0.1));
  // the reversal is real for EVERY freeze, not just the first
  for (let k = 1; k <= 4; k++) ok(`backward just below freeze #${k}`, direction(k * stop - d, S, fs) === 'BACKWARD');
}

// ── Claim 4. Nyquist: the true motion is captured faithfully ⟺ fs > 2*S*|f_rot|. ─
// Below twice the spoke-passing frequency, the recording cannot tell the truth.
{
  const S = 12, f_rot = 1.0;               // true: 1 rev/s forward, spoke freq 12 Hz
  const nyq = 2 * S * Math.abs(f_rot);     // need fs > 24 fps
  ok('faithful capture when fs > 2*S*f_rot', approx(apparent(f_rot, S, 25), f_rot) && direction(f_rot, S, 25) === 'forward');
  ok('aliased (wrong) when fs < 2*S*f_rot', !approx(apparent(f_rot, S, 20), f_rot));
  ok('Nyquist threshold here is 24 fps', approx(nyq, 24));
  // exactly AT Nyquist (fs = 2*S*f_rot) the spoke freq lands on the band edge fs/2 → ambiguous
  ok('exactly at Nyquist the apparent speed hits the band edge', approx(Math.abs(apparent(f_rot, S, nyq)), f_rot));
}

// Claim 5. The audio twin: selected nonzero aliases of sampled tones.
// Same fold, different sense. Sample a 1000 Hz sine at 1500 Hz → you hear 500 Hz.
{
  const heard = (f, fs) => Math.abs(fold(f, fs));
  ok('1000 Hz sampled at 1500 Hz is heard as 500 Hz', approx(heard(1000, 1500), 500));
  ok('a tone below Nyquist is heard true (700 Hz @ 1500)', approx(heard(700, 1500), 700));
  ok('21 kHz sampled at 44.1 kHz folds to 21 kHz (still below Nyquist)', approx(heard(21000, 44100), 21000));
  ok('25 kHz sampled at 44.1 kHz folds down to 19.1 kHz', approx(heard(25000, 44100), 19100));
}

// ── Claim 6. The page's preset numbers, recomputed here (show-the-check). ─────
// These exact figures appear in public/strata/the-wheel-that-spins-backward/index.html.
// This block checks four recorded presets against the model, not the page controls.
const PRESETS = [
  // [label, f_rot, S, fs, expected apparent rev/s, expected direction]
  ['Helicopter freeze',  2.0, 12, 24, 0.0,  'frozen'],
  ['The reversal',       1.9, 12, 24, -0.1, 'BACKWARD'],
  ['Faithful slow-mo',   1.0, 12, 25, 1.0,  'forward'],
  ['Crawl forward',      2.1, 12, 24, 0.1,  'forward'],
];
for (const [label, f_rot, S, fs, exp, dir] of PRESETS) {
  ok(`preset "${label}": apparent = ${exp} rev/s`, approx(apparent(f_rot, S, fs), exp));
  ok(`preset "${label}": direction = ${dir}`, direction(f_rot, S, fs) === dir);
}

// Compare the complete page fold() and the two numbers in the check bullets.
import fs2 from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
const pagePath = path.resolve(here, '../../public/strata/the-wheel-that-spins-backward/index.html');
if (fs2.existsSync(pagePath)) {
  const html = fs2.readFileSync(pagePath, 'utf8');
  // Ignore whitespace and the local var/let declaration difference, not return values.
  const foldSource = src => src.match(/function fold\(f, fs\)\s*\{[\s\S]*?\n\s*\}/)?.[0]
    .replace(/\b(?:var|let)\b/g, 'let').replace(/\s/g, '');
  ok('page ships the complete verifier fold()', foldSource(html) === foldSource(fold.toString()));
  const check = html.match(/<section class="check">([\s\S]*?)<\/section>/)?.[1] || '';
  const items = [...check.matchAll(/<li>([\s\S]*?)<\/li>/g)].map(m => m[1]
    .replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').replace(/−/g, '-').replace(/\s+/g, ' '));
  ok('first-freeze bullet states 2 rev/s', items.some(s => /first freeze at 2(?:\.0)? rev\/s/.test(s)));
  ok('reversal bullet states 1.9 rev/s gives -0.1 rev/s', items.some(s => /1\.9 rev\/s on film → -0\.1 rev\/s/.test(s)));
} else {
  console.log('  (page not built yet — skipping HTML cross-check)');
}

console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} — ${pass}/${pass + fail} checks`);
process.exit(fail === 0 ? 0 : 1);
