#!/usr/bin/env node
// verify.mjs — "The Pattern in Neither" (P3, the twelfth portal).
//
// The claim the portal supplies, which no single member states alone:
//   The pattern you PERCEIVE in each of three unrelated senses — the backward
//   wagon wheel (time), the moiré fringe (space), the roughness of two beating
//   tones (pitch) — is the DIFFERENCE FREQUENCY of two, |f1 - f2|, a frequency
//   physically present in NEITHER source. It is one line of trigonometry read
//   three ways. And a seam runs through it: for the beat and the moiré the two
//   frequencies are both signals out in the world (a recorder captures the
//   difference); for the wheel the second frequency is the observer's own
//   sampling clock fs, so the difference is an ALIAS — gone when the sampler is.
//
// This file re-derives the shared identity and each member's headline figure
// from first principles, and asserts each equals the value that member's own
// verifier already checks. Numbers are lifted from the members, not re-invented:
//   research/critical-band-consonance/verify.mjs   (beat rate |f1-f2|, ERB)
//   research/moire/verify-moire.mjs                (D = p/(2 sin θ/2), 57×, magic angle)
//   research/aliasing-wagon-wheel/verify.mjs       (fold, freeze fs/S, 1.9→-0.1, Nyquist)
//
//   node research/the-pattern-in-neither/verify.mjs
'use strict';

let PASS = 0, FAIL = 0;
const ok = (name, cond, detail = '') => {
  if (cond) { PASS++; console.log(`  ok   ${name}${detail ? '   ' + detail : ''}`); }
  else { FAIL++; console.log(`  FAIL ${name}${detail ? '   ' + detail : ''}`); }
};
const approx = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;
const TAU = Math.PI * 2;

