// verify-the-clock-only-euripides-kept.mjs: checks every number /strata/the-clock-only-euripides-kept/
// states in its prose, by re-running the scanner the page runs (the Euripides page's engine.mjs,
// unchanged) and the page's own three.mjs over the page's copy of the texts.
//
//   node verify-the-clock-only-euripides-kept.mjs          # the page's files
//   node verify-the-clock-only-euripides-kept.mjs --live   # also re-fetch the 14 Perseus TEI files
//                                                          # at the pinned commit and check that
//                                                          # data/lines.json is a faithful copy
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads engine.mjs, clock.mjs, three.mjs and both line files from https://artwaste.land (the
// bytes your browser runs). Exit 0 = every check passed.

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

const here = dirname(fileURLToPath(import.meta.url));
const LOCAL = existsSync(join(here, 'public/strata/the-clock-only-euripides-kept/three.mjs'));
const base = LOCAL ? join(here, 'public/strata') : 'https://artwaste.land/strata';
const LIVE = process.argv.includes('--live');
const get = async rel => LOCAL ? readFileSync(join(base, rel), 'utf8') : (await fetch(`${base}/${rel}`)).text();
const asModule = src => import('data:text/javascript;base64,' + Buffer.from(src).toString('base64'));
console.error(`files: ${base}`);

// three.mjs imports the engine by a relative path; from a download, point that import at the engine's bytes
const engineSrc = await get('how-euripides-plays-are-dated/engine.mjs');
const engineURL = 'data:text/javascript;base64,' + Buffer.from(engineSrc).toString('base64');
const E = await asModule(engineSrc);
const C = await asModule(await get('how-euripides-plays-are-dated/clock.mjs'));
const T = await asModule((await get('the-clock-only-euripides-kept/three.mjs')).replace(`'../how-euripides-plays-are-dated/engine.mjs'`, `'${engineURL}'`));
const MINE = JSON.parse(await get('the-clock-only-euripides-kept/data/lines.json'));
const EUR = JSON.parse(await get('how-euripides-plays-are-dated/data/lines.json'));
const PAGE = await get('the-clock-only-euripides-kept/index.html');
const PUB = JSON.parse(await get('the-clock-only-euripides-kept/data/published.json'));
const AUD = JSON.parse(await get('the-clock-only-euripides-kept/data/audit.json'));

let fails = 0, passes = 0;
const ok = (c, msg) => { if (c) passes++; else fails++; console.log((c ? 'PASS  ' : 'FAIL  ') + msg); };
const prose = PAGE.replace(/<script[\s\S]*?<\/script>/g, '').replace(/<style[\s\S]*?<\/style>/g, '').replace(/<[^>]+>/g, '').replace(/\s+/g, ' ');
const says = s => prose.includes(s);

// ── 1. scan everything, as the page does ─────────────────────────────────────────
let total = 0;
const P = {};
const text = Object.fromEntries(MINE.plays.map(p => [p.id, p.lines]));
const scan = (lines) => { const s = E.scanText(lines.map(([n, t, br]) => ({ n, text: t, bracketed: !!br }))); total += s.linesTotal; return s.lines.filter(l => l.inRun && !l.bracketed).map(l => Object.assign(l, T.nameSplit(l))); };
for (const p of T.PLAYS3) { const sp = scan(text[p.id]); P[p.id] = { ...p, sp, r: T.rates(sp) }; }
const eYear = Object.fromEntries(C.ANCHORS.map(a => [a.id, a.year]));
for (const p of EUR.plays) { const sp = scan(p.lines); P[p.id] = { poet: 'Euripides', id: p.id, en: E.PLAYS[p.id].en, year: eYear[p.id] ?? null, sp, r: T.rates(sp) }; }
const kept = Object.values(P).reduce((s, p) => s + p.sp.length, 0);
ok(MINE.plays.length === 14 && EUR.plays.length === 19, '14 plays of Aeschylus and Sophocles, 19 of Euripides');
ok(total === 44563 && kept === 28301, `${total.toLocaleString('en')} lines read, ${kept.toLocaleString('en')} kept as spoken trimeters (the page's status line reported 44,563 and 28,301 when it was written)`);
const byEn = en => Object.values(P).find(p => p.en === en && (en !== 'Suppliants' && en !== 'Electra' || p.poet !== 'Euripides'));
{
  const inv = Object.values(P).every(p => p.sp.every(l => l.free + l.named === l.resolutions));
  ok(inv, 'in every spoken line, resolutions in names + resolutions outside names = all resolutions');
}

