#!/usr/bin/env node
// Eight Minutes of Arc: the check.
//
// Recomputes, without Python and without an ephemeris file, every number the page prints, and
// fails if the page and the data disagree. Node 22+, no packages.
//
//   node verify.mjs            # check (inside the unzipped check.zip, or from the repository)
//   node verify.mjs --write    # (repository only) rebuild the page's data.json
//
// What it redoes, independently of the Python that made the data:
//   1. reads Tycho's Latin again (its own parser, not parse.py's) out of Pafko's sheet and
//      checks every declination parse.py wrote, and every place Pafko's numbers differ;
//   2. every statistic about Tycho's residuals (calendar, refraction, the 1587 month, the
//      digit slips) from observations.csv and modern.csv;
//   3. every fitted shape's error against the real Mars, with the page's own engine.js
//      on the page's own truth.json (so the browser is checked, not just the Python);
//   4. the dilemma (direction vs distance) from its fitted numbers, and Kepler's own two
//      circles from nothing but his printed eccentricities;
//   5. every shape graded by Tycho's 882 raw readings, from tycho-frame.json;
//   6. the independent route (astropy + analytic theories) against the DE440 declinations.
// What it does NOT redo: the DE440 positions and the least-squares fits themselves (reduce.py,
// dilemma.py, fitall.py; they need a 114 MB ephemeris and SciPy). It checks what they wrote.

import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = dirname(fileURLToPath(import.meta.url));
const SLUG = 'eight-minutes-of-arc';
const PAGE_DIR = join(HERE, '..', '..', 'public', 'strata', SLUG);
const WRITE = process.argv.includes('--write');
function locate(name) {
  for (const d of [HERE, PAGE_DIR]) { const p = join(d, name); if (existsSync(p)) return p; }
  throw new Error('missing ' + name);
}
const read = (n) => readFileSync(locate(n), 'utf8');
const json = (n) => JSON.parse(read(n));

let passed = 0, failed = 0;
function ok(cond, msg) { if (cond) passed++; else { failed++; console.log('  FAIL ' + msg); } }
function near(a, b, tol, msg) { ok(Math.abs(a - b) <= tol, `${msg}: ${a} vs ${b} (tol ${tol})`); }
function section(s) { console.log('\n' + s); }

function parseCSV(text) {
  const rows = []; let row = [], f = '', q = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (q) { if (c === '"') { if (text[i + 1] === '"') { f += '"'; i++; } else q = false; } else f += c; }
    else if (c === '"') q = true;
    else if (c === ',') { row.push(f); f = ''; }
    else if (c === '\n') { row.push(f); rows.push(row); row = []; f = ''; }
    else if (c !== '\r') f += c;
  }
  if (f.length || row.length) { row.push(f); rows.push(row); }
  return rows;
}
function records(text) { const [h, ...rs] = parseCSV(text).filter(r => r.length > 1); return rs.map(r => Object.fromEntries(h.map((k, i) => [k, r[i]]))); }
const median = (a) => { const s = [...a].sort((x, y) => x - y), n = s.length; return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2; };
function summary(r) {
  const a = r.map(Math.abs), med = median(r);
  return { n: r.length, median: med, median_abs: median(a), robust_sigma: 1.4826 * median(r.map(x => Math.abs(x - med))),
           within_2: a.filter(x => x <= 2).length / r.length, over_8: a.filter(x => x > 8).length };
}

