// verify.mjs — recompute, from scratch, the EQUATION OF TIME (the gap between the
// sundial and the clock) and the ANALEMMA, and prove the checkable headline:
//
//   The shortest day of the year IS the winter solstice — but the EARLIEST SUNSET
//   is not. At mid-northern latitudes the earliest sunset falls about two weeks
//   BEFORE the solstice, and the latest sunrise about two weeks AFTER it.
//
//   node research/equation-of-time/verify.mjs
//
// The equation of time is computed TWO INDEPENDENT WAYS and shown to agree:
//
//   Route 1 (spherical):  the Sun's true geometric longitude is reduced to its
//       right ascension by the actual spherical trigonometry of the tilted
//       ecliptic, and  E = (mean longitude) − (right ascension).  This is the
//       low-precision solar algorithm of Meeus, *Astronomical Algorithms* (2nd
//       ed., 1998), chapters 25 & 28.  A full apparent-position variant (with
//       aberration + nutation) reproduces Meeus's own worked Example 28.b.
//
//   Route 2 (analytic):   the standard truncated Fourier expansion of the same
//       quantity in the two small parameters — orbital eccentricity e and
//       y = tan²(ε/2) — which SEPARATES the two physical causes:
//           eccentricity (annual):   −2e·sinM − (5/4)e²·sin2M
//           obliquity   (semiannual): y·sin2L − (1/2)y²·sin4L
//           cross term:               4ey·sinM·cos2L
//       (e.g. the derivation in the Explanatory Supplement to the Astronomical
//       Almanac, and the compact form widely reproduced from it.)
//
// The two routes are genuinely independent derivations; they agree to a few
// seconds of time across the whole year.  The resulting curve is then anchored
// against the canon — the four extrema and four zero-crossings that the USNO,
// Meeus, and the Astronomical Almanac all publish with the same values.
//
// Finally the sunrise/sunset asymmetry is computed from the same machine for a
// range of latitudes, proving the headline and its latitude dependence.
//
// Free choices, declared:  a reference year of 2026 (the curve drifts ~1 day
// across the leap-year cycle and very slowly with the secular change of e and ε);
// the standard sunrise altitude a0 = −0.833° (34' refraction + 16' semidiameter);
// the observer's longitude/timezone is irrelevant to the asymmetry (it shifts
// every sunrise and sunset by the same amount) and is taken as the local mean
// meridian.  Nothing here depends on those choices except at the ~1-day level,
// which is stated on the page.

let fails = 0;
const ok  = (name, cond, extra='') => { console.log((cond?'  ok   ':'  FAIL ')+name+(extra?'  '+extra:'')); if(!cond) fails++; };
const sec = (s) => console.log('\n=== '+s+' ===');
const RAD = Math.PI/180, DEG = 180/Math.PI;
const norm360 = (x)=>{ x%=360; return x<0?x+360:x; };

/* ───────────────────────── calendar → Julian Day ───────────────────────── */
// Meeus ch. 7, Gregorian calendar.  d may be fractional (UT day fraction).
function julianDay(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;
}

