/* ============================================================================
 * verify.mjs — offline check for "The Star That Won't Stay North"
 *
 * Loads the same model the page ships and checks selected numeric outputs:
 * six anchored pole-star approaches, their succession, the radial-gap
 * approximation at each searched epoch, a modern-rate historical illustration,
 * the precession rate, and the zodiac drift. Static prose is checked separately.
 *
 * Run:  node research/precession-equinoxes/verify.mjs
 * ==========================================================================*/
import { fileURLToPath, pathToFileURL } from "node:url";
import { dirname, join } from "node:path";

const here = dirname(fileURLToPath(import.meta.url));
// The model attaches itself to globalThis.Precession (one source of truth with
// the page). Import it for side effect, then read it back.
await import(pathToFileURL(join(here, "..", "..", "public", "strata", "the-star-that-wont-stay-north", "model.js")).href);
const P = globalThis.Precession;

let pass = 0, fail = 0;
function ok(name, cond, detail) {
  if (cond) { pass++; console.log(`  ✓ ${name}${detail ? "  — " + detail : ""}`); }
  else { fail++; console.log(`  ✗ ${name}${detail ? "  — " + detail : ""}`); }
}
function near(a, b, tol) { return Math.abs(a - b) <= tol; }

console.log("\nThe Star That Won't Stay North — verifier\n");

// --- 1. Period <-> rate identity -------------------------------------------
console.log("Precession rate and period");
ok("period 25,772 yr ⇔ 50.29\"/yr", near(P.RATE_ARCSEC_PER_YR, 50.29, 0.01),
  `${P.RATE_ARCSEC_PER_YR.toFixed(3)}"/yr`);
ok("equinox regresses ~1° per 71.6 yr", near(3600 / P.RATE_ARCSEC_PER_YR, 71.6, 0.2),
  `1° every ${(3600 / P.RATE_ARCSEC_PER_YR).toFixed(1)} yr`);
ok("J2000 obliquity from IAU 1980", near(P.EPS0, 84381.448 / 3600, 1e-7), `${P.EPS0}°`);

// --- 2. Pole-star epochs & minimum distances vs published canon -------------
// Approximate literature anchors; see SOURCES.md. These tolerances check
// selected model outputs, not a uniform real-world error bound. Kochab has
// no external anchor here. Deep-time distances can differ by more than a degree.
console.log("\nPole-star closest approaches (model vs canon)");
const ANCHORS = {
  Thuban:    { year: -2787, yTol: 120, dist: 0.30, dTol: 0.25 }, // ~2787 BCE, very close
  Polaris:   { year:  2102, yTol:  40, dist: 0.46, dTol: 0.05 }, // ~2100 CE, ~0.45°
  Errai:     { year:  4130, yTol: 150, dist: 1.82, dTol: 0.30 }, // γ Cep, ~4000 CE
  Alderamin: { year:  7500, yTol: 300, dist: 3.0,  dTol: 1.0  }, // α Cep, ~3° around 7500 CE
  Deneb:     { year: 10200, yTol: 400, dist: 6.65, dTol: 0.50 }, // roughly 7° at this future approach
  Vega:      { year: 13727, yTol: 150, dist: 4.0,  dTol: 1.2  }  // ~13,700 CE, ~4–5°
};
for (const s of P.STARS) {
  const a = ANCHORS[s.name]; if (!a) continue;
  const ca = P.closestApproach(s);
  ok(`${s.name} nearest ≈ ${a.year > 0 ? a.year + " CE" : (-a.year) + " BCE"}`,
    near(ca.year, a.year, a.yTol) && near(ca.dist, a.dist, a.dTol),
    `model: ${ca.year > 0 ? ca.year + " CE" : (-ca.year) + " BCE"}, ${ca.dist.toFixed(2)}° (canon ≈ ${a.dist}°)`);
}
// Order of the succession is monotone in time within one cycle.
const order = P.STARS.map(s => ({ n: s.name, y: P.closestApproach(s).year })).sort((x, y) => x.y - y.y);
ok("succession runs Thuban → … → Vega in order",
  order.map(o => o.n).join(" → ") === "Thuban → Kochab → Polaris → Errai → Alderamin → Deneb → Vega",
  order.map(o => `${o.n}(${o.y})`).join(" → "));

// --- 3. The clean geometric identity ---------------------------------------
// For a stationary star at fixed obliquity, the minimum distance to the
// pole circle equals the radial gap |(90°-epsilon)-beta|. Here stars move:
// evaluate beta at the searched epoch and test an approximation for these
// seven stars in the finite search window, not a bound from today's latitude.
console.log("\nRadial-gap approximation at each searched epoch");
for (const s of P.STARS) {
  const ca = P.closestApproach(s);
  const yrs = ca.year - 2000;
  const beta = P.eclLat(s, yrs);
  const predicted = Math.abs((90 - P.EPS0) - beta);
  ok(`${s.name}: radial gap at approach approximates searched min`, near(predicted, ca.dist, 0.06),
    `gap ${predicted.toFixed(2)}° vs searched ${ca.dist.toFixed(2)}°`);
}

