#!/usr/bin/env node
// verify-does-the-full-moon-affect-behavior.mjs
//
// Offline gate for /strata/does-the-full-moon-affect-behavior/. Recomputes EVERY number
// shown on the page from first principles and the real birth data, and exits non-zero if
// any check fails. Two independent methods for the phase engine:
//   (A) the Meeus phase-angle series (illuminated fraction), the same routine the page runs;
//   (B) the Meeus Ch.49 k-based instants of new/full moon (an independent algorithm),
//       cross-checked against published full/new-moon UTC dates.
//
// Data: US daily births 2000-2014 (SSA), via the FiveThirtyEight mirror, stored
// alongside this file as US_births_2000-2014_SSA.csv (5,479 contiguous days from 2000-01-01).
//
// Run:  node research/does-the-full-moon-affect-behavior/verify-does-the-full-moon-affect-behavior.mjs

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const RAD = Math.PI / 180;
let failed = 0;
function check(name, cond, detail) {
  const ok = !!cond;
  if (!ok) failed++;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}${detail ? '   ' + detail : ''}`);
}

// ────────────────────────────────────────────────────────────────────────────
// METHOD A: Meeus phase-angle series -> illuminated fraction (page routine)
// ────────────────────────────────────────────────────────────────────────────
function jd(y, m, d) {
  if (m <= 2) { y -= 1; m += 12; }
  const A = Math.floor(y / 100), B = 2 - A + Math.floor(A / 4);
  return Math.floor(365.25 * (y + 4716)) + Math.floor(30.6001 * (m + 1)) + d + B - 1524.5;
}
function illum(JD) {
  const T = (JD - 2451545.0) / 36525.0;
  const D  = 297.8501921 + 445267.1114034 * T - 0.0018819 * T * T + T * T * T / 545868 - T * T * T * T / 113065000;
  const M  = 357.5291092 + 35999.0502909 * T - 0.0001536 * T * T + T * T * T / 24490000;
  const Mp = 134.9633964 + 477198.8675055 * T + 0.0087414 * T * T + T * T * T / 69699 - T * T * T * T / 14712000;
  const d = D * RAD, m = M * RAD, mp = Mp * RAD;
  let i = 180 - D - 6.289 * Math.sin(mp) + 2.100 * Math.sin(m) - 1.274 * Math.sin(2 * d - mp)
          - 0.658 * Math.sin(2 * d) - 0.214 * Math.sin(2 * mp) - 0.110 * Math.sin(d);
  i = ((i % 360) + 360) % 360;
  return (1 + Math.cos(i * RAD)) / 2;
}
function phaseFrac(JD) {
  const f = illum(JD), f2 = illum(JD + 0.5), wax = f2 > f;
  const a = Math.acos(Math.min(1, Math.max(-1, 1 - 2 * f))) / (2 * Math.PI); // 0 at new, 0.5 at full
  return wax ? a : 1 - a;
}
// bin k is centred on phase k/NB (0 new, 2 first quarter, 4 full, 6 last quarter)
const binOf = (pf) => Math.floor(pf * 8 + 0.5) % 8;

// ────────────────────────────────────────────────────────────────────────────
// METHOD B: Meeus Ch.49 instant of new/full moon (independent algorithm)
//   phase 0.0 = new, 0.5 = full. Returns JDE (dynamical time; ignoring the small
//   deltaT here keeps us well inside the <1 day tolerance we test against).
// ────────────────────────────────────────────────────────────────────────────
function moonPhaseJDE(k) {
  const T = k / 1236.85;
  let JDE = 2451550.09766 + 29.530588861 * k
    + 0.00015437 * T * T - 0.000000150 * T * T * T + 0.00000000073 * T * T * T * T;
  const E = 1 - 0.002516 * T - 0.0000074 * T * T;
  const M  = (2.5534 + 29.10535670 * k - 0.0000014 * T * T - 0.00000011 * T * T * T) * RAD;
  const Mp = (201.5643 + 385.81693528 * k + 0.0107582 * T * T + 0.00001238 * T * T * T - 0.000000058 * T * T * T * T) * RAD;
  const F  = (160.7108 + 390.67050284 * k - 0.0016118 * T * T - 0.00000227 * T * T * T + 0.000000011 * T * T * T * T) * RAD;
  const Om = (124.7746 - 1.56375588 * k + 0.0020672 * T * T + 0.00000215 * T * T * T) * RAD;
  const frac = ((k % 1) + 1) % 1;
  let corr = 0;
  if (Math.abs(frac) < 1e-6) { // new moon
    corr = -0.40720 * Math.sin(Mp) + 0.17241 * E * Math.sin(M) + 0.01608 * Math.sin(2 * Mp)
      + 0.01039 * Math.sin(2 * F) + 0.00739 * E * Math.sin(Mp - M) - 0.00514 * E * Math.sin(Mp + M)
      + 0.00208 * E * E * Math.sin(2 * M) - 0.00111 * Math.sin(Mp - 2 * F) - 0.00057 * Math.sin(Mp + 2 * F)
      + 0.00056 * E * Math.sin(2 * Mp + M) - 0.00042 * Math.sin(3 * Mp) + 0.00042 * E * Math.sin(M + 2 * F)
      + 0.00038 * E * Math.sin(M - 2 * F) - 0.00024 * E * Math.sin(2 * Mp - M) - 0.00017 * Math.sin(Om);
  } else { // full moon (frac ~ 0.5)
    corr = -0.40614 * Math.sin(Mp) + 0.17302 * E * Math.sin(M) + 0.01614 * Math.sin(2 * Mp)
      + 0.01043 * Math.sin(2 * F) + 0.00734 * E * Math.sin(Mp - M) - 0.00515 * E * Math.sin(Mp + M)
      + 0.00209 * E * E * Math.sin(2 * M) - 0.00111 * Math.sin(Mp - 2 * F) - 0.00057 * Math.sin(Mp + 2 * F)
      + 0.00056 * E * Math.sin(2 * Mp + M) - 0.00042 * Math.sin(3 * Mp) + 0.00042 * E * Math.sin(M + 2 * F)
      + 0.00038 * E * Math.sin(M - 2 * F) - 0.00024 * E * Math.sin(2 * Mp - M) - 0.00017 * Math.sin(Om);
  }
  return JDE + corr;
}
function jdToUTC(JD) {
  const Z = Math.floor(JD + 0.5), Fr = JD + 0.5 - Z;
  let A = Z;
  if (Z >= 2299161) { const alpha = Math.floor((Z - 1867216.25) / 36524.25); A = Z + 1 + alpha - Math.floor(alpha / 4); }
  const B = A + 1524, C = Math.floor((B - 122.1) / 365.25), D = Math.floor(365.25 * C), E = Math.floor((B - D) / 30.6001);
  const day = B - D - Math.floor(30.6001 * E) + Fr;
  const month = E < 14 ? E - 1 : E - 13;
  const year = month > 2 ? C - 4716 : C - 4715;
  return { year, month, day };
}

console.log('=== PHASE ENGINE (two independent methods) ===');

// Known full moons and new moons (UTC calendar date of the event), for both methods.
const KNOWN_FULL = [[2013, 6, 23], [2021, 1, 28], [2024, 9, 18], [2024, 10, 17], [2025, 3, 14]];
const KNOWN_NEW  = [[2024, 10, 2], [2025, 3, 29], [2023, 1, 21]];

// Method A: illuminated fraction should be ~1 at full, ~0 at new.
let aFullOK = true, aNewOK = true;
for (const [y, m, d] of KNOWN_FULL) if (illum(jd(y, m, d) + 0.5) < 0.99) aFullOK = false;
for (const [y, m, d] of KNOWN_NEW)  if (illum(jd(y, m, d) + 0.5) > 0.01) aNewOK = false;
check('A: illum > 99% on known full moons', aFullOK,
  KNOWN_FULL.map(([y, m, d]) => `${y}-${m}-${d}:${(illum(jd(y, m, d) + 0.5) * 100).toFixed(1)}%`).join(' '));
check('A: illum < 1% on known new moons', aNewOK,
  KNOWN_NEW.map(([y, m, d]) => `${y}-${m}-${d}:${(illum(jd(y, m, d) + 0.5) * 100).toFixed(2)}%`).join(' '));

// Method B: k-based instants must land on the published calendar dates (within 1 day).
// k ~= (year - 2000) * 12.3685 ; integer -> new moon, +0.5 -> full moon.
function nearestPhase(y, m, d, phaseOffset) {
  const targetJD = jd(y, m, d);
  const kApprox = (y + (m - 0.5) / 12 - 2000) * 12.3685;
  let best = null;
  for (let kk = Math.round(kApprox) - 2; kk <= Math.round(kApprox) + 2; kk++) {
    const JDE = moonPhaseJDE(kk + phaseOffset);
    if (best === null || Math.abs(JDE - targetJD) < Math.abs(best - targetJD)) best = JDE;
  }
  return best;
}
let bFullOK = true, bNewOK = true;
for (const [y, m, d] of KNOWN_FULL) if (Math.abs(nearestPhase(y, m, d, 0.5) - jd(y, m, d)) > 1.0) bFullOK = false;
for (const [y, m, d] of KNOWN_NEW)  if (Math.abs(nearestPhase(y, m, d, 0.0) - jd(y, m, d)) > 1.0) bNewOK = false;
check('B: Ch.49 full-moon instants within 1 day of published dates', bFullOK,
  KNOWN_FULL.map(([y, m, d]) => { const u = jdToUTC(nearestPhase(y, m, d, 0.5)); return `${u.year}-${u.month}-${Math.floor(u.day)}`; }).join(' '));
check('B: Ch.49 new-moon instants within 1 day of published dates', bNewOK,
  KNOWN_NEW.map(([y, m, d]) => { const u = jdToUTC(nearestPhase(y, m, d, 0.0)); return `${u.year}-${u.month}-${Math.floor(u.day)}`; }).join(' '));

// A vs B agreement: at each Method-B full-moon instant, Method-A illum must be ~max.
let agreeOK = true;
for (let kk = 160; kk < 220; kk++) {
  const jdeFull = moonPhaseJDE(kk + 0.5);
  if (illum(jdeFull) < 0.985) agreeOK = false;
  const jdeNew = moonPhaseJDE(kk);
  if (illum(jdeNew) > 0.015) agreeOK = false;
}
check('A vs B agree: illum ~1 at B full instants, ~0 at B new instants (60 cycles)', agreeOK);

// ────────────────────────────────────────────────────────────────────────────
// THE BIRTH BINNING (the ≤1% figure) — recomputed from the real CSV
// ────────────────────────────────────────────────────────────────────────────
console.log('\n=== BIRTHS BINNED BY LUNAR PHASE (real SSA data) ===');
const csv = fs.readFileSync(path.join(HERE, 'US_births_2000-2014_SSA.csv'), 'utf8').trim().split('\n').slice(1);
const rows = csv.map((l) => l.split(',').map(Number)); // year,month,date,dow(1=Mon..7=Sun),births
check('data: 5,479 contiguous daily rows loaded', rows.length === 5479, `rows=${rows.length}`);

// Independent check that the CSV is contiguous daily from 2000-01-01 (so the page can
// reconstruct dates by index).
let contiguous = true;
{
  const d = new Date(Date.UTC(2000, 0, 1));
  for (const r of rows) {
    if (r[0] !== d.getUTCFullYear() || r[1] !== d.getUTCMonth() + 1 || r[2] !== d.getUTCDate()) { contiguous = false; break; }
    const js = d.getUTCDay(); if (r[3] !== (js === 0 ? 7 : js)) { contiguous = false; break; }
    d.setUTCDate(d.getUTCDate() + 1);
  }
}
check('data: contiguous daily & day-of-week matches (page reconstructs by index)', contiguous);

const NB = 8;
const mean = (a) => a.reduce((x, y) => x + y, 0) / a.length;
function eta2(groups) {
  const all = [].concat(...groups), gm = mean(all);
  let ssb = 0, sst = 0;
  for (const g of groups) { const m = mean(g); ssb += g.length * (m - gm) ** 2; }
  for (const x of all) sst += (x - gm) ** 2;
  return ssb / sst;
}

const bins = Array.from({ length: NB }, () => []);
const dow = Array.from({ length: 7 }, () => []);
const ill = [];
for (const [y, mo, da, dw, b] of rows) {
  const JD = jd(y, mo, da) + 0.5;
  bins[binOf(phaseFrac(JD))].push(b);
  dow[dw - 1].push(b);
  ill.push({ f: illum(JD), dow: dw, b, JD });
}
const overall = mean(rows.map((r) => r[4]));
const lunarEta2 = eta2(bins);
const dowEta2 = eta2(dow);
const dowMean = dow.map(mean);
const binsRes = Array.from({ length: NB }, () => []);
for (const [y, mo, da, dw, b] of rows) binsRes[binOf(phaseFrac(jd(y, mo, da) + 0.5))].push(b - dowMean[dw - 1]);
const residEta2 = eta2(binsRes);
const fmBin = mean(bins[4]);
const rest = mean([].concat(...bins.filter((_, i) => i !== 4)));
const fmBinDiffPct = (fmBin / rest - 1) * 100;
// the bin labelled Full must hold the days nearest full moon (and bin 0 the days nearest new)
const binIllum = Array.from({ length: NB }, () => []);
for (const x of ill) binIllum[binOf(phaseFrac(x.JD))].push(x.f);
const binIllumMean = binIllum.map(mean);

check('overall mean births/day = 11,350', Math.round(overall) === 11350, `mean=${overall.toFixed(1)}`);
check('lunar phase variance explained η² ≤ 1% (Rotton & Kelly ceiling)', lunarEta2 <= 0.01,
  `η²=${(lunarEta2 * 100).toFixed(4)}%`);
check('correlation r = √η² ≤ ~0.02 (Rotton & Kelly 1% ceiling is r ≤ 0.1)', Math.sqrt(lunarEta2) <= 0.02,
  `r=${Math.sqrt(lunarEta2).toFixed(4)}`);
check('bin 4 (labelled Full) holds the brightest days, bin 0 (New) the darkest',
  binIllumMean[4] > 0.95 && binIllumMean[0] < 0.05 && binIllumMean.every((v) => v <= binIllumMean[4] && v >= binIllumMean[0]),
  `mean illum by bin ${binIllumMean.map((v) => (v * 100).toFixed(1)).join('/')}%`);
check('full-moon phase bin within ±1% of the rest (no spike)', Math.abs(fmBinDiffPct) < 1,
  `diff=${fmBinDiffPct.toFixed(2)}%`);
check('day-of-week η² ≫ lunar η² (the real cyclic driver)', dowEta2 > 0.5 && dowEta2 > lunarEta2 * 1000,
  `dow η²=${(dowEta2 * 100).toFixed(1)}% vs lunar ${(lunarEta2 * 100).toFixed(4)}%`);
check('lunar η² after removing the weekly cycle still ≤ 1%', residEta2 <= 0.01,
  `resid η²=${(residEta2 * 100).toFixed(4)}%`);

// Confirmation-bias demonstrator: full moons on weekdays fake a bump; control kills it.
const wd = ill.filter((x) => x.f > 0.96 && x.dow <= 5).map((x) => x.b);
const believerPct = (mean(wd) / overall - 1) * 100;
const res = ill.filter((x) => x.f > 0.96 && x.dow <= 5).map((x) => x.b - dowMean[x.dow - 1]);
const believerCtrlPct = (mean(res) / overall) * 100;
check('confirmation-bias bump appears (full moons on weekdays > +5% vs avg)', believerPct > 5,
  `+${believerPct.toFixed(1)}%`);
check('bump collapses under day-of-week control (< 1%)', Math.abs(believerCtrlPct) < 1,
  `+${believerCtrlPct.toFixed(2)}%`);

// ────────────────────────────────────────────────────────────────────────────
// THE SLEEP EXCEPTION (Casiraghi 2021) — direction + reported amplitudes
// ────────────────────────────────────────────────────────────────────────────
console.log('\n=== SLEEP EXCEPTION (Casiraghi 2021, reconstructed) ===');
const SYN = 29.530588853, PEAK = -4;
// Fitted sleep-onset amplitudes (min), Casiraghi 2021 Science Advances 7:eabe0465, Fig. 2:
//   rural no-electricity 10.0 [6.2–13.7], rural limited-light 12.1 [9.1–15.1], urban 6.4 [2.5–10.3].
// (Seattle was reported as a z-score, not minutes.) The three CIs overlap, so the source-supported
// claim is the two low-light rural communities > urban, NOT a monotone no-light>limited>urban ladder.
const AMP = { noElec: 10.0, limited: 12.1, urban: 6.4 };
const onsetDelay = (day, amp) => amp * Math.cos(2 * Math.PI * (day - PEAK) / SYN);
check('onset delayed in the nights before full moon (peak at day -4 > 0)',
  onsetDelay(PEAK, AMP.noElec) > 0, `peak=+${onsetDelay(PEAK, AMP.noElec).toFixed(1)} min`);
check('peak sits before full moon, not at/after it',
  onsetDelay(PEAK, AMP.noElec) > onsetDelay(0, AMP.noElec) &&
  onsetDelay(PEAK, AMP.noElec) > onsetDelay(4, AMP.noElec));
check('both low-light rural communities show larger onset amplitude than urban',
  AMP.noElec > AMP.urban && AMP.limited > AMP.urban,
  `no-elec ${AMP.noElec}, limited ${AMP.limited} > urban ${AMP.urban} min`);
check('amplitudes within Casiraghi reported onset range (6.4–12.1 min)',
  AMP.urban >= 6 && AMP.noElec >= 6 && AMP.noElec <= 13 && AMP.limited >= 6 && AMP.limited <= 13);

// ────────────────────────────────────────────────────────────────────────────
console.log('\n' + (failed === 0
  ? 'ALL CHECKS PASSED: behavior is a near-perfect null (≤1% variance); sleep is the one small, real exception, most likely light-driven.'
  : `${failed} CHECK(S) FAILED.`));
process.exit(failed === 0 ? 0 : 1);
