#!/usr/bin/env node
// verify.mjs — The Blink That Measures the Universe (P1, the Verification Venue)
//
// Re-derives, from Leavitt's own 1912 data, every number the page states or draws:
//   §1  the reproduction: least-squares Leavitt Law from her 25 SMC Cepheids
//       (slope in mag per dex, and her stated "0.48 in log P per magnitude")
//   §2  the fit is a LAW, not a line through a cloud: correlation |r| and the
//       linear-vs-log straightening the page's axis-flip shows
//   §3  her own residuals reproduced: our line's residuals match her Res. M / Res. m
//   §4  the distance ladder: the distance-modulus arithmetic, reproducing the
//       accepted distances to δ Cephei (~274 pc) and to Andromeda (~2.5 Mly)
//
// Data + citations live in data.mjs; the page reads the same file. Run: node verify.mjs
import { LEAVITT_1912, PL_MODERN_V, PC_PER_LY, distancePc, TARGETS } from './data.mjs';

let n = 0, pass = 0;
function check(name, ok, detail = '') {
  n++;
  if (ok) { pass++; console.log(`  ok ${String(n).padStart(2)} — ${name}${detail ? '  [' + detail + ']' : ''}`); }
  else { console.error(`FAIL ${String(n).padStart(2)} — ${name}${detail ? '  [' + detail + ']' : ''}`); }
}
const close = (a, b, tol) => Math.abs(a - b) <= tol;

// ordinary least squares: y = a + b·x ; returns {a,b,r}
function ols(xs, ys) {
  const N = xs.length;
  const mx = xs.reduce((s, v) => s + v, 0) / N;
  const my = ys.reduce((s, v) => s + v, 0) / N;
  let sxx = 0, sxy = 0, syy = 0;
  for (let i = 0; i < N; i++) {
    sxx += (xs[i] - mx) ** 2;
    syy += (ys[i] - my) ** 2;
    sxy += (xs[i] - mx) * (ys[i] - my);
  }
  const b = sxy / sxx;
  const a = my - b * mx;
  const r = sxy / Math.sqrt(sxx * syy);
  return { a, b, r };
}

const stars = LEAVITT_1912.stars;
const logP = stars.map(s => Math.log10(s.P));
const maxMag = stars.map(s => s.max);   // brightness at maximum (smaller = brighter)
const minMag = stars.map(s => s.min);

console.log('§0 the primary table');
check('Table I holds exactly 25 variable stars', stars.length === 25, `n=${stars.length}`);
check('periods span 1.25336 d (H1505) to 127.0 d (H821)',
  Math.min(...stars.map(s => s.P)) === 1.25336 && Math.max(...stars.map(s => s.P)) === 127.0);
check('every star: max is brighter (smaller mag) than min',
  stars.every(s => s.max < s.min));

console.log('\n§1 the reproduction — Leavitt Law from her 25 stars');
const fitMax = ols(logP, maxMag);
const fitMin = ols(logP, minMag);
console.log(`   maxima:  m = ${fitMax.a.toFixed(3)} + (${fitMax.b.toFixed(3)})·log10 P   (r = ${fitMax.r.toFixed(4)})`);
console.log(`   minima:  m = ${fitMin.a.toFixed(3)} + (${fitMin.b.toFixed(3)})·log10 P   (r = ${fitMin.r.toFixed(4)})`);
// Leavitt's stated result: log P rises ~0.48 per magnitude of brightening.
// Our fitted slope b = d(mag)/d(logP); brightening = mag decreasing, so
// d(logP)/d(brightening) = -1/b. Reproduce her 0.48 for both series.
const logPperMagMax = -1 / fitMax.b;
const logPperMagMin = -1 / fitMin.b;
console.log(`   → d(log P) per magnitude:  maxima ${logPperMagMax.toFixed(3)}, minima ${logPperMagMin.toFixed(3)}  (Leavitt: 0.48)`);
check('maxima slope is negative & steep (brighter ⇒ longer period)', fitMax.b < -1.5, fitMax.b.toFixed(3));
check('minima slope is negative & steep', fitMin.b < -1.5, fitMin.b.toFixed(3));
check("reproduces Leavitt's 'about 0.48 in log P per magnitude' (maxima), tol 0.06",
  close(logPperMagMax, LEAVITT_1912.leavittSlopeLogPPerMag, 0.06), logPperMagMax.toFixed(3));
check("reproduces Leavitt's 'about 0.48 in log P per magnitude' (minima), tol 0.06",
  close(logPperMagMin, LEAVITT_1912.leavittSlopeLogPPerMag, 0.06), logPperMagMin.toFixed(3));