// --- 4. Hipparchus, recomputed ---------------------------------------------
// Around 129 BCE Hipparchus compared his Spica measurements at lunar eclipses
// with Timocharis's occultations about 160 years earlier. As an approximate
// illustration only, use 150 years at the modern rate and compare with his
// rough 2-degree estimate. The 1-degree/century wording below is a paraphrase.
console.log("\nA modern-rate illustration of Hipparchus's rough estimate");
const shift150 = P.RATE_ARCSEC_PER_YR * 150 / 3600; // degrees
ok("150 yr of modern precession ≈ Hipparchus's ~2°", near(shift150, 2.0, 0.2),
  `${shift150.toFixed(2)}° (he reported ~2°)`);
ok("modern rate clears his '≥1°/century' floor", P.RATE_ARCSEC_PER_YR * 100 / 3600 >= 1.0,
  `${(P.RATE_ARCSEC_PER_YR * 100 / 3600).toFixed(2)}°/century`);
ok("his rate floor (1°/century) gives an upper bound on the period",
  36000 > P.PERIOD, `≤36,000 yr (his max) vs ${P.PERIOD} yr (modern)`);

// --- 5. The zodiac drift ----------------------------------------------------
// The thirteen IAU constellations the ecliptic crosses, with their widths
// taken from the real Sun's transit times. They must sum to ~one year, and
// Ophiuchus must be present (the 13th the tropical zodiac drops).
console.log("\nThe zodiac drift");
const totalDays = P.CONSTELLATIONS.reduce((s, c) => s + c[3], 0);
ok("13 ecliptic constellations span ≈ 365 days", near(totalDays, 365, 2), `${totalDays} days`);
ok("Ophiuchus is on the ecliptic (the 13th)",
  P.CONSTELLATIONS.some(c => c[0] === "Ophiuchus"));
ok("Scorpius is the narrowest (Sun there only ~7 days)",
  P.CONSTELLATIONS.find(c => c[0] === "Scorpius")[3] === Math.min(...P.CONSTELLATIONS.map(c => c[3])));
ok("Virgo is the widest (~45 days)",
  P.CONSTELLATIONS.find(c => c[0] === "Virgo")[3] === Math.max(...P.CONSTELLATIONS.map(c => c[3])));

// The headline mismatch: the equinox now sits in Pisces, ~one sign behind
// "Aries", because the signs were named ~2000 yr ago and the stars have slid.
const eq = P.birthday(3, 21); // the March-equinox date itself
ok("March-equinox date: sign 'Aries' but Sun is really in Pisces",
  eq.sign === "Aries" && eq.constellation === "Pisces",
  `sign ${eq.sign} · constellation ${eq.constellation}`);

// Count mismatching names in the model's fixed birthday ranges. Most differ;
// some still coincide, so this does not assert a mismatch for every birthday.
let mism = 0, total = 0;
for (let m = 1; m <= 12; m++) {
  const dmax = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1];
  for (let d = 1; d <= dmax; d++) { total++; const b = P.birthday(m, d); if (b.sign !== b.constellation) mism++; }
}
ok("the sign and the real constellation disagree on most days",
  mism / total > 0.7, `${mism}/${total} days mismatched`);

// Rough check against the cited "equinox enters Aquarius ~2597 CE".
// This estimate uses a 2000 reference; the browser wheel uses 2026.
// The equinox sits in Pisces now and precesses westward (decreasing ecliptic
// longitude) toward Aquarius. The Aquarius↔Pisces boundary is where the Sun
// crosses FROM Aquarius INTO Pisces — calendar date Mar 12 — which is ~8 days
// of solar motion before the equinox (Mar 20). Mean Sun ≈ 0.9856°/day ⇒ ~7.9°;
// at 50.29"/yr that arc takes ~565 yr ⇒ ~2565 CE (cited 2597, mean-Sun approx).
console.log("\nThe Age of Aquarius, cross-checked");
const arcDeg = (P.doy(3, 20) - P.doy(3, 12)) * (360 / 365.2422); // equinox to Aquarius/Pisces boundary
const yearsToAquarius = arcDeg / (P.RATE_ARCSEC_PER_YR / 3600);
const enterAquarius = Math.round(2000 + yearsToAquarius);
ok("computed equinox→Aquarius ≈ cited 2597 CE", near(enterAquarius, 2597, 80),
  `model ${enterAquarius} CE vs cited 2597 CE (mean-Sun approx.)`);

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