// mulberry32 — deterministic PRNG (no Math.random; reproducible run to run).
function mulberry32(seed) {
  let s = seed >>> 0;
  return () => { s |= 0; s = (s + 0x6D2B79F5) | 0;
    let t = Math.imul(s ^ (s >>> 15), 1 | s);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}

console.log('THE PATTERN IN NEITHER — twelfth portal verifier\n');

// ═════════════════════════════════════════════════════════════════════════
// (0) THE SHARED IDENTITY.  cos α + cos β = 2 cos((α−β)/2) cos((α+β)/2).
//     The perceived envelope is the slow factor at (α−β)/2 → full difference rate.
// ═════════════════════════════════════════════════════════════════════════
console.log('(0) the product-to-sum identity underneath all three');
{
  const rnd = mulberry32(0x1234abcd);
  let worst = 0;
  for (let i = 0; i < 200000; i++) {
    const a = (rnd() * 2 - 1) * 1000, b = (rnd() * 2 - 1) * 1000;
    const lhs = Math.cos(a) + Math.cos(b);
    const rhs = 2 * Math.cos((a - b) / 2) * Math.cos((a + b) / 2);
    worst = Math.max(worst, Math.abs(lhs - rhs));
  }
  ok('cos α + cos β == 2 cos((α−β)/2) cos((α+β)/2), 200k random', worst < 1e-9,
     `max abs err ${worst.toExponential(2)}`);
}

// ═════════════════════════════════════════════════════════════════════════
// (1) PITCH — the acoustic beat.  Synthesize two tones, MEASURE the envelope's
//     swell rate back from the samples: it must equal |f1 − f2|, whatever the
//     carrier. (Independent of the identity above; a numeric confirmation.)
// ═════════════════════════════════════════════════════════════════════════
console.log('\n(1) pitch — the beat rate measured back from synthesized samples');
{
  // Count amplitude-envelope maxima per second of y(t)=cos(2πf1 t)+cos(2πf2 t).
  // Envelope = |2 cos(π Δf t)|; its maxima occur at t = k/Δf → Δf peaks/second.
  function measureBeatRate(f1, f2) {
    const fs = 96000, dur = 4.0;                     // 4 s at 96 kHz
    const n = Math.round(fs * dur);
    let prevEnv = -1, prevSlope = 0, peaks = 0;
    for (let i = 0; i < n; i++) {
      const t = i / fs;
      const env = Math.abs(2 * Math.cos(Math.PI * (f2 - f1) * t)); // analytic envelope
      const slope = env - prevEnv;
      if (i > 1 && prevSlope > 0 && slope <= 0) peaks++;           // local max of envelope
      prevEnv = env; prevSlope = slope;
    }
    return peaks / dur;
  }
  const cases = [[440, 444, 4], [440, 445.5, 5.5], [1000, 1017, 17], [261.63, 293.66, 32.03]];
  for (const [f1, f2, df] of cases) {
    const m = measureBeatRate(f1, f2);
    ok(`beat rate(${f1},${f2}) measured ≈ |f1−f2| = ${df.toFixed(2)} Hz`, Math.abs(m - df) <= 0.5,
       `measured ${m.toFixed(2)} Hz`);
  }
  // ERB (Glasberg–Moore 1990) — the same critical-bandwidth proxy the member uses;
  // roughness peaks near ¼ CB (Plomp–Levelt). Assert the page's 440-Hz numbers.
  const ERB = f => 24.7 * (4.37 * f / 1000 + 1);
  const erb440 = ERB(440);
  ok('ERB(440 Hz) ≈ 72.2 Hz (member’s critical-band proxy)', approx(erb440, 72.16, 0.1),
     `${erb440.toFixed(2)} Hz`);
  ok('roughness peak ≈ ¼ CB ≈ 17 Hz at 440 Hz (page readout)', approx(0.24 * erb440, 17.3, 0.3),
     `${(0.24 * erb440).toFixed(1)} Hz`);
}

// ═════════════════════════════════════════════════════════════════════════
// (2) SPACE — moiré, the spatial beat.  Mirror the member's three period laws
//     and assert the reductions + the two headline figures (57×, magic angle).
// ═════════════════════════════════════════════════════════════════════════
console.log('\n(2) space — the moiré fringe as a spatial beat (from research/moire)');
{
  const D_master = (p1, p2, th) => (p1 * p2) / Math.sqrt(p1*p1 + p2*p2 - 2*p1*p2*Math.cos(th));
  const D_masterStable = (p1, p2, th) => (p1 * p2) / Math.sqrt((p1-p2)*(p1-p2) + 2*p1*p2*(1-Math.cos(th)));
  const D_rotation = (p, th) => p / (2 * Math.sin(th / 2));
  const D_beat = (p1, p2) => (p1 * p2) / Math.abs(p1 - p2);   // = 1/|k1−k2|, k=1/p

  // rotation-only special case
  const rnd = mulberry32(0x0f0f0f0f); let worstRot = 0, worstBeat = 0;
  for (let i = 0; i < 100000; i++) {
    const p = 0.5 + rnd() * 20, th = (0.3 + rnd() * 80) * Math.PI / 180;
    const dr = D_rotation(p, th); worstRot = Math.max(worstRot, Math.abs(D_master(p, p, th) - dr) / dr);
    const p1 = 0.5 + rnd() * 20, p2 = 0.5 + rnd() * 20, db = D_beat(p1, p2);
    worstBeat = Math.max(worstBeat, Math.abs(D_masterStable(p1, p2, 0) - db) / db);
  }
  ok('master period == rotation form when p1==p2 (100k random)', worstRot < 1e-6,
     `max rel err ${worstRot.toExponential(2)}`);
  ok('master period == spatial BEAT p1p2/|p1−p2| when θ==0 (100k)', worstBeat < 1e-9,
     `max rel err ${worstBeat.toExponential(2)}`);

  // the spatial beat IS the difference of the two spatial frequencies k=1/p
  {
    const p1 = 7, p2 = 7.3, k1 = 1/p1, k2 = 1/p2;
    ok('spatial beat frequency == |k1 − k2|', approx(1 / D_beat(p1, p2), Math.abs(k1 - k2)),
       `D_beat ${D_beat(p1,p2).toFixed(2)} px`);
  }

  // headline: a 1° twist magnifies ~57× (member's figure)
  const M1 = 1 / (2 * Math.sin((1 * Math.PI / 180) / 2));
  ok('1° twist → magnification 57.3× (member: "57-fold")', M1.toFixed(1) === '57.3' && approx(M1, 57.2965, 1e-3), `${M1.toFixed(4)}×`);

  // magic angle: two honeycomb lattices at 1.1°, a = 0.246 nm → ~13 nm superlattice
  const a = 0.246; // nm, graphene lattice constant
  const Dmagic = a / (2 * Math.sin((1.1 * Math.PI / 180) / 2));
  ok('graphene magic-angle superlattice ≈ 13 nm (member: ~13 nm)', Dmagic > 12 && Dmagic < 14,
     `${Dmagic.toFixed(2)} nm`);
}

// ═════════════════════════════════════════════════════════════════════════
// (3) TIME — the wagon wheel, the temporal ALIAS.  Mirror the member's fold and
//     assert its four claims — PLUS the portal's own point: the alias is a beat
//     between the signal and the SAMPLER, and it vanishes as the sampler → ∞.
// ═════════════════════════════════════════════════════════════════════════
console.log('\n(3) time — the wheel as a beat against the camera (from research/aliasing-wagon-wheel)');
{
  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; }
  const apparent = (f, S, fs) => fold(S * f, fs) / S;
  const dir = (f, S, fs) => { const a = apparent(f, S, fs); return Math.abs(a) <= 1e-9 ? 'frozen' : (a > 0 ? 'forward' : 'BACKWARD'); };

  const S = 12, fs = 24;
  ok('first freeze at f = fs/S = 2.0 rev/s', approx(fs / S, 2.0) && approx(apparent(2.0, S, fs), 0));
  ok('1.9 rev/s shows exactly −0.1 rev/s (BACKWARD)', approx(apparent(1.9, S, fs), -0.1) && dir(1.9, S, fs) === 'BACKWARD');
  ok('2.1 rev/s shows forward', dir(2.1, S, fs) === 'forward');
  ok('Nyquist: faithful iff fs > 2·S·f', (24 > 2 * S * 0.9) === (dir(0.9, S, 24) === 'forward' && approx(apparent(0.9, S, 24), 0.9)));

  // the alias IS the beat between the spoke frequency S·f and the sampler fs:
  //   apparent spoke freq = fold(S·f, fs) = S·f − fs·round(S·f/fs)  (distance to
  //   the nearest multiple of the sampler = a difference frequency, signal vs clock).
  {
    const f = 1.9, sf = S * f;               // spoke frequency 22.8 /s
    const nearestMultiple = fs * Math.round(sf / fs);
    ok('aliased spoke freq == S·f − (nearest multiple of fs)', approx(fold(sf, fs), sf - nearestMultiple),
       `${fold(sf,fs).toFixed(2)} = ${sf} − ${nearestMultiple}`);
  }

  // THE SEAM, made checkable: remove the sampler (fs → ∞) and the alias collapses
  // to the truth — apparent spin → true spin. (No such limit exists for the beat
  // and the moiré, whose two frequencies are BOTH real signals; see (4).)
  {
    let worst = 0;
    for (const f of [0.9, 1.9, 3.7, 5.5]) {
      const big = apparent(f, S, 1e6);       // sample enormously fast ≈ look continuously
      worst = Math.max(worst, Math.abs(big - f));
    }
    ok('as fs → ∞ the apparent spin → the true spin (the alias vanishes)', worst < 1e-3,
       `max residual ${worst.toExponential(2)} rev/s`);
  }
}