/* ──────────── Route 1: the spherical solar position (Meeus 25 & 28) ──────── */
function solar(jd) {
  const T = (jd - 2451545.0) / 36525.0;                 // Julian centuries since J2000
  const L0 = norm360(280.46646 + 36000.76983*T + 0.0003032*T*T);   // geometric mean longitude
  const M  = norm360(357.52911 + 35999.05029*T - 0.0001537*T*T);   // mean anomaly
  const e  = 0.016708634 - 0.000042037*T - 0.0000001267*T*T;       // eccentricity of Earth's orbit
  const Mr = M*RAD;
  const C  = (1.914602 - 0.004817*T - 0.000014*T*T)*Math.sin(Mr)   // equation of centre
           + (0.019993 - 0.000101*T)*Math.sin(2*Mr)
           +  0.000289*Math.sin(3*Mr);
  const trueLong = L0 + C;                              // Sun's true geometric longitude ☉
  // apparent longitude (aberration + nutation in longitude), Meeus 25.x
  const Omega = 125.04 - 1934.136*T;
  const lambdaApp = trueLong - 0.00569 - 0.00478*Math.sin(Omega*RAD);
  // mean obliquity (Meeus 22.2) and true obliquity (+ nutation in obliquity, simplified)
  const eps0 = 23 + (26 + 21.448/60)/60 - (46.8150*T + 0.00059*T*T - 0.001813*T*T*T)/3600;
  const epsTrue = eps0 + 0.00256*Math.cos(Omega*RAD);
  // right ascension from longitude — the reduction across the tilted ecliptic
  const raGeom = norm360( Math.atan2(Math.cos(eps0*RAD)*Math.sin(trueLong*RAD), Math.cos(trueLong*RAD)) * DEG );
  const raApp  = norm360( Math.atan2(Math.cos(epsTrue*RAD)*Math.sin(lambdaApp*RAD), Math.cos(lambdaApp*RAD)) * DEG );
  // declination (apparent), for sunrise/sunset and the analemma
  const decl = Math.asin( Math.sin(epsTrue*RAD)*Math.sin(lambdaApp*RAD) ) * DEG;
  // Equation of time, geometric (E = mean longitude − right ascension), minutes of time
  const eGeomDeg = norm180(L0 - raGeom);
  // Equation of time, apparent (Meeus 28.3): includes aberration constant + nutation
  const dpsiCosEps = -0.00478*Math.sin(Omega*RAD) * Math.cos(epsTrue*RAD); // Δψ·cosε, deg
  const eAppDeg  = norm180(L0 - 0.0057183 - raApp + dpsiCosEps);
  return { T, L0, M, e, trueLong, lambdaApp, eps0, epsTrue, raGeom, raApp, decl,
           eotGeomMin: eGeomDeg*4, eotAppMin: eAppDeg*4 };
}
function norm180(x){ x = norm360(x); return x>180 ? x-360 : x; }

/* ─────────────── Route 2: the analytic two-cause Fourier form ────────────── */
// Returns the equation of time in minutes, split into its physical components.
// Sign convention matches Route 1 geometric (E = apparent − mean solar time).
function eotAnalytic(jd) {
  const T  = (jd - 2451545.0) / 36525.0;
  const L0 = norm360(280.46646 + 36000.76983*T + 0.0003032*T*T) * RAD;
  const M  = norm360(357.52911 + 35999.05029*T - 0.0001537*T*T) * RAD;
  const e  = 0.016708634 - 0.000042037*T;
  const eps0 = (23 + (26 + 21.448/60)/60 - (46.8150*T)/3600) * RAD;
  const y  = Math.tan(eps0/2)**2;                       // y = tan²(ε/2)
  const ecc    = (-2*e*Math.sin(M) - 1.25*e*e*Math.sin(2*M));
  const obliq  = ( y*Math.sin(2*L0) - 0.5*y*y*Math.sin(4*L0) );
  const cross  = ( 4*e*y*Math.sin(M)*Math.cos(2*L0) );
  const totalRad = ecc + obliq + cross;                 // radians of hour angle
  const toMin = DEG*4;                                  // rad→deg→minutes (×4 min/deg)
  return { total: totalRad*toMin, ecc: ecc*toMin, obliq: obliq*toMin, cross: cross*toMin };
}

