#!/usr/bin/env node
// ───────────────────────────────────────────────────────────────────────────
// The Machine Made of Months — verifier
//
// The Antikythera mechanism is a bronze astronomical computer recovered in 1901.
// This file derives reconstructed mean gear ratios from Freeth et al. (2006/2008)
// tooth counts using exact fractions. Day conversions use a supplied year length;
// residuals and continued fractions also use supplied modern astronomical values.
// Surviving gears are distinguished from hypothetical gears, and adopted tooth
// counts can include estimates from partial remains. The browser is a separate
// illustration with mirrored values, not an execution of this verifier.
//
// Run:  node research/antikythera/verify.mjs
// ───────────────────────────────────────────────────────────────────────────

// ── exact rational arithmetic (BigInt) ─────────────────────────────────────
const bgcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; };
class Q {
  constructor(n, d = 1n) {
    n = BigInt(n); d = BigInt(d);
    if (d === 0n) throw new Error('zero denominator');
    if (d < 0n) { n = -n; d = -d; }
    const g = bgcd(n, d) || 1n;
    this.n = n / g; this.d = d / g;
  }
  mul(o) { return new Q(this.n * o.n, this.d * o.d); }
  div(o) { return new Q(this.n * o.d, this.d * o.n); }
  sub(o) { return new Q(this.n * o.d - o.n * this.d, this.d * o.d); }
  num() { return Number(this.n) / Number(this.d); }
  str() { return `${this.n}/${this.d}`; }
  eq(o) { return this.n === o.n && this.d === o.d; }
}
const R = (n, d = 1n) => new Q(n, d);

// ── tooth counts (Freeth et al. 2006 Nature 444:587; 2008 Nature 454:614) ──
// a:true marks a surviving gear; adopted tooth counts can include estimates.
// a:false marks a hypothetical gear in Freeth 2008 Supplementary Figure 14.
// This flag describes survival, not whether every tooth was directly counted.
const T = {
  a1: { t: 48,  a: true,  note: 'input / hand crank' },
  b1: { t: 223, a: true,  note: 'great four-spoked mean-Sun wheel; 1 turn = 1 year' },
  b2: { t: 64,  a: true,  note: 'shares the year axis; root of every train' },
  b3: { t: 32,  a: true },
  c1: { t: 38,  a: true },
  c2: { t: 48,  a: true },
  d1: { t: 24,  a: true },
  d2: { t: 127, a: true,  note: 'the famous one: 127 = 254/2 sidereal months' },
  e1: { t: 32,  a: true },
  e2: { t: 32,  a: true },
  e3: { t: 223, a: true,  note: 'carries the lunar-anomaly epicycle; 223 = Saros months' },
  e4: { t: 188, a: true },
  e5: { t: 50,  a: true },
  e6: { t: 50,  a: true },
  f1: { t: 53,  a: true },
  f2: { t: 30,  a: true },
  g1: { t: 54,  a: true },
  g2: { t: 20,  a: true },
  h1: { t: 60,  a: true },
  h2: { t: 15,  a: true },
  i1: { t: 60,  a: true },
  k1: { t: 50,  a: true,  note: 'pin-and-slot: equal to k2, no mean effect, all anomaly' },
  k2: { t: 50,  a: true },
  l1: { t: 38,  a: true },
  l2: { t: 53,  a: true },
  m1: { t: 96,  a: true },
  m2: { t: 15,  a: true },
  m3: { t: 27,  a: false, note: 'hypothetical (Freeth 2008, Figure 14)' },
  n1: { t: 53,  a: false, note: 'hypothetical (Freeth 2008, Figure 14)' },
  n3: { t: 57,  a: false, note: 'reconstructed (Freeth 2008): drives the Olympiad dial' },
  o1: { t: 60,  a: true,  note: 'Olympiad pointer; "beyond reasonable doubt" 60 teeth' },
};
const tt = (g) => BigInt(T[g].t);

