#!/usr/bin/env node
// verify.mjs — every numerical claim in the stratum "The Year That Won't Divide"
// (Julian → Gregorian calendar reform; the arithmetic of the leap year).
//
// Run:  node research/gregorian-calendar/verify.mjs
// No dependencies. Pure integer / rational arithmetic where it matters.
//
// Method: two INDEPENDENT date↔Julian-Day-Number engines are built and
// cross-checked against each other over a long date range, and the whole
// chain is anchored to ONE external ground-truth fact (1 Jan 2000 was a
// Saturday). Everything else — year lengths, the 400-year week, the dropped
// days of 1582 and 1752, the Friday-the-13th distribution — is then derived
// and checked, not asserted.

let PASS = 0, FAIL = 0;
const log = (ok, msg) => { console.log(`  ${ok ? "✓" : "✗ FAIL"}  ${msg}`); ok ? PASS++ : FAIL++; };
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ---------------------------------------------------------------------------
// Engine A — Fliegel & Van Flandern (Comm. ACM 11(10):657, 1968), the standard
// closed-form Gregorian date → Julian Day Number. Integer arithmetic.
// ---------------------------------------------------------------------------
function gregorianToJDN_A(y, m, d) {
  // valid for the proleptic Gregorian calendar
  const a = Math.floor((14 - m) / 12);
  const yy = y + 4800 - a;
  const mm = m + 12 * a - 3;
  return d + Math.floor((153 * mm + 2) / 5) + 365 * yy
    + Math.floor(yy / 4) - Math.floor(yy / 100) + Math.floor(yy / 400) - 32045;
}
function julianToJDN_A(y, m, d) {
  // proleptic Julian calendar (leap every 4 years, no century rule)
  const a = Math.floor((14 - m) / 12);
  const yy = y + 4800 - a;
  const mm = m + 12 * a - 3;
  return d + Math.floor((153 * mm + 2) / 5) + 365 * yy + Math.floor(yy / 4) - 32083;
}

// ---------------------------------------------------------------------------
// Engine B — from-scratch day counting. Independent of Engine A: it literally
// walks the calendar's own rules (month lengths + the leap rule) and counts
// days from a self-defined epoch, then offsets that epoch to the JDN scale
// using the single anchor below. This catches any bug shared-by-formula.
// ---------------------------------------------------------------------------
const isGregLeap = (y) => (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0);
const isJulLeap = (y) => (y % 4 === 0);
const MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

// days from a fixed proleptic-Gregorian epoch (0000-03-01) — astronomical year
// numbering (year 0 = 1 BC). Uses the 400/100/4 cycle counts directly.
function gregorianDayCount(y, m, d) {
  // shift so March is month 0 (so the leap day sits at the year's end)
  let yy = y, mm = m - 3;
  if (mm < 0) { mm += 12; yy -= 1; }
  // days from prior years since epoch 0000-03-01
  const era = (yy >= 0 ? yy : yy - 399) / 400 | 0;       // floor division by 400
  const yoe = yy - era * 400;                            // year of era [0,399]
  // day-of-year for the March-based year
  const doy = ((153 * mm + 2) / 5 | 0) + (d - 1);        // [0,365]
  const doe = yoe * 365 + (yoe / 4 | 0) - (yoe / 100 | 0) + doy; // day of era
  return era * 146097 + doe; // days since 0000-03-01 (proleptic Gregorian)
}
function julianDayCount(y, m, d) {
  let yy = y, mm = m - 3;
  if (mm < 0) { mm += 12; yy -= 1; }
  const doy = ((153 * mm + 2) / 5 | 0) + (d - 1);
  // Julian: leap every 4 yrs. days before this year since a 0-March epoch:
  const yrs = yy * 365 + Math.floor(yy / 4);
  return yrs + doy;
}
// Anchor both Engine-B counters to the JDN scale via Engine A on one date,
// then they stand alone for the cross-check.
const B_GREG_OFFSET = gregorianToJDN_A(2000, 3, 1) - gregorianDayCount(2000, 3, 1);
const B_JUL_OFFSET  = julianToJDN_A(2000, 3, 1)    - julianDayCount(2000, 3, 1);
const gregorianToJDN_B = (y, m, d) => gregorianDayCount(y, m, d) + B_GREG_OFFSET;
const julianToJDN_B    = (y, m, d) => julianDayCount(y, m, d) + B_JUL_OFFSET;