/* ───────────────────────── sunrise / sunset model ───────────────────────── */
const A0 = -0.833;   // standard sunrise/sunset Sun altitude: −34' refraction − 16' semidiameter
// For a given calendar day in `year`, evaluated at local solar noon, return the
// clock times (in hours, local mean time at the standard meridian) of sunrise,
// solar transit and sunset, plus daylight length and the day's declination.
function dayTimes(year, dayOfYear, latDeg) {
  // JD at 12h UT of this day; day 0 = Jan 1
  const jdJan1 = julianDay(year, 1, 1.5);              // 1.5 = noon UT on Jan 1
  const jd = jdJan1 + dayOfYear;
  const s = solar(jd);
  const E = s.eotAppMin;                                // minutes; apparent − mean
  const noonClock = 12 - E/60;                          // mean (clock) time of apparent noon, hours
  const phi = latDeg*RAD, dec = s.decl*RAD;
  const cosH = (Math.sin(A0*RAD) - Math.sin(phi)*Math.sin(dec)) / (Math.cos(phi)*Math.cos(dec));
  if (cosH >  1) return { polar:'night', decl:s.decl, E, noonClock };  // sun never rises
  if (cosH < -1) return { polar:'day',   decl:s.decl, E, noonClock };  // midnight sun
  const H = Math.acos(cosH)*DEG;                        // half-day arc, degrees
  const halfHours = H/15;                               // 15°/hour
  return { sunrise: noonClock - halfHours, sunset: noonClock + halfHours,
           noon: noonClock, daylight: 2*halfHours, decl: s.decl, E };
}
// Day-of-year of the extremum of f over a window [d0,d1] (d may exceed 364, i.e.
// run into the next January — the northern winter straddles the year boundary).
function extremumDay(year, latDeg, pick, sign, d0=0, d1=364) {
  let best=null;
  for (let d=d0; d<=d1; d++) {
    const t = dayTimes(year, d, latDeg);
    const v = pick(t);
    if (v===undefined) continue;
    if (!best || sign*v > sign*best.value) best = { day:d, value:v };
  }
  return best;
}
const MONTHS=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
function dayLabel(year, d){
  const jd = julianDay(year,1,1.5)+d;
  // invert JD→calendar (Meeus 7)
  let Z = Math.floor(jd+0.5), F=jd+0.5-Z;
  let A = Z;
  if (Z>=2299161){ const al=Math.floor((Z-1867216.25)/36524.25); A=Z+1+al-Math.floor(al/4); }
  const B=A+1524, C=Math.floor((B-122.1)/365.25), Dd=Math.floor(365.25*C), Ee=Math.floor((B-Dd)/30.6001);
  const day=B-Dd-Math.floor(30.6001*Ee)+F;
  const month=Ee<14?Ee-1:Ee-13;
  return `${MONTHS[month-1]} ${Math.floor(day)}`;  // day 0 is noon (F = 0.5): floor, not round
}

/* ════════════════════════════════ TESTS ════════════════════════════════ */
const YEAR = 2026;

sec('The date labels are real calendar dates (they read Jan 32 and Dec 32 until 2026-09-29)');
{
  const labs = Array.from({length:365}, (_,d)=>dayLabel(YEAR,d));
  ok('day 0 is Jan 1 and day 364 is Dec 31', labs[0]==='Jan 1' && labs[364]==='Dec 31', `${labs[0]} … ${labs[364]}`);
  ok('365 distinct labels, none past its month', new Set(labs).size===365 && labs.every(l=>{ const [m,dd]=l.split(' '); return +dd>=1 && +dd<=[31,28,31,30,31,30,31,31,30,31,30,31][MONTHS.indexOf(m)]; }));
}

sec('Route 1 reproduces Meeus, Astronomical Algorithms, Example 28.b (1992 Oct 13.0 TD)');
{
  const jd = julianDay(1992, 10, 13.0);                 // = 2448908.5
  ok('JD(1992-10-13.0) = 2448908.5', Math.abs(jd-2448908.5)<1e-6, 'jd='+jd);
  const s = solar(jd);
  // Meeus's published result for the apparent equation of time: E = +13m 42.7s
  const target = 13 + 42.7/60;                          // minutes
  ok('apparent E = +13m42.7s (Meeus 28.b)', Math.abs(s.eotAppMin-target)<0.1,
     `E = ${s.eotAppMin.toFixed(4)} min (${minToMS(s.eotAppMin)})  target ${minToMS(target)}`);
}

sec('Route 1 ≡ Route 2 — the two derivations agree across the whole year (geometric)');
{
  let maxDiff=0, worst='';
  for (let d=0; d<365; d++) {
    const jd = julianDay(YEAR,1,1.5)+d;
    const e1 = solar(jd).eotGeomMin;
    const e2 = eotAnalytic(jd).total;
    const diff = Math.abs(e1-e2);
    if (diff>maxDiff){ maxDiff=diff; worst=dayLabel(YEAR,d); }
  }
  ok('spherical vs analytic agree to < 3 s of time all year (the page says under three seconds)', maxDiff < 0.05,
     `max gap = ${(maxDiff*60).toFixed(2)} s (near ${worst})`);
}