// ── 2. the prose ─────────────────────────────────────────────────────────────────
const eFit = C.fitClock(C.ANCHORS.map(a => ({ ...a, rate: P[a.id].r.all })));
{
  const alc = P.tlg002.r.all, late = Math.max(P.tlg016.r.all, P.tlg017.r.all, P.tlg018.r.all);
  ok(alc > 6 && alc < 8 && late > 40 && says('from about seven in a hundred lines in the 430s BC to more than forty in a hundred at the end'), `Euripides: Alcestis ${alc.toFixed(2)}, latest plays up to ${late.toFixed(2)} per 100`);
  const ratio = P.tlg016.r.all / byEn('Philoctetes').r.all, ratioF = P.tlg016.r.free / byEn('Philoctetes').r.free;
  ok(ratio > 3.5 && ratio < 4.5 && ratioF > 3.5 && ratioF < 4.5 && says('about four times as many resolutions per line'), `Orestes against Philoctetes: ${ratio.toFixed(2)}x counting every resolution, ${ratioF.toFixed(2)}x with names left out ("about four times")`);
  const earlyMax = Math.max(...['tlg002', 'tlg003', 'tlg005'].map(id => P[id].r.free));
  const within = T.PLAYS3.filter(p => P[p.id].r.free <= earlyMax).length;
  const top = Math.max(...T.PLAYS3.map(p => P[p.id].r.all)), tro = P.tlg011.r.all;
  const later = C.ANCHORS.filter(a => a.year >= -415).every(a => P[a.id].r.all > top * 1.5);
  ok(within === 10 && later && says('ten of the fourteen plays of Aeschylus and Sophocles sit at or below the rate of Euripides\' three earliest dated plays'), `${within} of 14 at or below Euripides' earliest dated (${earlyMax.toFixed(2)}, names left out); highest of the 14 ${top.toFixed(2)} against Trojan Women ${tro.toFixed(2)} and every later dated play`);
}
{
  const ys = T.PLAYS3.map(p => eFit.a + eFit.b * P[p.id].r.all);
  const lo = Math.min(...ys), hi = Math.max(...ys);
  ok(Math.round(-lo) === 433 && Math.round(-hi) === 428 && says('in the four or five years around 430 BC'), `Euripides' clock puts all fourteen between ${Math.round(-lo)} and ${Math.round(-hi)} BC`);
  const pe = eFit.a + eFit.b * byEn('Persians').r.all - (-472), oc = eFit.a + eFit.b * byEn('Oedipus at Colonus').r.all - (-401);
  ok(Math.round(pe) === 44 && Math.round(oc) === -30 && says('comes out 44 years late') && says('30 years early'), `Persians ${pe.toFixed(1)} years late, Oedipus at Colonus ${(-oc).toFixed(1)} years early`);
}
const aAnch = T.PLAYS3.filter(p => p.poet === 'Aeschylus' && p.anchor).map(p => ({ en: p.en, year: p.year, rate: P[p.id].r.free }));
{
  const pe = byEn('Persians').r, se = byEn('Seven against Thebes').r;
  ok(Math.abs(pe.all - se.all) < 0.5 && says('Counting every resolution, Persians and Seven look the same'), `with names counted Persians ${pe.all.toFixed(2)} and Seven ${se.all.toFixed(2)} are level`);
  const loo = T.leaveOneOut(aAnch), rho = T.spearman(aAnch.map(p => p.year), aAnch.map(p => p.rate));
  ok(loo.rmse < 2 && rho < -0.8 && says('the typical miss is under two years'), `Aeschylus, names left out: leave-one-out RMSE ${loo.rmse.toFixed(2)} years, Spearman ${rho.toFixed(3)}`);
  const f = T.ols(aAnch), perYear = -1 / f.b;
  ok(perYear > 0.3 && perYear < 0.4 && says('by roughly one resolution per hundred lines every three years'), `the rate falls ${perYear.toFixed(3)} per 100 lines a year (one every ${(1 / perYear).toFixed(1)} years)`);
  const gap = pe.free - se.free, comb = Math.sqrt(pe.freeSE ** 2 + se.freeSE ** 2);
  ok(gap < 2 * comb && says('smaller than twice its own sampling error'), `Persians minus Seven, names left out: ${gap.toFixed(2)} against twice the combined standard error ${(2 * comb).toFixed(2)}`);
  const early = ['Persians', 'Seven against Thebes', 'Suppliants'].map(n => byEn(n).r.free), ore = ['Agamemnon', 'Libation Bearers', 'Eumenides'].map(n => byEn(n).r.free);
  ok(early.every(r => r >= 8.9 && r < 10.5) && ore.every(r => r >= 5 && r < 6.5) && says('three early plays at about nine or ten resolutions per hundred lines, and the Oresteia at about five or six'), `early three ${early.map(r => r.toFixed(2)).join(', ')}; Oresteia ${ore.map(r => r.toFixed(2)).join(', ')}`);
  // leave one YEAR out (not pre-registered; the page says so)
  const lyo = key => { const pts = T.PLAYS3.filter(p => p.poet === 'Aeschylus' && p.anchor).map(p => ({ year: p.year, rate: key === 'free' ? P[p.id].r.free : P[p.id].r.all }));
    const errs = [...new Set(pts.map(p => p.year))].flatMap(y => { const f = T.ols(pts.filter(p => p.year !== y)); return pts.filter(p => p.year === y).map(p => f.a + f.b * p.rate - y); });
    return Math.sqrt(errs.reduce((s, e) => s + e * e, 0) / errs.length); };
  const a = lyo('free'), b = lyo('all');
  ok(Math.round(a) === 3 && Math.round(b) === 137 && says('gives a typical miss of about three years') && says('it gives about 137 years'), `leave one year out: ${a.toFixed(2)} years names left out, ${b.toFixed(1)} with names`);
}
{
  const per = Object.fromEntries(T.PLAYS3.filter(p => p.poet === 'Aeschylus').map(p => [p.id, P[p.id].sp.map(l => l.free)]));
  const s = T.suppliantsTest(per, 10000, 1);
  ok(Math.round(-s.point) === 468 && Math.round(-s.lo) === 475 && Math.round(-s.hi) === 462 && says('at about 468, and the middle nine tenths of the resamplings run from 475 to 462'), `Suppliants: ${Math.round(-s.point)} BC, 90% ${Math.round(-s.lo)} to ${Math.round(-s.hi)} BC (seed 1)`);
  const n490 = s.years.filter(y => y <= -490).length;
  const n500 = s.years.filter(y => y <= -500).length;
  ok(n490 === 4 && n500 === 0 && says('four of the ten thousand reach it; none reaches 500'), `resamplings reaching 490 BC: ${n490} of 10,000; reaching 500 BC: ${n500}`);
  ok(-s.lo >= 475 && -s.lo < 476 && says("takes in both the usual 463 and most of Scullion's 477 to 470"), `the interval ${(-s.lo).toFixed(1)} to ${(-s.hi).toFixed(1)} BC covers 463 and ${Math.min(477, -s.lo) - 470 > 3 ? 'most' : 'less than most'} of 477 to 470 (${(Math.min(477, -s.lo) - 470).toFixed(1)} of its 7 years)`);
  { const pts = T.PLAYS3.filter(p => p.poet === 'Aeschylus' && p.anchor).map(p => ({ year: p.year, rate: P[p.id].r.all })); const f = T.ols(pts); const y = f.a + f.b * byEn('Suppliants').r.all;
    ok(Math.round(-y) === 465 && says('Counting names as well, the same fit gives 465'), `Suppliants with names counted: ${(-y).toFixed(1)} BC`); }
  const supp = byEn('Suppliants').r.free;
  ok(supp < byEn('Persians').r.free && supp > byEn('Seven against Thebes').r.free && says('The verse puts Suppliants in among Persians and Seven') && says('the count cannot order them'), `Suppliants ${supp.toFixed(2)} lies between Seven ${byEn('Seven against Thebes').r.free.toFixed(2)} and Persians ${byEn('Persians').r.free.toFixed(2)}`);
  const f = T.ols(aAnch), pv = f.a + f.b * byEn('Prometheus Bound').r.free;
  const oreMean = ['Agamemnon', 'Libation Bearers', 'Eumenides'].map(n => byEn(n).r.free);
  ok(Math.round(-pv) === 457 && byEn('Prometheus Bound').r.free >= Math.min(...oreMean) - 0.2 && byEn('Prometheus Bound').r.free <= Math.max(...oreMean) && says('would put it about 457'), `Prometheus Bound ${byEn('Prometheus Bound').r.free.toFixed(2)} (Oresteia ${oreMean.map(r => r.toFixed(2)).join(', ')}), on the line ${Math.round(-pv)} BC`);
}
{
  const S = T.PLAYS3.filter(p => p.poet === 'Sophocles').map(p => ({ en: p.en, r: P[p.id].r })).sort((a, b) => b.r.free - a.r.free);
  const rank = S.findIndex(p => p.en === 'Oedipus at Colonus') + 1;
  ok(rank === 5 && says('Oedipus at Colonus sits in the middle, level with Ajax, Women of Trachis and Oedipus the King'), `Oedipus at Colonus ranks ${rank} of 7: ${S.map(p => p.en + ' ' + p.r.free.toFixed(2)).join(' > ')}`);
  const oc = S.find(p => p.en === 'Oedipus at Colonus').r;
  const level = ['Ajax', 'Women of Trachis', 'Oedipus the King'].every(n => { const r = S.find(p => p.en === n).r; return Math.abs(r.free - oc.free) < 2 * Math.sqrt(r.freeSE ** 2 + oc.freeSE ** 2); });
  ok(level, 'and "level" means within twice the combined standard error of each of those three');
  ok(S[0].en === 'Philoctetes' && S.at(-1).en === 'Electra' && S.at(-2).en === 'Antigone' && says('put Electra and Antigone first and Philoctetes last'), 'read as a clock, Electra and Antigone lowest and Philoctetes highest');
  const per = Object.fromEntries(T.PLAYS3.filter(p => p.poet === 'Sophocles').map(p => [p.id, P[p.id].sp.map(l => l.free)]));
  const ph = T.philoctetesTest(per, 10000, 1);
  ok(ph.p < 0.001 && says('well under once in a thousand shuffles'), `Philoctetes against the other six: +${ph.diff.toFixed(2)} per 100, p = ${ph.p.toFixed(4)} (seed 1)`);
  const others = S.slice(1).map(p => p.r), phr = S[0].r;
  ok(others.every(r => phr.free - r.free > 2 * Math.sqrt(phr.freeSE ** 2 + r.freeSE ** 2)), 'Philoctetes is above every other Sophocles play by more than twice the combined standard error ("well above every other play of his")');
}
ok(says('Prometheus 960 prints τε twice') && MINE.plays.find(p => p.id === 'tlg0085.tlg003').lines.some(([n, t]) => n === '960' && /τε τε/.test(t)), 'the OCR slip the page names is in the text (Prometheus 960, τε τε)');

