// verify.mjs — the check behind "Why Clocks Go Clockwise".
//
// The one *physical* claim the page rests on: a horizontal sundial's shadow
// sweeps CLOCKWISE in the northern hemisphere and COUNTER-CLOCKWISE in the
// southern hemisphere — and, in the tropics, it can do EITHER depending on the
// season. None of that is asserted by hand here; it is computed from a standard
// solar-position model and the model is itself checked against facts that have
// nothing to do with clocks (equinox sun rises due east, noon altitude = 90−|φ|
// at an equinox, declination never leaves ±23.44°, …).
//
// The deeper, exact invariant the page leans on:
//   the shadow sweeps clockwise  ⇔  the sun crosses the meridian to your SOUTH
//                                ⇔  your latitude φ is greater than the sun's
//                                   declination δ on that day.
// Mid-latitudes (|φ| ≥ 23.44°) are therefore locked to one sense all year;
// only the tropics can flip. We verify that the *measured* daily rotation sense
// (from tracking the sun's azimuth minute by minute) agrees with the φ vs δ rule
// across a grid of latitudes and dates.
//
//   node research/why-clocks-go-clockwise/verify.mjs

const D2R = Math.PI / 180, R2D = 180 / Math.PI;
const norm360 = (d) => ((d % 360) + 360) % 360;

// --- solar position (NOAA / Spencer Fourier series) -------------------------
// Inputs: day-of-year n (1..365), apparent solar time h in hours (12 = solar
// noon), latitude φ in degrees. Returns altitude & azimuth (deg, clockwise from
// true north: 0=N, 90=E, 180=S, 270=W).
function solarDeclination(n) {
  // Spencer (1971), accurate to ~0.0006 rad. γ = fractional year angle.
  const g = (2 * Math.PI / 365) * (n - 1);
  return (0.006918
    - 0.399912 * Math.cos(g) + 0.070257 * Math.sin(g)
    - 0.006758 * Math.cos(2 * g) + 0.000907 * Math.sin(2 * g)
    - 0.002697 * Math.cos(3 * g) + 0.001480 * Math.sin(3 * g)); // radians
}
function sunPosition(n, h, latDeg) {
  const phi = latDeg * D2R;
  const decl = solarDeclination(n);
  const H = (h - 12) * 15 * D2R;             // hour angle: 0 at solar noon, + in afternoon
  const sinA = Math.sin(phi) * Math.sin(decl) + Math.cos(phi) * Math.cos(decl) * Math.cos(H);
  const alt = Math.asin(Math.max(-1, Math.min(1, sinA)));
  // azimuth clockwise from north
  const sinAz = -Math.cos(decl) * Math.sin(H) / Math.cos(alt);
  const cosAz = (Math.sin(decl) - Math.sin(phi) * sinA) / (Math.cos(phi) * Math.cos(alt) + 1e-12);
  let az = Math.atan2(sinAz, cosAz) * R2D;
  return { altDeg: alt * R2D, azDeg: norm360(az), declDeg: decl * R2D };
}
// A vertical gnomon's shadow points opposite the sun.
const shadowAzimuth = (sunAz) => norm360(sunAz + 180);

// --- measured daily rotation sense ------------------------------------------
// Walk solar time from sunrise to sunset; unwrap the sun's azimuth so it is
// continuous, and report the net change. >0 ⇒ azimuth increased ⇒ the shadow
// (and the sun) swept clockwise; <0 ⇒ counter-clockwise. Also report whether the
// sweep was monotone (no reversal during the day).
function dailySense(n, latDeg) {
  let prev = null, unwrapped = null, start = null, net = 0;
  let monoUp = true, monoDown = true, samples = 0;
  for (let h = 0; h <= 24; h += 1 / 60) {        // one-minute steps
    const p = sunPosition(n, h, latDeg);
    if (p.altDeg <= 0.0) { prev = null; continue; } // only count daylight
    if (prev === null) { unwrapped = p.azDeg; start = p.azDeg; prev = p.azDeg; continue; }
    let d = p.azDeg - prev;
    if (d > 180) d -= 360; else if (d < -180) d += 360; // unwrap step
    unwrapped += d; net += d;
    if (d < -1e-9) monoUp = false;
    if (d > 1e-9) monoDown = false;
    prev = p.azDeg; samples++;
  }
  return { net, monotone: (monoUp || monoDown), daylight: samples > 0 };
}