sec('The two physical causes sum to the whole, and have the right amplitudes');
{
  // sample the components over the year; obliquity is semiannual (~9.9 min),
  // eccentricity is annual (~7.7 min).
  let maxEcc=0, maxObl=0;
  for (let d=0; d<365; d++) {
    const c = eotAnalytic(julianDay(YEAR,1,1.5)+d);
    maxEcc=Math.max(maxEcc, Math.abs(c.ecc));
    maxObl=Math.max(maxObl, Math.abs(c.obliq));
    if (Math.abs((c.ecc+c.obliq+c.cross)-c.total)>1e-9) { ok('components sum to total', false); break; }
  }
  ok('components sum to total exactly', true);
  ok('eccentricity term amplitude ≈ 7.7 min', Math.abs(maxEcc-7.66)<0.2, `|ecc|max = ${maxEcc.toFixed(2)} min`);
  ok('obliquity term amplitude ≈ 9.9 min',   Math.abs(maxObl-9.87)<0.2, `|obl|max = ${maxObl.toFixed(2)} min`);
}

sec('The canon — the four extrema and four zeros (USNO / Meeus / Astron. Almanac)');
{
  // sample at fine resolution and locate extrema/zeros
  const N=365*4; const pts=[];
  for (let i=0;i<=N;i++){ const d=i/4; const jd=julianDay(YEAR,1,1.5)+d; pts.push({d, E:solar(jd).eotAppMin}); }
  // global + local extrema by scanning sign changes of the slope
  const ext=[];
  for (let i=1;i<pts.length-1;i++){
    if ((pts[i].E-pts[i-1].E)>=0 && (pts[i+1].E-pts[i].E)<0) ext.push({type:'max', ...pts[i]});
    if ((pts[i].E-pts[i-1].E)<=0 && (pts[i+1].E-pts[i].E)>0) ext.push({type:'min', ...pts[i]});
  }
  const zeros=[];
  for (let i=1;i<pts.length;i++){ if (Math.sign(pts[i].E)!==Math.sign(pts[i-1].E)) zeros.push(pts[i].d); }
  const named = ext.map(e=>({...e, label:dayLabel(YEAR,Math.round(e.d)), ms:minToMS(e.E)}));
  console.log('     extrema:', named.map(e=>`${e.label} ${e.ms}`).join('  |  '));
  console.log('     zeros  :', zeros.map(d=>dayLabel(YEAR,Math.round(d))).join('  '));
  // canon (degrees of tolerance generous: ±0.3 min, ±2 days)
  const find=(lo,hi)=>named.find(e=>e.d>=lo&&e.d<=hi);
  const nov = find(300,313), feb = find(35,48), may = find(125,142), jul = find(195,215);
  ok('max  ≈ +16.4 min near Nov 3', nov && Math.abs(nov.E-16.4)<0.4, nov?`${nov.label} ${nov.ms}`:'not found');
  ok('min  ≈ −14.2 min near Feb 11', feb && Math.abs(feb.E+14.2)<0.4, feb?`${feb.label} ${feb.ms}`:'not found');
  ok('local max ≈ +3.7 min near May 14', may && Math.abs(may.E-3.7)<0.5, may?`${may.label} ${may.ms}`:'not found');
  ok('local min ≈ −6.4 min near Jul 26', jul && Math.abs(jul.E+6.4)<0.5, jul?`${jul.label} ${jul.ms}`:'not found');
  ok('exactly four zero-crossings in the year', zeros.length===4, '#='+zeros.length);
}