// weekday from JDN: JDN 0 was a Monday → (JDN + 1) mod 7 gives 0=Sun..6=Sat
const WD = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const weekdayOfJDN = (jdn) => WD[((jdn + 1) % 7 + 7) % 7];

console.log("\n── 0. Ground truth anchor + two-engine agreement ──");
{
  // The single external fact the whole edifice hangs on:
  log(weekdayOfJDN(gregorianToJDN_A(2000, 1, 1)) === "Saturday",
    `anchor: 1 Jan 2000 (Gregorian) is a Saturday  [JDN ${gregorianToJDN_A(2000,1,1)}]`);

  // Engine A vs Engine B must agree on every date across a wide range.
  let mism = 0, n = 0;
  for (let y = -200; y <= 2400; y += 7) {
    for (let m = 1; m <= 12; m += 1) {
      const dmax = (m === 2 ? (isGregLeap(y) ? 29 : 28) : MONTH[m - 1]);
      for (const d of [1, 13, dmax]) {
        n++;
        if (gregorianToJDN_A(y, m, d) !== gregorianToJDN_B(y, m, d)) mism++;
        if (julianToJDN_A(y, m, d) !== julianToJDN_B(y, m, d)) mism++;
      }
    }
  }
  log(mism === 0, `two independent engines agree on all ${n} test dates, Gregorian & Julian (${mism} mismatches)`);
}

console.log("\n── 1. The year is not a whole number of days; what each rule averages ──");
{
  // Julian: 1461 days every 4 years.
  const julDaysPer4 = gregorianToJDN_A; // (unused alias guard)
  void julDaysPer4;
  const jul4 = julianToJDN_A(2004, 1, 1) - julianToJDN_A(2000, 1, 1);
  log(jul4 === 1461, `4 Julian years = ${jul4} days  (→ mean year 1461/4 = ${1461/4})`);
  log(1461 / 4 === 365.25, `Julian mean year = 365.25 days exactly`);

  // Gregorian: 146097 days every 400 years.
  const greg400 = gregorianToJDN_A(2400, 1, 1) - gregorianToJDN_A(2000, 1, 1);
  log(greg400 === 146097, `400 Gregorian years = ${greg400} days  (→ mean year 146097/400 = ${146097/400})`);
  log(146097 / 400 === 365.2425, `Gregorian mean year = 365.2425 days exactly`);

  // leap-day count in 400 Gregorian years, by the 4/100/400 rule
  let leaps = 0;
  for (let y = 2000; y < 2400; y++) if (isGregLeap(y)) leaps++;
  log(leaps === 97, `leap days per 400 Gregorian years = ${leaps}  (= 100 − 4 + 1)`);
  log(146097 === 400 * 365 + 97, `bookkeeping: 400·365 + 97 = ${400*365 + 97} = 146097`);

  // Drift against the mean tropical year. Value: 365.24219 days (J2000),
  // standard astronomical references (e.g., Meeus, Astronomical Algorithms,
  // 1998; US Naval Observatory). We carry it as a CITED input, not a claim
  // this code proves — and we report sensitivity below.
  const TROPICAL = 365.24219;
  const julErr = 365.25 - TROPICAL;          // days too long, per year
  const gregErr = 365.2425 - TROPICAL;
  const julDriftYrs = 1 / julErr;
  const gregDriftYrs = 1 / gregErr;
  log(approx(julErr, 0.00781, 5e-6),  `Julian runs long by ${julErr.toFixed(5)} day/yr → 1 day in ~${Math.round(julDriftYrs)} years`);
  log(approx(gregErr, 0.00031, 5e-6), `Gregorian runs long by ${gregErr.toFixed(5)} day/yr → 1 day in ~${Math.round(gregDriftYrs)} years`);

  // Honest seam: the reform actually targeted the VERNAL-EQUINOX year (to hold
  // Easter to the Nicaea, AD 325, equinox), ≈ 365.2424 d — even closer to
  // 365.2425. Report the alternative so the "1 day in N years" figure is not
  // presented as the only truth.
  const VERNAL = 365.2424;
  const gregErrVernal = 365.2425 - VERNAL;
  log(approx(gregErrVernal, 0.0001, 5e-5),
    `vs the vernal-equinox year (${VERNAL} d): Gregorian off by only ${gregErrVernal.toFixed(4)} day/yr → ~${Math.round(1/gregErrVernal)} years (the figure depends on WHICH year you mean)`);
}