console.log('\n§2 it is a law, not a cloud — the log axis straightens it');
check('maxima correlation |r| > 0.95 on log-period axis', Math.abs(fitMax.r) > 0.95, `|r|=${Math.abs(fitMax.r).toFixed(4)}`);
check('minima correlation |r| > 0.95 on log-period axis', Math.abs(fitMin.r) > 0.95, `|r|=${Math.abs(fitMin.r).toFixed(4)}`);
// The linear-period axis (Leavitt's Fig. 1) is visibly CURVED: a straight fit
// against raw period is worse than against log period. Show it quantitatively.
const fitMaxLinear = ols(stars.map(s => s.P), maxMag);
const rmse = (fit, xs, ys) => Math.sqrt(ys.reduce((s, y, i) => s + (y - (fit.a + fit.b * xs[i])) ** 2, 0) / ys.length);
const rmseLog = rmse(fitMax, logP, maxMag);
const rmseLin = rmse(fitMaxLinear, stars.map(s => s.P), maxMag);
console.log(`   RMSE of a straight line: vs log10 P = ${rmseLog.toFixed(3)} mag ; vs raw P = ${rmseLin.toFixed(3)} mag`);
check('a straight line fits the LOG-period axis far better than the raw-period axis',
  rmseLog < 0.7 * rmseLin, `${rmseLog.toFixed(3)} < 0.7·${rmseLin.toFixed(3)}`);

console.log('\n§3 her own residuals reproduced');
// Leavitt tabulated Res. M / Res. m: residuals of each star from her hand-drawn
// lines in Fig. 2. Our least-squares residuals should track hers closely.
// Sign convention (tested): Leavitt's residual ≈ (observed magnitude) − (line).
let rmsResDiffMax = 0, rmsResDiffMin = 0;
for (let i = 0; i < stars.length; i++) {
  const ourResMax = maxMag[i] - (fitMax.a + fitMax.b * logP[i]);
  const ourResMin = minMag[i] - (fitMin.a + fitMin.b * logP[i]);
  rmsResDiffMax += (ourResMax - stars[i].resMax) ** 2;
  rmsResDiffMin += (ourResMin - stars[i].resMin) ** 2;
}
rmsResDiffMax = Math.sqrt(rmsResDiffMax / stars.length);
rmsResDiffMin = Math.sqrt(rmsResDiffMin / stars.length);
console.log(`   RMS difference (our residual − Leavitt's tabulated): maxima ${rmsResDiffMax.toFixed(3)}, minima ${rmsResDiffMin.toFixed(3)} mag`);
check("our residuals match Leavitt's Res. M to < 0.15 mag RMS", rmsResDiffMax < 0.15, rmsResDiffMax.toFixed(3));
check("our residuals match Leavitt's Res. m to < 0.20 mag RMS", rmsResDiffMin < 0.20, rmsResDiffMin.toFixed(3));
// her residuals are small: the law holds to ~a quarter magnitude
const rmsHerResMax = Math.sqrt(stars.reduce((s, st) => s + st.resMax ** 2, 0) / stars.length);
check("Leavitt's own scatter about her line is < 0.3 mag RMS (a real law)", rmsHerResMax < 0.3, rmsHerResMax.toFixed(3));

console.log('\n§4 the distance ladder — the stopwatch becomes a ruler');
// Distance modulus μ = m − M = 5 log10(d/10pc). Check the identity round-trips.
{
  const dTest = 1000; // pc
  const mu = 5 * Math.log10(dTest / 10);
  check('distance-modulus identity round-trips (1000 pc ⇒ μ=10 ⇒ 1000 pc)',
    close(distancePc(mu, 0), 1000, 1e-6) && close(mu, 10, 1e-9));
}
// δ Cephei — Galactic prototype. Correct apparent mag for foreground extinction,
// then apply the modern P–L law, then invert the distance modulus.
{
  const t = TARGETS.deltaCephei;
  const M = PL_MODERN_V.absMag(t.P);
  const m0 = t.appMag_V - t.extinction_A_V;   // de-reddened apparent magnitude
  const d = distancePc(m0, M);
  console.log(`   δ Cephei: P=${t.P} d → M_V=${M.toFixed(2)} ; m0=${m0.toFixed(2)} → d=${d.toFixed(0)} pc (accepted ${t.acceptedDistance_pc}±${t.acceptedTol_pc})`);
  check('δ Cephei distance from Leavitt Law matches HST parallax (±25 pc)',
    close(d, t.acceptedDistance_pc, t.acceptedTol_pc), `${d.toFixed(0)} pc`);
}
// Andromeda — a representative Cepheid places M31 at the modern distance.
{
  const t = TARGETS.andromeda;
  const M = PL_MODERN_V.absMag(t.P);
  const m0 = t.appMag_V - t.extinction_A_V;
  const d = distancePc(m0, M);
  const dMly = d * PC_PER_LY / 1e6;
  console.log(`   M31: P=${t.P} d → M_V=${M.toFixed(2)} ; m=${m0.toFixed(2)} → d=${(d / 1000).toFixed(0)} kpc = ${dMly.toFixed(2)} Mly (accepted ≈ ${(t.acceptedDistance_pc / 1000).toFixed(0)} kpc)`);
  check('Andromeda distance ≈ 785 kpc (±60 kpc) from the same law',
    close(d, t.acceptedDistance_pc, t.acceptedTol_pc), `${(d / 1000).toFixed(0)} kpc`);
  check('Andromeda distance rounds to ≈ 2.5 million light-years',
    close(dMly, 2.5, 0.2), `${dMly.toFixed(2)} Mly`);
}

console.log(`\n${pass}/${n} checks passed`);
process.exit(pass === n ? 0 : 1);