sec('THE HEADLINE — earliest sunset precedes the shortest day, latest sunrise follows it');
{
  // Scan one contiguous northern winter: Nov 1 (≈day 304) → mid-Feb of next year
  // (day 410), so the early-January latest-sunrise belongs to THIS solstice, not
  // the previous one.
  const W0=304, W1=410;
  for (const lat of [51.5, 40.0, 23.5, 0.0]) {
    const shortest = extremumDay(YEAR, lat, t=>t.daylight, -1, W0, W1);     // min daylight
    const earlySet = extremumDay(YEAR, lat, t=>t.sunset,  -1, W0, W1);      // min sunset clock time
    const lateRise = extremumDay(YEAR, lat, t=>t.sunrise, +1, W0, W1);      // max sunrise clock time
    if (!shortest||!earlySet||!lateRise) { ok(`lat ${lat}: computed`, false); continue; }
    const sLab=dayLabel(YEAR,shortest.day), eLab=dayLabel(YEAR,earlySet.day), lLab=dayLabel(YEAR,lateRise.day);
    console.log(`     ${String(lat).padStart(5)}°N   earliest sunset ${eLab}  ·  shortest day ${sLab}  ·  latest sunrise ${lLab}`);
    if (lat>=10) { // away from the equatorial degenerate band the ordering is strict and visible
      // shortest day must be the solstice: USNO gives 2026 Dec 21 20:50 UT (aa.usno.navy.mil/api/seasons?year=2026)
      ok(`lat ${lat}: shortest day is the solstice (Dec 21)`, sLab === 'Dec 21', sLab);
      ok(`lat ${lat}: earliest sunset is BEFORE the solstice`, earlySet.day < shortest.day, `${eLab} < ${sLab}`);
      ok(`lat ${lat}: latest sunrise is AFTER the solstice`,   lateRise.day > shortest.day, `${lLab} > ${sLab}`);
    } else {
      // at the equator day/night are ~equal all year (no real shortest day), yet
      // the EoT alone still throws earliest sunset weeks off the solstice
      ok(`lat ${lat}: earliest sunset still far from the solstice (EoT alone)`, shortest.day-earlySet.day>20, `${eLab} vs ${sLab}`);
    }
  }
}

sec('The spread shrinks toward the pole, widens toward the equator (the latitude law)');
{
  // gap between earliest sunset and the solstice, in days, vs latitude
  const W0=304, W1=410;
  const spreadAt = (lat)=>{
    const shortest = extremumDay(YEAR, lat, t=>t.daylight, -1, W0, W1);
    const earlySet = extremumDay(YEAR, lat, t=>t.sunset,  -1, W0, W1);
    return shortest.day - earlySet.day;
  };
  const g60=spreadAt(60), g40=spreadAt(40), g20=spreadAt(20);
  console.log(`     sunset-to-solstice gap:  60°N ${g60}d   40°N ${g40}d   20°N ${g20}d`);
  ok('gap at 20°N exceeds gap at 40°N exceeds gap at 60°N', g20>g40 && g40>g60, `${g20}>${g40}>${g60}`);
}

sec('The analemma closes — declination and time-offset span the published ranges');
{
  let dmin=9, dmax=-9, emin=99, emax=-99;
  for (let d=0; d<365; d++) {
    const s = solar(julianDay(YEAR,1,1.5)+d);
    dmin=Math.min(dmin,s.decl); dmax=Math.max(dmax,s.decl);
    emin=Math.min(emin,s.eotAppMin); emax=Math.max(emax,s.eotAppMin);
  }
  ok('declination spans ±ε (≈ ±23.44°)', Math.abs(dmax-23.44)<0.1 && Math.abs(dmin+23.44)<0.1,
     `decl ∈ [${dmin.toFixed(2)}, ${dmax.toFixed(2)}]`);
  ok('time-offset spans ≈ [−14.2, +16.4] min', Math.abs(emax-16.4)<0.4 && Math.abs(emin+14.2)<0.4,
     `E ∈ [${emin.toFixed(2)}, ${emax.toFixed(2)}] min`);
}

function minToMS(m){ const s=Math.round(Math.abs(m)*60); const sign=m<0?'−':'+'; return `${sign}${Math.floor(s/60)}m${String(s%60).padStart(2,'0')}s`; }

console.log('\n'+(fails===0 ? 'ALL CHECKS PASS' : `${fails} CHECK(S) FAILED`));
process.exit(fails===0?0:1);