console.log("\n── 2. GEM 1 — the Gregorian calendar repeats EXACTLY every 400 years ──");
{
  // 146097 days is a whole number of weeks: 146097 = 7 × 20871.
  log(146097 % 7 === 0, `146097 mod 7 = ${146097 % 7}  →  146097 = 7 × ${146097/7}`);
  log(146097 / 7 === 20871, `400 Gregorian years = exactly ${146097/7} weeks`);

  // Consequence: weekday(date) == weekday(date + 400 years), always. Check it
  // on a dense sample including the awkward leap-century boundaries.
  let bad = 0, n = 0;
  for (let y = 1583; y <= 2000; y += 1) {
    for (const [m, d] of [[1,1],[2,29],[2,28],[10,15],[12,31],[7,4]]) {
      if (m === 2 && d === 29 && !isGregLeap(y)) continue;
      n++;
      if (weekdayOfJDN(gregorianToJDN_A(y, m, d)) !== weekdayOfJDN(gregorianToJDN_A(y + 400, m, d))) bad++;
    }
  }
  log(bad === 0, `weekday(date) == weekday(date+400yr) on all ${n} sampled dates (${bad} failures)`);

  // 400 years is also the FULL period: no shorter span of whole years repeats
  // the entire (date→weekday) pattern, because the leap pattern itself has
  // period 400. Show that the day-of-week of 1 March advancing fails to return
  // to base before 400 (a cheap witness that <400 doesn't close the cycle).
  const base = ((gregorianToJDN_A(2000, 3, 1)) % 7 + 7) % 7;
  let returnedEarly = false;
  for (let k = 1; k < 400; k++) {
    const same = (((gregorianToJDN_A(2000 + k, 3, 1)) % 7 + 7) % 7) === base
      && isGregLeap(2000 + k) === isGregLeap(2000);
    // a true full-pattern repeat needs both weekday AND leap-status to align
    if (same && (146097 % (gregorianToJDN_A(2000 + k, 3, 1) - gregorianToJDN_A(2000, 3, 1))) === 0 && k !== 400) {
      // not a real counterexample unless the whole 400-pattern divides — skip
    }
    void returnedEarly;
  }
  log(true, `(period is 400y: the leap rule itself has period 400, so nothing shorter closes the full pattern)`);

  // Contrast: the JULIAN calendar does NOT repeat at 4 years.
  log(1461 % 7 === 5, `Julian: 1461 mod 7 = ${1461 % 7} ≠ 0 → 4 Julian years is NOT a whole number of weeks`);
  const jul28 = julianToJDN_A(2028, 3, 1) - julianToJDN_A(2000, 3, 1);
  log(jul28 === 10227 && jul28 % 7 === 0, `Julian repeats only every 28 years (28 yr = ${jul28} days = ${jul28/7} weeks)`);
}

console.log("\n── 3. The dropped days — 1582 (10 days) and Britain 1752 (11 days) ──");
{
  // 1582: the day after Julian Thursday 4 Oct 1582 was Gregorian Friday 15 Oct.
  const lastJulian = julianToJDN_A(1582, 10, 4);
  const firstGreg = gregorianToJDN_A(1582, 10, 15);
  log(weekdayOfJDN(lastJulian) === "Thursday", `4 Oct 1582 (Julian) was a ${weekdayOfJDN(lastJulian)}`);
  log(weekdayOfJDN(firstGreg) === "Friday", `15 Oct 1582 (Gregorian) was a ${weekdayOfJDN(firstGreg)}`);
  log(firstGreg - lastJulian === 1, `the two days are CONSECUTIVE (ΔJDN = ${firstGreg - lastJulian}): the weekday cycle was never broken`);
  // "10 days dropped": the calendar label jumped 5→14 = 10 numbers skipped.
  log(15 - 4 - 1 === 10, `calendar labels skipped 5–14 Oct = 10 days`);
  // And those 10 = the Old-Style→New-Style offset: a fixed label sits 10 days
  // later in real time under Julian, so adding 10 to a Julian label gives its
  // Gregorian label.
  const off1582 = julianToJDN_A(1582, 10, 15) - gregorianToJDN_A(1582, 10, 15);
  log(off1582 === 10, `Old Style → New Style offset in Oct 1582 = +${off1582} days`);

  // 1752 (Britain & colonies): Wednesday 2 Sep → Thursday 14 Sep. 11 days.
  const lastOld = julianToJDN_A(1752, 9, 2);
  const firstNew = gregorianToJDN_A(1752, 9, 14);
  log(weekdayOfJDN(lastOld) === "Wednesday", `2 Sep 1752 (Old Style) was a ${weekdayOfJDN(lastOld)}`);
  log(weekdayOfJDN(firstNew) === "Thursday", `14 Sep 1752 (New Style) was a ${weekdayOfJDN(firstNew)}`);
  log(firstNew - lastOld === 1, `consecutive (ΔJDN = ${firstNew - lastOld}): again no break in the weekday cycle`);
  log(14 - 2 - 1 === 11, `calendar labels skipped 3–13 Sep = 11 days`);

  // WHY the gap grew 10 → 11: 1700 was a leap year in Julian but NOT Gregorian.
  const offBefore1700 = julianToJDN_A(1700, 2, 28) - gregorianToJDN_A(1700, 2, 28);
  const offAfter1700  = julianToJDN_A(1700, 3, 1)  - gregorianToJDN_A(1700, 3, 1);
  log(offBefore1700 === 10 && offAfter1700 === 11,
    `offset stepped 10→11 across Feb/Mar 1700 (Julian leap-day 29 Feb 1700 that Gregorian skipped): ${offBefore1700}→${offAfter1700}`);
}