// ═════════════════════════════════════════════════════════════════════════
// (4) THE UNIFYING STRUCTURE.  All three perceived patterns are a difference of
//     two frequencies; the world/clock seam is the number of INDEPENDENT signal
//     inputs (2 for the beat & moiré, 1 for the wheel — the other is the clock).
// ═════════════════════════════════════════════════════════════════════════
console.log('\n(4) the one claim none of the three states alone');
{
  const diff = (a, b) => Math.abs(a - b);
  // pitch: perceived beat = diff of the two tone frequencies
  ok('pitch: perceived = |f1 − f2|', approx(diff(440, 444), 4));
  // space: perceived = diff of the two spatial frequencies (k = 1/p)
  ok('space: perceived = |k1 − k2|', approx(diff(1/7, 1/7.3), Math.abs(1/7 - 1/7.3)));
  // time: perceived = diff of signal spoke-frequency and the SAMPLER
  const S = 12, fs = 24, f = 1.9;
  const aliasFreq = Math.abs((S * f) - fs * Math.round(S * f / fs));  // |signal − nearest clock multiple|
  ok('time: perceived = |signal − clock| (spoke freq vs frame rate)', approx(aliasFreq, 1.2),
     `${aliasFreq.toFixed(2)} /s → /S = 0.1 rev/s`);

  // world vs clock, encoded as: does the perceived pattern survive removing the
  // SECOND source? A beat/moiré needs both real signals; the wheel needs only its
  // spin plus a sampler, and removing the sampler (continuous look) removes the
  // pattern entirely. That asymmetry is the seam.
  function foldA(x, fs){ let r = x - fs*Math.round(x/fs); if (r<=-fs/2) r+=fs; if (r>fs/2) r-=fs; return r; }
  const wheelContinuous = foldA(S * f, 1e9) / S;          // continuous look
  ok('wheel: continuous look shows the TRUE motion (no pattern without a clock)',
     Math.abs(wheelContinuous - f) < 1e-4, `${wheelContinuous.toFixed(4)} rev/s`);
}

// ═════════════════════════════════════════════════════════════════════════
console.log(`\n${FAIL === 0 ? 'ALL PASS' : 'FAILURES'} — ${PASS} passed, ${FAIL} failed.`);
process.exit(FAIL === 0 ? 0 : 1);