// =================== the checks ====================
let pass = 0, fail = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function ok(name, cond, extra = '') {
  if (cond) { pass++; console.log(`  ok   ${name}${extra ? '   ' + extra : ''}`); }
  else { fail++; console.log(`FAIL   ${name}${extra ? '   ' + extra : ''}`); }
}

console.log('\n— solar model sanity (nothing to do with clocks) —');
// Declination never escapes the obliquity of the ecliptic.
let dmin = 99, dmax = -99;
for (let n = 1; n <= 365; n++) { const d = solarDeclination(n) * R2D; dmin = Math.min(dmin, d); dmax = Math.max(dmax, d); }
ok('declination stays within ±23.44° (obliquity)', dmin > -23.6 && dmax < 23.6, `range [${dmin.toFixed(2)}, ${dmax.toFixed(2)}]`);
ok('declination ≈ 0 at the March equinox (day 80)', approx(solarDeclination(80) * R2D, 0, 0.6), `δ=${(solarDeclination(80) * R2D).toFixed(2)}°`);
ok('declination near +23.4° at June solstice (day 172)', approx(solarDeclination(172) * R2D, 23.44, 0.4), `δ=${(solarDeclination(172) * R2D).toFixed(2)}°`);
ok('declination near −23.4° at Dec solstice (day 355)', approx(solarDeclination(355) * R2D, -23.44, 0.4), `δ=${(solarDeclination(355) * R2D).toFixed(2)}°`);

// At an equinox the sun rises due east and sets due west, everywhere.
{
  const rise = sunPosition(80, 6.0, 51.5);   // London, equinox ~sunrise
  const set = sunPosition(80, 18.0, 51.5);   // ~sunset
  ok('equinox sunrise is due east (az≈90°)', approx(rise.azDeg, 90, 1.0), `az=${rise.azDeg.toFixed(2)}°`);
  ok('equinox sunset is due west (az≈270°)', approx(set.azDeg, 270, 1.0), `az=${set.azDeg.toFixed(2)}°`);
}
// Noon altitude at an equinox equals 90 − |latitude|.
for (const lat of [0, 23.44, 51.5, -33.9]) {
  const noon = sunPosition(80, 12, lat);
  ok(`equinox noon altitude = 90−|φ| at φ=${lat}°`, approx(noon.altDeg, 90 - Math.abs(lat), 0.7), `alt=${noon.altDeg.toFixed(2)}° vs ${(90 - Math.abs(lat)).toFixed(2)}°`);
}

console.log('\n— the shadow is exactly opposite the sun —');
{
  const p = sunPosition(172, 9, 40);
  ok('shadow azimuth = sun azimuth + 180°', approx(norm360(shadowAzimuth(p.azDeg) - p.azDeg), 180, 1e-9), `Δ=${norm360(shadowAzimuth(p.azDeg) - p.azDeg).toFixed(3)}°`);
}