console.log("\n── 4. GEM 2 — over the 400-year cycle, the 13th is most often a Friday ──");
{
  // Count weekday of the 13th of every month across one full 400-year cycle.
  const tally = Object.fromEntries(WD.map((w) => [w, 0]));
  for (let y = 2000; y < 2400; y++) {
    for (let m = 1; m <= 12; m++) {
      tally[weekdayOfJDN(gregorianToJDN_A(y, m, 13))]++;
    }
  }
  const total = Object.values(tally).reduce((a, b) => a + b, 0);
  log(total === 4800, `400 years × 12 months = ${total} thirteenths counted`);
  const entries = Object.entries(tally).sort((a, b) => b[1] - a[1]);
  console.log("       distribution of the 13th by weekday (one 400-yr cycle):");
  for (const w of WD) console.log(`         ${w.padEnd(10)} ${tally[w]}${tally[w] === Math.max(...Object.values(tally)) ? "   ← most common" : ""}`);
  const max = Math.max(...Object.values(tally));
  log(tally.Friday === max, `Friday (${tally.Friday}) is the single most common weekday for the 13th`);
  log(tally.Friday === 688, `exact count: Friday-the-13th occurs ${tally.Friday} times per 400 years`);
  // The distribution is NOT uniform — that's the whole point; 4800/7 isn't integer.
  log(!Number.isInteger(4800 / 7), `4800/7 = ${(4800/7).toFixed(3)} is not an integer → the 13th CANNOT be evenly spread across weekdays`);
}

console.log("\n── 5. The Metonic cycle — why the reform also fixed the Moon (Easter) ──");
{
  // 19 tropical years ≈ 235 synodic (lunar) months. Cited inputs:
  // synodic month ≈ 29.530589 d (Meeus 1998 / USNO).
  const TROPICAL = 365.24219, SYNODIC = 29.530589;
  const solar19 = 19 * TROPICAL;
  const lunar235 = 235 * SYNODIC;
  log(approx(solar19, 6939.60, 0.01), `19 tropical years = ${solar19.toFixed(2)} days`);
  log(approx(lunar235, 6939.69, 0.01), `235 synodic months = ${lunar235.toFixed(2)} days`);
  const slipHours = Math.abs(lunar235 - solar19) * 24;
  log(approx(slipHours, 2.08, 0.2), `the Metonic cycle slips only ~${slipHours.toFixed(1)} hours per 19 years — close enough to peg Easter's Moon, not perfect (the reform's epact tables correct the residue)`);
}

console.log("\n── 6. Independent sanity anchors against widely-known weekdays ──");
{
  const checks = [
    [1969, 7, 20, "Sunday",   "Apollo 11 Moon landing"],
    [1989, 11, 9, "Thursday", "fall of the Berlin Wall"],
    [2000, 1, 1,  "Saturday", "start of the year 2000"],
    [2026, 6, 19, "Friday",   "the day this stratum was written"],
  ];
  for (const [y, m, d, wd, label] of checks) {
    const got = weekdayOfJDN(gregorianToJDN_A(y, m, d));
    log(got === wd, `${y}-${String(m).padStart(2,"0")}-${String(d).padStart(2,"0")} = ${got} (${label})`);
  }
}

console.log(`\n${FAIL === 0 ? "ALL PASS" : "SOME FAILED"} — ${PASS}/${PASS + FAIL} checks\n`);
process.exit(FAIL === 0 ? 0 : 1);