// ── modern astronomical constants (for honest residuals only) ───────────────
const MODERN = {
  sidMonth:  27.321661,   // sidereal month, days
  synMonth:  29.530589,   // synodic  month, days
  tropYear:  365.242190,  // tropical year, days
  saros:     6585.3211,   // 223 synodic months, days
  metonic:   6939.6884,   // 235 synodic months, days
  apsis:     8.850,       // lunar apsidal precession period, years
};
// Supplied conversion scale: the Gregorian mean year, 365 + 97/400 days.
// This is an illustration convention, not a value inferred from the gear teeth.
const MECH_YEAR = 365.2425;

// ── the gear trains, as products of fractions, straight from the teeth ──────
// Each pointer's *period* (years per one revolution) = Time(x) * product of
// (driver teeth / driven teeth) along its chain, with Time(x) = 1 year for b1.
const F = (driver, driven) => R(tt(driver), tt(driven));

const trains = {
  // Moon, mean sidereal motion. period = (c1/b2)(d1/c2)(e2/d2); the pin-and-slot
  // k1/k2 and the e5/e6, b3/e1 stages are 1:1 on average (they carry the anomaly,
  // not the mean rate). Target: exactly 19/254 yr = 1 sidereal month.
  moonSidereal: {
    label: 'Moon — mean sidereal month',
    period: F('c1', 'b2').mul(F('d1', 'c2')).mul(F('e2', 'd2')),
    targetExact: R(19n, 254n),                 // 254 sidereal months per 19 years
    targetDays: MODERN.sidMonth,
    chain: '(c1/b2)·(d1/c2)·(e2/d2)',
  },
  // Metonic pointer: 5 turns of a 5-loop spiral over 19 years = 235 synodic
  // months. period = (l1/b2)(m1/l2)(n1/m2). Target: exactly 19/5 yr/turn.
  metonic: {
    label: 'Metonic pointer (1 turn)',
    period: F('l1', 'b2').mul(F('m1', 'l2')).mul(F('n1', 'm2')),
    targetExact: R(19n, 5n),                   // 5 turns over 19 years
    targetDays: MODERN.metonic / 5,
    chain: '(l1/b2)·(m1/l2)·(n1/m2)',
  },
  // Olympiad / Games dial: the Metonic axis carries n3, meshing o1.
  // rate = (5/19)·(n3/o1) = 1/4 turn per year => exactly 4 years.
  olympiad: {
    label: 'Olympiad (Games) dial',
    period: F('l1', 'b2').mul(F('m1', 'l2')).mul(F('n1', 'm2')).div(F('n3', 'o1')),
    targetExact: R(4n, 1n),                    // 4 years
    targetDays: 4 * MECH_YEAR,
    chain: '(metonic period)·(o1/n3)',
  },
  // Lunar apsidal precession: the carrier of the k1/k2 epicycle (gear e3)
  // turns once per ~8.88 years. period = (l1/b2)(m1/l2)(e3/m3).
  apsis: {
    label: 'Lunar apsidal precession',
    period: F('l1', 'b2').mul(F('m1', 'l2')).mul(F('e3', 'm3')),
    targetExact: null,                         // not an integer relation; design value 8.8826 yr
    designYears: 8.8826,
    targetDays: MODERN.apsis * MECH_YEAR,
    chain: '(l1/b2)·(m1/l2)·(e3/m3)',
  },
  // Saros eclipse dial: 4 turns of its spiral over 223 synodic months.
  // period = (apsis period)·(f1/e4)·(g1/f2).
  saros: {
    label: 'Saros dial (1 turn)',
    period: F('l1', 'b2').mul(F('m1', 'l2')).mul(F('e3', 'm3'))
              .mul(F('f1', 'e4')).mul(F('g1', 'f2')),
    targetDays: MODERN.saros / 4,              // 223 synodic months / 4 turns
    chain: '(apsis period)·(f1/e4)·(g1/f2)',
  },
  // Exeligmos dial: 3 Saros cycles (the time for eclipses to recur near the
  // same hour). period = (Saros turn period)·(h1/g2)·(i1/h2) = 12 × Saros turn.
  exeligmos: {
    label: 'Exeligmos dial',
    period: F('l1', 'b2').mul(F('m1', 'l2')).mul(F('e3', 'm3'))
              .mul(F('f1', 'e4')).mul(F('g1', 'f2'))
              .mul(F('h1', 'g2')).mul(F('i1', 'h2')),
    targetDays: 3 * MODERN.saros,              // 669 synodic months
    chain: '(Saros turn)·(h1/g2)·(i1/h2)',
  },
};