// ---------------------------------------------------------------------------------------
section('1. Tycho\'s Latin, read a second time');
// A second parser, written without looking at parse.py's: take the declination out of the
// quoted reading. Degrees, minutes, optional seconds; '1/2' after a number adds to it.
function readDec(q) {
  if (q.includes('…') || q.includes('...')) return null;
  let s = q;
  const k = s.search(/decl/i);
  if (k >= 0) { s = s.slice(k).replace(/^decl\w*\.?/i, ''); s = s.split(/\bet\b|Afc|Asc|Recta/)[0]; }
  if (/\bII\b/.test(s)) s = s.split(/\bII\b/)[0].replace(/\bI\b/, ' ');
  s = s.replace(/[°'"]/g, ' ').replace(/(\d)o\b/g, '$1 ');
  const toks = [...s.matchAll(/(\d+)\s*\/\s*(\d+)|(\d+)/g)];
  const v = [];
  for (const m of toks) {
    if (m[3] !== undefined) v.push(Number(m[3]));
    else { if (!v.length) return null; v[v.length - 1] += Number(m[1]) / Number(m[2]); }
  }
  if (!v.length) return null;
  return v[0] + (v.length > 1 ? v[1] / 60 : 0) + (v.length > 2 ? v[2] / 3600 : 0);
}
const raw = parseCSV(read('pafko-raw.csv'));
const obs = records(read('observations.csv'));
const obsByRow = Object.fromEntries(obs.map(o => [o.sheet_row, o]));
let nRead = 0, agree = 0;
raw.forEach((r, i) => {
  const sheetRow = i + 1;
  if (sheetRow < 7 || !r[1] || !r[1].trim()) return;
  nRead++;
  const mine = readDec(r[4]);
  const theirs = obsByRow[String(sheetRow)];
  const pd = theirs.dec_abs_deg === '' ? null : Number(theirs.dec_abs_deg);
  if ((mine === null && pd === null) || (mine !== null && pd !== null && Math.abs(mine - pd) < 1e-9)) agree++;
  else console.log(`    row ${sheetRow}: second reading ${mine} vs parse.py ${pd}  (${r[4]})`);
});
ok(nRead === 923, `923 readings in the sheet (${nRead})`);
ok(agree === nRead, `both parsers agree on every declination (${agree}/${nRead})`);

// ---------------------------------------------------------------------------------------
section('2. Tycho against the real Mars');
const modern = records(read('modern.csv'));
const ADOPTED = { hven: 'julian', benatky: 'gregorian' };
const CORRECTED = /refr|vera|emend/i;
function resid(m, col = 'dec_refracted', dec = null) {
  const o = obsByRow[m.sheet_row];
  const sign = Number(m.dec_true) >= 0 ? 1 : -1;
  return ((dec ?? Number(o.dec_abs_deg)) * sign - Number(m[col])) * 60;
}
const adopted = modern.filter(m => m.calendar === ADOPTED[m.site]);
const raw0 = adopted.filter(m => !CORRECTED.test(obsByRow[m.sheet_row].quote));
const T = json('tycho.json');
ok(adopted.length === T.n_with_hour, `${adopted.length} readings with an hour and a declination`);
ok(adopted.length - raw0.length === T.n_labelled_corrected, `${adopted.length - raw0.length} readings Tycho labels as already corrected`);
const S = {};
for (const site of ['hven', 'benatky']) for (const cal of ['julian', 'gregorian']) {
  const r = modern.filter(m => m.site === site && m.calendar === cal && !CORRECTED.test(obsByRow[m.sheet_row].quote)).map(m => resid(m));
  S[`${site}_${cal}`] = summary(r);
  near(S[`${site}_${cal}`].median_abs, T.calendar[`${site}_${cal}`].median_abs, 0.001, `${site} ${cal}: median |residual|`);
  near(S[`${site}_${cal}`].robust_sigma, T.calendar[`${site}_${cal}`].robust_sigma, 0.001, `${site} ${cal}: robust sigma`);
}
const all = summary(raw0.map(m => resid(m)));
const trueSky = summary(raw0.map(m => resid(m, 'dec_true')));
near(all.median_abs, T.refraction.raw_vs_refracted_sky.median_abs, 0.001, 'all raw readings, median |r|');
near(all.robust_sigma, T.refraction.raw_vs_refracted_sky.robust_sigma, 0.001, 'robust sigma');
near(all.within_2, T.refraction.raw_vs_refracted_sky.within_2, 0.0001, 'fraction within 2\'');
ok(all.over_8 === T.refraction.raw_vs_refracted_sky.over_8, `readings more than 8' out: ${all.over_8}`);
near(trueSky.median, T.refraction.raw_vs_true_sky.median, 0.001, 'median against the airless sky');
// refraction slope by ordinary least squares on the same selection
{
  const X = [], Y = [];
  for (const m of raw0) {
    const xr = (Number(m.dec_refracted) - Number(m.dec_true)) * 60, y = resid(m, 'dec_true');
    if (Math.abs(y - xr) < 8) { X.push(xr); Y.push(y); }
  }
  const n = X.length, mx = X.reduce((a, b) => a + b) / n, my = Y.reduce((a, b) => a + b) / n;
  let sxy = 0, sxx = 0; for (let i = 0; i < n; i++) { sxy += (X[i] - mx) * (Y[i] - my); sxx += (X[i] - mx) ** 2; }
  near(sxy / sxx, T.refraction.slope_on_refraction.slope, 0.0006, 'slope of residual on refraction');
  ok(n === T.refraction.slope_on_refraction.n, `slope fitted on ${n} readings`);
}
// the 1587 month
{
  const feb = modern.filter(m => m.calendar === 'julian-if-february');
  const jan = modern.filter(m => m.calendar === 'julian' && feb.some(f => f.sheet_row === m.sheet_row));
  near(Math.max(...jan.map(m => Math.abs(resid(m)))), T.month_test_1587.max_abs_if_january, 0.006, '1587 read as January: worst');
  near(Math.min(...feb.map(m => Math.abs(resid(m)))), T.month_test_1587.min_abs_if_february, 0.006, '1587 read as February: best');
}
// Pafko's numbers vs the Latin
{
  let differ = 0, over5 = 0, oursCloser = 0;
  for (const m of raw0) {
    const o = obsByRow[m.sheet_row];
    if (o.pafko_dec_deg === '') continue;
    const rp = resid(m, 'dec_refracted', Math.abs(Number(o.pafko_dec_deg))), r = resid(m);
    if (Math.abs(rp - r) > 0.05) { differ++; if (Math.abs(rp - r) > 5) over5++; if (Math.abs(r) < Math.abs(rp)) oursCloser++; }
  }
  ok(differ === T.pafko_vs_ours.n_differ, `readings where Pafko's number and the Latin differ: ${differ}`);
  ok(over5 === T.pafko_vs_ours.n_differ_over_5, `...by more than 5': ${over5}`);
  ok(oursCloser === T.pafko_vs_ours.ours_closer, `...where the Latin lands closer to the sky: ${oursCloser}`);
}
// hours moved by visibility, and the cost of a 30-minute clock error
ok(adopted.filter(m => m.hour_rule === 'moved').length === T.n_hour_moved_by_visibility, 'hours re-read by visibility');
ok(adopted.every(m => m.hour_rule !== 'not visible'), 'every reading has an hour at which Mars was up and the Sun down');
{
  const rates = adopted.map(m => Math.abs(Number(m.dec_rate_arcmin_per_h)));
  near(Math.max(...rates) * 0.5, T.hour_error_budget.max_arcmin, 0.001, 'worst cost of a 30-minute hour error');
}

// ---------------------------------------------------------------------------------------
section('3. The shapes, seen from the Earth (the page\'s engine on the page\'s truth)');
new Function(read('engine.js'))();
const E = globalThis.EightMinutes;
const truth = json('truth.json');
const F = json('fits.json');
let nCombo = 0;
for (const [key, v] of Object.entries(F.fits)) {
  const [ek, mk, ref] = key.split('|');
  const s = E.stats(E.lonErrors(truth, ek, mk, ref, v.truth.params));
  near(s.max, v.truth.max_abs_err_arcmin, 0.005, `${key} worst longitude error`);
  near(s.rms, v.truth.rms_arcmin, 0.005, `${key} rms`);
  nCombo++;
}
ok(nCombo === 28, `28 combinations of shapes (${nCombo})`);
const NAMED = F.named;
const truthStat = (name) => F.fits[NAMED[name].join('|')].truth;

// ---------------------------------------------------------------------------------------
section('4. The dilemma, seen from the Sun');
const D = json('dilemma.json');
const pl = truth.plane;
const helio = truth.mars.map(p => [p[0] * pl[0][0] + p[1] * pl[0][1] + p[2] * pl[0][2], p[0] * pl[1][0] + p[1] * pl[1][1] + p[2] * pl[1][2]]);
function dilemmaErrors(kind, f, p, R) {
  let md = 0, mr = 0, sumd = 0;
  const lon = [], dist = [];
  for (let i = 0; i < helio.length; i++) {
    const t = truth.start_tt + i * truth.step_days - D.T0_tt;
    const A = p[1] + p[4] * t, M = p[3] + (p[2] - p[4]) * t;
    const xy = kind === 'ellipse' ? E.keplerEllipse(p[0], M) : E.circEquant((1 - f) * p[0], f * p[0], M);
    const c = Math.cos(A), s = Math.sin(A), X = c * xy[0] - s * xy[1], Y = s * xy[0] + c * xy[1];
    const d = E.wrap(Math.atan2(Y, X) - Math.atan2(helio[i][1], helio[i][0])) * E.AM;
    md = Math.max(md, Math.abs(d));
    lon.push(d); dist.push([Math.hypot(X, Y), Math.hypot(helio[i][0], helio[i][1])]);
    sumd += dist[i][1];
  }
  const mean = sumd / helio.length;
  for (const [r, tr] of dist) mr = Math.max(mr, Math.abs(R * r - tr) / mean * 100);
  return { dir: md, dist: mr };
}
for (const name of ['vicarious', 'bisected', 'ellipse']) {
  const rec = D[name];
  const e = dilemmaErrors(rec.kind === 'ellipse' ? 'ellipse' : 'circle', rec.f_exact ?? 0, rec.params, rec.R_au);
  near(e.dir, rec.max_dir_err_arcmin, 0.005, `${name}: worst direction error from its numbers`);
  near(e.dist, rec.max_dist_err_pct, 0.005, `${name}: worst distance error (%)`);
}
{
  const best = D.sweep.reduce((a, b) => (b.max_dir_err_arcmin < a.max_dir_err_arcmin ? b : a));
  ok(Math.abs(best.f - 0.38) < 0.005, `the circle's direction is best at f = ${best.f}`);
  ok(D.sweep.every((r, i, a) => i === 0 || r.max_dist_err_pct < a[i - 1].max_dist_err_pct || r.f > 0.5), 'distance error falls all the way to bisection');
}
// Kepler's own two circles: no data at all
let kMax = 0, k45 = 0;
for (let i = 0; i <= 360000; i++) {
  const M = i / 360000 * 2 * Math.PI;
  const v = E.circEquant(0.11332, 0.07232, M), b = E.circEquant(0.09282, 0.09282, M);
  const d = Math.abs(E.wrap(Math.atan2(b[1], b[0]) - Math.atan2(v[1], v[0])) * E.AM);
  const h = ((Math.atan2(v[1], v[0]) * 180 / Math.PI) + 360) % 360;
  kMax = Math.max(kMax, d);
  if (Math.abs(h - 45) < 5 || Math.abs(h - 315) < 5) k45 = Math.max(k45, d);
}
near(kMax, D.kepler_numbers.max_diff_arcmin, 1e-4, 'Kepler\'s two circles: widest gap');
near(k45, D.kepler_numbers.max_diff_within_5deg_of_45_from_aphelion, 1e-4, '...within 5 deg of 45 deg from aphelion');

// ---------------------------------------------------------------------------------------
section('5. Tycho as the judge');
const TF = json('tycho-frame.json');
function tychoResiduals(ek, mk, ref, q) {
  const out = [];
  for (let i = 0; i < TF.t.length; i++) {
    const g = E.geocentric(ek, mk, ref, q, TF.t[i], truth.plane, truth.eplane);
    const m = TF.mat[i];
    const x = m[0] * g[0] + m[1] * g[1] + m[2] * g[2], y = m[3] * g[0] + m[4] * g[1] + m[5] * g[2], z = m[6] * g[0] + m[7] * g[1] + m[8] * g[2];
    const dec = Math.asin(z / Math.hypot(x, y, z)) * 180 / Math.PI;
    out.push((dec - TF.dec_deg[i]) * 60 + TF.corr_arcmin[i]);
  }
  return out;
}
ok(TF.t.length === 882, `${TF.t.length} raw readings in the judging set`);
ok(TF.wild.filter(Boolean).length === 38, 'readings over 8\' from the real Mars, left out of the refit only');
const JUDGE = {};
for (const [name, [ek, mk, ref]] of Object.entries(NAMED)) {
  const rec = F.fits[`${ek}|${mk}|${ref}`];
  for (const which of ['graded', 'tycho']) {
    const q = which === 'graded' ? rec.truth.params : rec.tycho.params;
    const s = summary(tychoResiduals(ek, mk, ref, q));
    near(s.robust_sigma, rec[which].robust_sigma_arcmin, 0.003, `${name} ${which}: robust sigma`);
    near(s.within_2, rec[which].within_2, 0.0012, `${name} ${which}: within 2'`);
    (JUDGE[name] ||= {})[which] = s;
  }
}

// ---------------------------------------------------------------------------------------
section('6. The second route');
const X = json('cross-check.json');
ok(X.n === 887, `astropy compared on ${X.n} readings`);
ok(X.max_abs_diff_arcsec < 15, `worst disagreement with DE440, ${X.max_abs_diff_arcsec}", is under a quarter of an arcminute`);

// ---------------------------------------------------------------------------------------
section('7. The page says what the data says');
const f1 = (x) => x.toFixed(1), f2 = (x) => x.toFixed(2), pct = (x) => Math.round(x * 100) + '%';
const claims = {
  n_all: '923', n_used: String(raw0.length), n_hour: String(adopted.length),
  med_abs: f2(all.median_abs), sigma: f2(all.robust_sigma), within2: pct(all.within_2), over8: String(all.over_8),
  greg_med: String(Math.round(S.hven_gregorian.median_abs)),
  ben_jul: f1(S.benatky_julian.median_abs), ben_greg: f1(S.benatky_gregorian.median_abs),
  true_sky_med: f1(trueSky.median), slope: f2(T.refraction.slope_on_refraction.slope),
  slope_lo: f2(T.refraction.slope_on_refraction.ci95[0]), slope_hi: f2(T.refraction.slope_on_refraction.ci95[1]),
  jan: f1(T.month_test_1587.max_abs_if_january), feb: String(Math.round(T.month_test_1587.min_abs_if_february)),
  pafko_n: String(T.pafko_vs_ours.n_differ), pafko_5: String(T.pafko_vs_ours.n_differ_over_5), pafko_closer: String(T.pafko_vs_ours.ours_closer),
  moved: String(T.n_hour_moved_by_visibility), clock: f1(T.hour_error_budget.max_arcmin),
  vic_dir: f1(D.vicarious.max_dir_err_arcmin), vic_dist: f1(D.vicarious.max_dist_err_pct),
  bis_dir: f1(D.bisected.max_dir_err_arcmin), bis_dist: f2(D.bisected.max_dist_err_pct),
  ell_dir: f1(D.ellipse.max_dir_err_arcmin), ell_dist: f2(D.ellipse.max_dist_err_pct),
  k_max: f1(D.kepler_numbers.max_diff_arcmin), k_45: f1(D.kepler_numbers.max_diff_within_5deg_of_45_from_aphelion),
  pto_max: String(Math.round(truthStat('ptolemy').max_abs_err_arcmin)), cop_max: String(Math.round(truthStat('copernicus').max_abs_err_arcmin)),
  bis_geo: String(Math.round(truthStat('kepler-bisected').max_abs_err_arcmin)), k1609_geo: f1(truthStat('kepler-1609').max_abs_err_arcmin),
  eq_ell_geo: f1(F.fits['equant|ellipse|sun'].truth.max_abs_err_arcmin),
  g_pto: f1(JUDGE.ptolemy.graded.robust_sigma), g_cop: f1(JUDGE.copernicus.graded.robust_sigma),
  g_bis: f1(JUDGE['kepler-bisected'].graded.robust_sigma), g_vic: f1(JUDGE['kepler-vicarious'].graded.robust_sigma),
  g_1609: f2(JUDGE['kepler-1609'].graded.robust_sigma),
  t_pto: f1(JUDGE.ptolemy.tycho.robust_sigma), t_cop: f1(JUDGE.copernicus.tycho.robust_sigma),
  t_bis: f1(JUDGE['kepler-bisected'].tycho.robust_sigma), t_vic: f1(JUDGE['kepler-vicarious'].tycho.robust_sigma),
  t_1609: f2(JUDGE['kepler-1609'].tycho.robust_sigma),
  w_pto: pct(JUDGE.ptolemy.graded.within_2), w_cop: pct(JUDGE.copernicus.graded.within_2), w_vic: pct(JUDGE['kepler-vicarious'].graded.within_2), w_bis: pct(JUDGE['kepler-bisected'].graded.within_2), w_1609: pct(JUDGE['kepler-1609'].graded.within_2),
  tilt: f1(F.earth_tilt_arcmin), xcheck: f1(X.max_abs_diff_arcsec),
};
const html = read('index.html');
{
  const desc = (html.match(/<meta name="description" content="([^"]*)"/) || [])[1] || '';
  ok(desc.includes(claims.n_used + ' of Tycho') && desc.includes(claims.med_abs + ' arcminutes') && desc.includes(claims.bis_dir + ' arcminutes'),
     'the meta description carries the page\'s own figures (' + claims.n_used + ', ' + claims.med_abs + ', ' + claims.bis_dir + ')');
}

const spans = [...html.matchAll(/data-v="([a-z0-9_]+)"[^>]*>([^<]*)</g)];
const seen = new Set();
for (const [, key, text] of spans) {
  seen.add(key);
  ok(key in claims, `the page prints an unknown figure '${key}'`);
  if (key in claims) ok(text.trim() === claims[key], `page figure ${key}: page says '${text.trim()}', data says '${claims[key]}'`);
}
for (const k of Object.keys(claims)) ok(seen.has(k), `the page never prints '${k}'`);
{ // the ground's card for this page (repository only; not in the zip)
  const md = join(HERE, '..', '..', 'src', 'content', 'strata', SLUG + '.md');
  if (existsSync(md)) {
    const t = readFileSync(md, 'utf8');
    for (const k of ['n_used', 'med_abs', 'sigma', 'vic_dir', 'vic_dist', 'bis_dir', 'bis_dist', 'ell_dir', 'pto_max', 'cop_max', 'bis_geo', 'k1609_geo', 'pafko_n'])
      ok(t.includes(claims[k]), `the stratum card carries ${k} = ${claims[k]}`);
  }
}

// ---------------------------------------------------------------------------------------
// In the repository only: the check.zip a reader downloads must hold these very files, or the
// reader would be checking an older page than the one in front of them.
if (existsSync(join(PAGE_DIR, 'check.zip')) && !WRITE) {
  section('8. The reader\'s zip holds these files');
  const { inflateRawSync } = await import('node:zlib');
  const z = readFileSync(join(PAGE_DIR, 'check.zip'));
  const inZip = {};
  for (let o = 0; z.readUInt32LE(o) === 0x04034b50;) {
    const method = z.readUInt16LE(o + 8), csize = z.readUInt32LE(o + 18), nlen = z.readUInt16LE(o + 26), xlen = z.readUInt16LE(o + 28);
    const name = z.toString('utf8', o + 30, o + 30 + nlen), body = z.subarray(o + 30 + nlen + xlen, o + 30 + nlen + xlen + csize);
    inZip[name.split('/').pop()] = method === 8 ? inflateRawSync(body) : body;
    o += 30 + nlen + xlen + csize;
  }
  const beside = join(PAGE_DIR, 'verify.mjs');
  ok(existsSync(beside) && readFileSync(beside).equals(readFileSync(join(HERE, 'verify.mjs'))), 'the verify.mjs served beside the page is this one (cp it after editing)');
  for (const n of ['verify.mjs', 'engine.js', 'index.html', 'observations.csv', 'modern.csv', 'tycho.json', 'fits.json', 'dilemma.json', 'tycho-frame.json', 'truth.json', 'cross-check.json', 'pafko-raw.csv'])
    ok(inZip[n] && inZip[n].equals(readFileSync(locate(n))), `check.zip carries the current ${n} (rebuild with python3 package.py)`);
}
if (WRITE) {
  const r = (x, d = 2) => Number(x.toFixed(d));
  const points = raw0.map(m => {
    const o = obsByRow[m.sheet_row];
    const other = modern.find(x => x.sheet_row === m.sheet_row && x.calendar === (m.calendar === 'julian' ? 'gregorian' : 'julian'));
    const y = Number(o.year), mo = Number(o.month), d = Number(o.day);
    return [Number(m.sheet_row), r(y + (mo - 1 + (d - 0.5) / 31) / 12, 4), r(resid(m), 3), r(resid(m, 'dec_true'), 3), r(resid(other), 1),
            o.pafko_dec_deg === '' ? null : r(resid(m, 'dec_refracted', Math.abs(Number(o.pafko_dec_deg)))),
            `${o.year}-${String(o.month).padStart(2, '0')}-${String(o.day).padStart(2, '0')}`, o.quote, Number(o.volume), Number(o.page)];
  });
  const judged = {};
  for (const [name, [ek, mk, ref]] of Object.entries(NAMED)) judged[name] = tychoResiduals(ek, mk, ref, F.fits[`${ek}|${mk}|${ref}`].truth.params).map(x => r(x));
  const data = {
    points, judged, named: NAMED,
    fits: Object.fromEntries(Object.entries(F.fits).map(([k, v]) => [k, { params: v.truth.params, max: r(v.truth.max_abs_err_arcmin), rms: r(v.truth.rms_arcmin) }])),
    dilemma: { sweep: D.sweep.map(x => ({ f: x.f, dir: r(x.max_dir_err_arcmin), dist: r(x.max_dist_err_pct, 3), E: x.total_ecc, params: x.params, R: x.R_au })),
               ellipse: { dir: r(D.ellipse.max_dir_err_arcmin), dist: r(D.ellipse.max_dist_err_pct, 3), params: D.ellipse.params, R: D.ellipse.R_au },
               T0_tt: D.T0_tt },
  };
  writeFileSync(join(PAGE_DIR, 'data.json'), JSON.stringify(data));
  console.log('\nwrote data.json');
}
console.log(`\n${passed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