console.log('\n— the core claim: rotation sense matches the φ-vs-δ rule —');
// For a dense grid of latitude × day, the *measured* daily rotation sense must
// agree with the sign of (φ − δ): φ>δ ⇒ sun culminates south ⇒ clockwise (net>0).
let agree = 0, total = 0;
let monoOutside = 0, totalOutside = 0;       // outside the tropics
let nonMonoAllTropical = true;               // every reversal must be tropical
for (let lat = -80; lat <= 80; lat += 5) {
  for (let n = 10; n <= 360; n += 20) {
    const decl = solarDeclination(n) * R2D;
    if (Math.abs(lat - decl) < 1.2) continue;       // skip the overhead-sun degeneracy
    const s = dailySense(n, lat);
    if (!s.daylight) continue;                       // skip polar night
    total++;
    const predictCW = lat > decl;                    // φ>δ ⇒ clockwise
    const measuredCW = s.net > 0;
    if (predictCW === measuredCW) agree++;
    if (Math.abs(lat) >= 23.44) { totalOutside++; if (s.monotone) monoOutside++; }
    if (!s.monotone && Math.abs(lat) >= 23.44) nonMonoAllTropical = false;
  }
}
ok('measured rotation sense matches φ>δ ⇒ clockwise everywhere on the grid', agree === total, `${agree}/${total} samples`);
ok('outside the tropics (|φ|≥23.44°) the daily sweep is always monotone', monoOutside === totalOutside, `${monoOutside}/${totalOutside} monotone`);
ok('every mid-day reversal occurs only inside the tropics (sun near overhead)', nonMonoAllTropical);

console.log('\n— mid-latitudes are locked to one sense all year —');
{
  // London (51.5°N): clockwise on every day of the year, both solstices.
  let alwaysCW = true;
  for (let n = 1; n <= 365; n += 7) { const s = dailySense(n, 51.5); if (s.daylight && s.net <= 0) alwaysCW = false; }
  ok('51.5°N (London): shadow clockwise every day of the year', alwaysCW);
  // Sydney (33.9°S): counter-clockwise on every day of the year.
  let alwaysCCW = true;
  for (let n = 1; n <= 365; n += 7) { const s = dailySense(n, -33.9); if (s.daylight && s.net >= 0) alwaysCCW = false; }
  ok('33.9°S (Sydney): shadow counter-clockwise every day of the year', alwaysCCW);
}

console.log('\n— the tropics flip with the season (the honest exception) —');
{
  // 10°N: in northern winter δ<10 ⇒ clockwise; in deep northern summer δ>10 ⇒ counter-clockwise.
  const winter = dailySense(355, 10);   // Dec solstice, δ≈−23
  const summer = dailySense(172, 10);   // Jun solstice, δ≈+23 > 10
  ok('10°N in December: clockwise (sun to the south, δ≈−23° < 10°)', winter.net > 0, `net=${winter.net.toFixed(1)}°`);
  ok('10°N in June: counter-clockwise (sun to the north, δ≈+23° > 10°)', summer.net < 0, `net=${summer.net.toFixed(1)}°`);
  // There must exist a crossover day where the noon sun is overhead and the sense turns over.
  let flips = 0, prevCW = null;
  for (let n = 1; n <= 365; n++) {
    const s = dailySense(n, 10); if (!s.daylight) continue;
    const cw = s.net > 0;
    if (prevCW !== null && cw !== prevCW) flips++;
    prevCW = cw;
  }
  ok('10°N reverses sense exactly twice a year (sun overhead twice)', flips === 2, `${flips} reversals`);
}

console.log('\n— an equatorial-mounted dial moves uniformly at 15°/hour —');
{
  // On a dial face parallel to the equatorial plane the shadow's hour angle IS
  // the sun's hour angle, advancing a uniform 15° per hour — the geometric root
  // of "an hour is a fixed angle on the face". (Hour angle, not horizontal-dial
  // azimuth, which is non-uniform.) Verify the rate is constant.
  let okRate = true;
  for (let h = 9; h <= 15; h++) {
    const ha = (h - 12) * 15;            // hour angle in degrees
    const haNext = (h + 1 - 12) * 15;
    if (!approx(haNext - ha, 15, 1e-9)) okRate = false;
  }
  ok('equatorial dial: 15° of shadow per hour, exactly', okRate);
}

console.log(`\n${fail === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${pass} passed, ${fail} failed.\n`);
process.exit(fail === 0 ? 0 : 1);