// ── continued-fraction convergents of the year : synodic-month ratio ────────
// The deep "why these counts": you cannot tile a year with whole months — the
// ratio is irrational-for-all-practical-purposes. The best whole-number calendar
// cycles are exactly the continued-fraction convergents of that ratio, and the
// machine's Metonic gear (235 months : 19 years) is one of them, cut in bronze.
function cfConvergents(x, n) {
  const a = [], conv = [];
  let v = x;
  let h0 = 0n, h1 = 1n, k0 = 1n, k1 = 0n;
  for (let i = 0; i < n; i++) {
    const ai = Math.floor(v + 1e-9);
    const A = BigInt(ai);
    a.push(ai);
    const h = A * h1 + h0, k = A * k1 + k0;
    conv.push([h, k]);
    h0 = h1; h1 = h; k0 = k1; k1 = k;
    const frac = v - ai;
    if (frac < 1e-9) break;
    v = 1 / frac;
  }
  return { a, conv };
}

// ───────────────────────────────────────────────────────────────────────────
// run the checks
// ───────────────────────────────────────────────────────────────────────────
let pass = 0, fail = 0;
const out = [];
function check(name, cond, detail = '') {
  (cond ? pass++ : fail++);
  out.push(`  ${cond ? '✓' : '✗ FAIL'}  ${name}${detail ? ' — ' + detail : ''}`);
  if (!cond) process.exitCode = 1;
}

console.log('\n═══ THE MACHINE MADE OF MONTHS — gear trains re-derived from the teeth ═══\n');

// 1. the famous moon train is an EXACT astronomical fraction
{
  const t = trains.moonSidereal;
  check('Moon train = 19/254 yr/orbit exactly (254 sidereal months / 19 yr)',
        t.period.eq(t.targetExact), `${t.chain} = ${t.period.str()}`);
  const days = t.period.num() * MECH_YEAR;
  out.push(`         → ${days.toFixed(5)} d  (modern sidereal month ${MODERN.sidMonth} d;` +
           ` residual ${((days - MODERN.sidMonth) / MODERN.sidMonth * 1e6).toFixed(0)} ppm)`);
  // the 127 gear is half of 254
  check('d2 = 127 is exactly half of 254 sidereal months', tt('d2') * 2n === 254n);
}

// 2. Metonic = exactly 19/5 yr per turn; 5 turns = 19 yr = 235 synodic months
{
  const t = trains.metonic;
  check('Metonic pointer = 19/5 yr/turn exactly (5 turns over 19 years)',
        t.period.eq(t.targetExact), `${t.chain} = ${t.period.str()}`);
  // 5 turns spans 19 tropical years; the dial has 235 month-cells
  check('5 Metonic turns = 19 years', t.period.num() * 5 === 19);
  const days = t.period.num() * 5 * MECH_YEAR;
  out.push(`         → 5-turn span ${days.toFixed(1)} d  (235 synodic months = ${MODERN.metonic} d)`);
}

// 3. Olympiad dial = exactly 4 years
{
  const t = trains.olympiad;
  check('Olympiad dial = 4 years exactly  (5/19)·(57/60) = 1/4 turn/yr',
        t.period.eq(t.targetExact), `= ${t.period.str()} yr/turn`);
}

// 4. lunar apsidal precession ≈ 8.8826 yr (the machine's design value)
{
  const t = trains.apsis;
  const yr = t.period.num();
  check('Lunar precession ≈ 8.8826 yr (Freeth design value)',
        Math.abs(yr - t.designYears) < 5e-4, `${t.chain} = ${t.period.str()} = ${yr.toFixed(4)} yr`);
  out.push(`         → ${yr.toFixed(4)} yr  (modern apsidal period ${MODERN.apsis} yr; ` +
           `the machine's own approximation, off by ${((yr - MODERN.apsis) / MODERN.apsis * 100).toFixed(2)}%)`);
}