// ── 2b. the hand counts ───────────────────────────────────────────────────────────
{
  const soph = T.PLAYS3.filter(p => p.poet === 'Sophocles').map(p => p.id);
  const mine = soph.map(id => P[id].r.free), h = soph.map(id => PUB.haigh1896.values[id]), w = soph.map(id => 100 / PUB.wolff.values[id]);
  const rh = T.spearman(mine, h), rw = T.spearman(mine, w);
  ok(rh > 0.85 && rw > 0.85, `Sophocles, names left out, rank agreement with Haigh 1896 ${rh.toFixed(2)} and with Wolff ${rw.toFixed(2)} ("nearly the same order")`);
  const top = a => soph[a.indexOf(Math.max(...a))], lows = a => soph.slice().sort((x, y) => a[soph.indexOf(x)] - a[soph.indexOf(y)]).slice(0, 2).sort().join();
  ok([mine, h, w].every(a => top(a) === 'tlg0011.tlg006' && lows(a) === ['tlg0011.tlg002', 'tlg0011.tlg005'].join()), 'in all three counts Philoctetes is highest and Electra and Antigone are the two lowest');
  const pooled = poet => { const ps = Object.values(P).filter(p => p.poet === poet); return 100 * ps.reduce((s, p) => s + p.r.free * p.r.n / 100, 0) / ps.reduce((s, p) => s + p.r.n, 0); };
  const M = PUB.muller1866.totals, diffs = ['Aeschylus', 'Sophocles', 'Euripides'].map(k => [k, pooled(k), 100 * M[k][0] / M[k][1]]);
  ok(diffs.every(([, a, b]) => Math.abs(a - b) < 1) && says("Müller's totals and this page's agree to within a point in all three poets"), 'against Müller 1866, names left out: ' + diffs.map(([k, a, b]) => `${k} ${a.toFixed(2)} v ${b.toFixed(2)}`).join('; '));
}
{
  const r = AUD.result;
  ok(r.lines === 120 && r.agreeOnCount === 116 && r.agreeOnCountAndNames === 116 && r.namedScanner === 18 && r.resolutionsScanner === 66 && r.notTrimeter.length === 2 && r.disagreements.length === 2 && r.disagreements.every(d => d.scanner - d.reader === 1)
    && says('agree on the count in 116 of 120 lines') && says('would be 64'), 'the blind audit record: 116 of 120 agree, 18 in names each, 2 unscannable to the reader, 2 optional synizeses (66 would be 64)');
  const again = AUD.sample.every(x => { const k = AUD.key.find(k => k.k === x.k); const l = E.scanLine(x.text); return l.trimeter && l.resolutions === k.resolutions && T.nameSplit({ text: x.text, ...l }).named === k.named; });
  ok(again, 'the scanner, run again on the 120 audit lines, gives the key it gave the reader\'s comparison');
}

// ── 3. the text is Perseus's text ─────────────────────────────────────────────────
if (LIVE) {
  const C0 = 'bcc5df0602f3b3fe6fefe1e1d575602a25ab1db6';
  let same = 0;
  for (const p of MINE.plays) {
    const [a, w] = p.id.split('.');
    const xml = await (await fetch(`https://raw.githubusercontent.com/PerseusDL/canonical-greekLit/${C0}/data/${a}/${w}/${p.id}.perseus-grc2.xml`)).text();
    const L = E.readLines(xml).map(l => [l.n, l.text, l.bracketed ? 1 : 0]);
    if (JSON.stringify(L) === JSON.stringify(p.lines)) same++;
  }
  ok(same === 14, `--live: ${same} of 14 plays in data/lines.json match Perseus at ${C0.slice(0, 8)} line for line`);
}

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