#!/usr/bin/env node
// verify.mjs — the check for "A Thousand Springs" (the Kyoto cherry record).
// This check compares the three source transcriptions and re-derives selected
// data counts, rankings and averages. The shipped data is pinned to the checked
// dataset so it cannot silently drift. Run:
//
//   node research/a-thousand-springs/verify.mjs
//
// Exits nonzero on any failure. No network, no invented numbers.
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { doyFromISO } from "./build-data.mjs";

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, "..", "..");
const lines = (f) => readFileSync(join(HERE, f), "utf8").trim().split("\n");

let pass = 0, fail = 0;
const ok = (name, cond, extra = "") => {
  (cond ? pass++ : fail++);
  console.log(`${cond ? "  ok " : " FAIL"}  ${name}${extra ? "  — " + extra : ""}`);
};
const approx = (a, b, eps = 0.05) => Math.abs(a - b) <= eps;
const mean = (a) => a.reduce((s, x) => s + x, 0) / a.length;

// ---- load the three independent mirrors ----
const gmu = lines("kyoto_gmu.csv").slice(1).map((l) => {
  const c = l.split(",").map((x) => x.replace(/"/g, ""));
  return { year: +c[4], date: c[5], doy: +c[6] };
}).filter((r) => r.doy > 0);
const ry = new Map();
for (const l of lines("mirror_ryon7.csv").slice(1)) {
  const c = l.split(",");
  if (c[1] && c[1].trim() !== "") ry.set(+c[0], +c[1]);
}
const rt = new Map();
for (const l of lines("mirror_rethinking.csv").slice(1)) {
  const c = l.split(";");
  if (c[1] && c[1] !== "NA") rt.set(+c[0], +c[1]);
}
const data = JSON.parse(readFileSync(join(HERE, "data.json"), "utf8"));
const recs = data.records;

console.log("A Thousand Springs — verification\n");

// ============ 1. internal consistency: DOY recomputes from the calendar date ============
let doyBad = 0;
for (const r of gmu) if (doyFromISO(r.date) !== r.doy) doyBad++;
ok("every full-flowering DOY recomputes from its date (leap-aware)", doyBad === 0, `${doyBad} mismatches of ${gmu.length}`);

// ============ 2. three independent transcriptions agree on every shared year ============
let shared7 = 0, dis7 = 0, sharedRt = 0, disRt = 0;
for (const r of gmu) {
  if (ry.has(r.year)) { shared7++; if (ry.get(r.year) !== r.doy) dis7++; }
  if (rt.has(r.year)) { sharedRt++; if (rt.get(r.year) !== r.doy) disRt++; }
}
ok("GMU vs Ryo-N7 transcription: identical on all shared years", dis7 === 0, `${shared7} shared, ${dis7} disagree`);
ok("GMU vs McElreath transcription: identical on all shared years", disRt === 0, `${sharedRt} shared, ${disRt} disagree`);

// ============ 3. the merged data.json is faithful to the sources (drift guard) ============
const gmuMap = new Map(gmu.map((r) => [r.year, r]));
let mergeBad = 0;
for (const r of recs) {
  const g = gmuMap.get(r.year);
  if (!g || g.date !== r.date || g.doy !== r.doy) mergeBad++;
}
ok("data.json dates/DOY match the GMU source exactly", mergeBad === 0 && recs.length === gmu.length, `${recs.length} records`);

// the live page loads public/.../data.js — it must be byte-identical to data.json
const pubJs = readFileSync(join(ROOT, "public", "strata", "a-thousand-springs", "data.js"), "utf8");
const pubJson = pubJs.replace(/^[\s\S]*?window\.SPRINGS\s*=\s*/, "").replace(/;\s*$/, "").trim();
const jsonStr = JSON.stringify(data, null, 0);
ok("public data.js the page ships is byte-identical to the checked data.json", pubJson === jsonStr);

// ============ 4. span and coverage ============
const years = recs.map((r) => r.year);
ok("838 dated records spanning 812–2026", recs.length === 838 && Math.min(...years) === 812 && Math.max(...years) === 2026);

// ============ 5. provenance classification ============
const estimated = recs.filter((r) => r.estimated);
const modernNoRef = recs.filter((r) => r.ref === null);
const directWithSrc = recs.filter((r) => r.ref !== null && !r.estimated);
ok("14 dates are Aono estimates (EST-from-WF or EST-from-KJ), all pre-1600", estimated.length === 14 && estimated.every((r) => r.year < 1600));
ok("11 no-historical-source years are the modern extension (2016–2026)", modernNoRef.length === 11 && modernNoRef.every((r) => r.year >= 2016));
ok("824 dates from cherry records or modern observations, 14 estimated (813 sourced + 11 modern)", directWithSrc.length === 813 && directWithSrc.length + modernNoRef.length === 824);

// ============ 6. the headline: the record earliest blooms ============
const byDoy = [...recs].sort((a, b) => a.doy - b.doy || a.year - b.year);
ok("earliest full flowering in the whole record is 2023 (Mar 25, DOY 84)", byDoy[0].year === 2023 && byDoy[0].date === "2023-03-25" && byDoy[0].doy === 84);
ok("second earliest is 2021 (Mar 26, DOY 85)", byDoy[1].year === 2021 && byDoy[1].date === "2021-03-26" && byDoy[1].doy === 85);
const preModern = byDoy.filter((r) => r.year < 1900);
ok("earliest date before 1900 is 1409 (Mar 27, DOY 86) — beaten only in the 21st c.", preModern[0].year === 1409 && preModern[0].doy === 86);
ok("both 21st-century record-holders are direct modern observations, not estimates",
  !byDoy[0].estimated && !byDoy[1].estimated);

// ============ 7. the millennium-long baseline, and its recent collapse ============
const pre1900 = recs.filter((r) => r.year < 1900).map((r) => r.doy);
const since2000 = recs.filter((r) => r.year >= 2000).map((r) => r.doy);
ok("pre-1900 mean DOY ≈ 105.2 over 714 records", pre1900.length === 714 && approx(mean(pre1900), 105.21, 0.02));
ok("2000+ mean DOY ≈ 94.2 over 27 records", since2000.length === 27 && approx(mean(since2000), 94.22, 0.02));
ok("the cherry now blooms ~11 days earlier than its eleven-century average", approx(mean(pre1900) - mean(since2000), 10.99, 0.02));

// century means: flat for a millennium, then the 20th–21st drop
const cм = (lo) => { const s = recs.filter((r) => r.year >= lo && r.year < lo + 100).map((r) => r.doy); return s.length ? mean(s) : null; };
const c19 = cм(1900), c20base = cм(1800);
ok("century means sit in a ~101–107 band for a millennium (800s–1800s)",
  [800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800].every((c) => { const m = cм(c); return m >= 100 && m <= 108; }));
ok("the 1900s mean (101.0) is the earliest of any century until the 2000s (94.2)",
  approx(c19, 101.0, 0.1) && approx(cм(2000), 94.2, 0.1) && cм(2000) < c19);

console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