// 5. Saros dial: 4 turns ≈ 223 synodic months
{
  const t = trains.saros;
  const turnDays = t.period.num() * MECH_YEAR;
  const fourTurns = 4 * turnDays;
  check('Saros dial: 4 turns land on 223 synodic months (±0.1 d)',
        Math.abs(fourTurns - MODERN.saros) < 0.12,
        `4×${turnDays.toFixed(2)} d = ${fourTurns.toFixed(2)} d vs ${MODERN.saros} d`);
}

// 6. Exeligmos = exactly 3 Saros (the ×12 stage)
{
  const t = trains.exeligmos;
  const ratio = t.period.div(trains.saros.period);   // exeligmos turn / saros turn
  check('Exeligmos = exactly 3 Saros cycles (gear stage = ×12)',
        ratio.eq(R(12n, 1n)), `ratio = ${ratio.str()}`);
  const days = t.period.num() * MECH_YEAR;
  out.push(`         → ${days.toFixed(0)} d  (3 × 223 = 669 synodic months = ${(3 * MODERN.saros).toFixed(0)} d)`);
}

// 7. the synodic month falls out of the Sun/Moon differential, not a gear of
//    its own: 254 sidereal − 19 solar laps = 235 synodic in 19 years.
{
  const synTurnsPerYear = (254 - 19) / 19;
  const days = (1 / synTurnsPerYear) * MECH_YEAR;
  check('Synodic month = differential of Moon and Sun pointers (235 / 19 yr)',
        Math.abs(days - MODERN.synMonth) < 0.001,
        `${days.toFixed(4)} d vs modern ${MODERN.synMonth} d`);
  check('254 sidereal − 235 synodic = 19  (the count of years in the cycle)',
        254 - 235 === 19);
}

// 8. The adopted lunar-prediction scheme (Freeth 2008 supplement, section 4.3).
//    33 six-month and 5 five-month gaps describe 38 lunar possibilities.
//    Figure 20's combined solar/lunar reconstruction has 51 glyphs. The equation
//    alone does not select 33/5; even spacing does not supply that missing constraint.
{
  const a = 33, b = 5;
  const solutions = [];
  for (let six = 0; six * 6 <= 223; six++) {
    const rest = 223 - six * 6;
    if (rest % 5 === 0) solutions.push([six, rest / 5]);
  }
  check('Adopted lunar scheme: 33 six-month + 5 five-month gaps, 38 possibilities',
        6 * a + 5 * b === 223 && a + b === 38);
  check('6a + 5b = 223 admits seven nonnegative integer solutions; 33/5 is one',
        solutions.length === 7 && solutions.some(([six, five]) => six === a && five === b),
        solutions.map(([six, five]) => `(${six},${five})`).join(', '));
}

// 9. the Metonic cycle is a continued-fraction convergent of year : month
{
  const ratio = MODERN.tropYear / MODERN.synMonth;   // months per year ≈ 12.368
  const { conv } = cfConvergents(ratio, 12);
  const has235over19 = conv.some(([h, k]) => h === 235n && k === 19n);
  check('235 months / 19 years is a continued-fraction convergent of year:month',
        has235over19, `convergents include ${conv.slice(0, 7).map(([h, k]) => `${h}/${k}`).join(', ')}`);
}

// 10. internal consistency: every adopted tooth count is a positive integer
{
  const allInt = Object.values(T).every(g => Number.isInteger(g.t) && g.t > 0);
  check('all tooth counts are positive integers', allInt);
  const nAttested = Object.values(T).filter(g => g.a).length;
  const nRecon = Object.values(T).filter(g => !g.a).length;
  out.push(`         → ${nAttested} surviving gears, ${nRecon} hypothetical (of ${Object.keys(T).length} listed)`);
}

console.log(out.join('\n'));
console.log(`\n${'─'.repeat(70)}`);
console.log(`  ${pass} checks passed, ${fail} failed.`);
console.log(`${'─'.repeat(70)}\n`);
if (fail === 0) console.log('All green: reconstructed mean gear ratios and stated arithmetic checked with supplied reference values.\n');

// Machine-readable export for offline consumers; the browser does not import it.
export const ANTIKYTHERA = { T, MODERN, MECH_YEAR, trains, cfConvergents };
