// verify-phossy-jaw.mjs: checks what /strata/phossy-jaw/ says against the files it runs on.
//
//   node verify-phossy-jaw.mjs          # the page, its engine and its data
//   node verify-phossy-jaw.mjs --live   # also refetch the Swiss treaty register and the Swedish bill
//
// Needs only Node 18+. Inside the repository it tests the local files (and re-runs the research
// directory's quote check against the saved sources); from an empty directory it downloads
// index.html, engine.mjs and data/*.json from https://artwaste.land, the bytes your browser runs.
// Exit 0 = every check passed. A --live failure means a source has changed since 2026-09-26,
// which is news about the source, not necessarily a fault in the page.

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

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'phossy-jaw';
const localDir = join(here, 'public/strata', slug);
const remote = `https://artwaste.land/strata/${slug}/`;
const LIVE = process.argv.includes('--live');
const local = existsSync(join(localDir, 'engine.mjs'));
async function text(name) { return local ? readFileSync(join(localDir, name), 'utf8') : (await fetch(remote + name)).text(); }
async function mod(name) {
  if (local) return import(join(localDir, name));
  return import('data:text/javascript;base64,' + Buffer.from(await text(name)).toString('base64'));
}
console.error(`files: ${local ? localDir : remote}`);
const E = await mod('engine.mjs');
const html = await text('index.html');
const claims = JSON.parse(await text('data/claims.json'));
const berne = JSON.parse(await text('data/berne.json'));
const article = await text('data/link-21.txt');
const byId = new Map(claims.map((c) => [c.id, c]));

let fails = 0, passes = 0;
const ok = (c, msg) => { if (c) passes++; else fails++; console.log((c ? 'PASS  ' : 'FAIL  ') + msg); };

// ── 1. every src button on the page names a row that exists ────────────────────────
{
  const ids = [...html.matchAll(/data-id="([^"]+)"/g)].map((m) => m[1]);
  const missing = ids.filter((id) => !byId.has(id));
  ok(ids.length >= 60 && missing.length === 0, `${ids.length} source buttons on the page, ${missing.length} naming a missing row${missing.length ? ': ' + missing.join(', ') : ''}`);
  ok(claims.length === 302 && /302 rows/.test(html), `the record holds ${claims.length} rows (page: 302)`);
  ok(claims.every((c) => c.quote && c.source_url && c.confidence), 'every row carries a quote, a source URL and a confidence');
  ok(new Set(claims.map((c) => c.id)).size === claims.length, 'row ids are unique');
}

// ── 2. the engine ───────────────────────────────────────────────────────────────────
{
  ok(E.yearOf('1900') === 1900 && E.yearOf('1900-03') === 1900 + 59 / 365 && E.yearOf('1904-03-01') === 1904 + 60 / 366,
    'yearOf: a year, a month (1900 is not a leap year) and a day in a leap year');
  ok(E.waitYears(1855, '1910-01-01') === 55 && E.waitYears(E.STARTS.sesqui.year, '1872-11-13') === -26, 'waitYears: UK from 1855 is 55.0; Finland from Nov 1898 is -26.0');
  ok(E.median([3, 1, 2]) === 2 && E.median([4, 1, 2, 3]) === 2.5, 'median of odd and even lists');
  ok(E.search('Fines, fined; refined', 'fine').length === 2, 'search matches words that begin with the query, not words that contain it');
}

// ── 3. the wait chart: each row's date is the date its quoted row carries ─────────────
{
  const bad = [];
  for (const r of E.ROWS) {
    const c = byId.get(r.id);
    if (!c) { bad.push(`${r.country}: no row ${r.id}`); continue; }
    for (const id of [r.untilId, ...(r.also || [])].filter(Boolean)) if (!byId.has(id)) bad.push(`${r.country}: no row ${id}`);
    const same = c.date === r.date;
    // the two rows whose date the page reads from the quote, not the date field
    const fromQuote = (r.id === 'bans-59' && /January 1, 1901/.test(c.quote) && r.date === '1901-01-01');
    if (!same && !fromQuote) bad.push(`${r.country}: chart ${r.date}, row ${c.date}`);
    if (r.until && byId.get(r.untilId)?.date !== r.until) bad.push(`${r.country}: repeal date differs`);
  }
  ok(E.ROWS.length === 18 && bad.length === 0, `18 chart rows; every date is its source row's date${bad.length ? ': ' + bad.join('; ') : ''}`);
  const sorted = E.ROWS.every((r, i) => i === 0 || E.yearOf(E.ROWS[i - 1].date) <= E.yearOf(r.date));
  ok(sorted, 'the rows are in date order, as the caption says');
  const neg = E.ROWS.filter((r) => E.waitYears(E.STARTS.sesqui.year, r.date) < 0).map((r) => r.country);
  ok(neg.join() === 'Finland,Denmark,Switzerland,France' && /<span id="neg-count">four<\/span>/.test(html),
    `measured from Nov 1898, the negative rows are ${neg.join(', ')} (page: four; France within a year or two)`);
  const fr = E.ROWS.find((r) => r.country === 'France');
  ok(Math.abs(E.yearOf('1898-11-15') - E.yearOf(fr.range[0])) < 2 && Math.abs(E.yearOf(fr.range[1]) - E.yearOf('1898-11-15')) < 2,
    'France\'s range 1897 to 1899 lies within two years of 15 Nov 1898 at both ends');
  const w = E.ROWS.map((r) => E.waitYears(1855, r.date));
  ok(E.median(w) === 55.5 && Math.max(...w) === 67.5, `from 1855: median ${E.median(w)} years, longest ${Math.max(...w)} (Japan)`);
  const sw = E.ROWS.filter((r) => r.country.startsWith('Sweden')).map((r) => r.date);
  ok(sw.join() === '1900-03-30,1920-02-27', 'Sweden appears twice: sale at home 1900-03-30, manufacture 1920-02-27');
}

// ── 4. the numbers in the prose are in the quotes they cite ─────────────────────────
{
  const pairs = [
    ['us-13', 'less than 5 per cent'], ['us-0', '15'], ['us-10', '3,591'], ['us-10', '314'], ['us-11', '65 per cent'],
    ['us-2', 'Sixteen definite cases'], ['us-5', 'more than 100 cases'], ['us-7', '40 cases'], ['us-7', '15 resulted'], ['us-7', 'June, 1908'],
    ['us-22', 'two cents per one hundred matches'], ['us-33', 'ninety-five per cent'], ['us-46', 'Jan. 28'],
    ['uk-31', '36  cases'], ['uk-32', 'Three'], ['uk-52', '21st December 1908'], ['uk-53', 'January nineteen hundred and ten'],
    ['uk-16', 'Abolition of all fines'], ['uk-27', 'systematic neglect'],
    ['bans-50', 'January  1,  1875'], ['bans-55', 'January 1881'], ['bans-77', '30 mars 1900'], ['bans-79', '27 February 1920'],
    ['bans-22', '10. April'], ['chem-0', '30'], ['chem-2', '260'], ['chem-12', '100'], ['chem-37', 'Dez. 1847'], ['chem-52', '1838'],
    ['extra-2', 'endast ske för export'],
  ];
  const bad = pairs.filter(([id, s]) => !(byId.get(id)?.quote || '').includes(s));
  ok(bad.length === 0, `${pairs.length - bad.length}/${pairs.length} prose numbers found in the quote of the row they cite${bad.length ? ': ' + bad.map((b) => b.join(' ')).join('; ') : ''}`);
  const blockquoted = ['us-14', 'us-15', 'uk-34'].map((id) => [id, byId.get(id).quote.replace(/\s+/g, ' ').replace(/­ /g, '').trim()]);
  const flat = html.replace(/&shy;/g, '').replace(/&ldquo;|&rdquo;/g, '').replace(/<[^>]+>/g, '').replace(/\s+/g, ' ');
  const missing = blockquoted.filter(([, s]) => !flat.includes(s.slice(-40)));
  ok(missing.length === 0, `the quoted English passages on the page end as their sources do (${blockquoted.length} checked)`);
}

// ── 5. the Berne register ────────────────────────────────────────────────────────────
const MONTHS = { Januar: 1, Februar: 2, 'März': 3, April: 4, Mai: 5, Juni: 6, Juli: 7, August: 8, September: 9, Oktober: 10, November: 11, Dezember: 12 };
function reparse(line) { // a second reading of a register line, written separately from the page's builder
  const c = line.split('|').map((s) => s.trim());
  const [, dd, mm] = /^0?(\d+)\. (\S+)$/.exec(c[1]); const [, yy, kind] = /^(\d{4}) ?([BN]?)$/.exec(c[2]);
  return { party: c[0], date: `${yy}-${String(MONTHS[mm]).padStart(2, '0')}-${dd.padStart(2, '0')}`, kind: kind === 'B' ? 'accession' : kind === 'N' ? 'succession' : 'ratification' };
}
{
  const rows = berne.rows;
  const bad = rows.filter((r) => { const p = reparse(r.quote); return p.party !== r.party || p.date !== r.date || p.kind !== r.kind; });
  ok(rows.length === 54 && bad.length === 0, `54 register lines; each re-read from its own quoted line gives the same party, date and kind${bad.length ? ': ' + bad.map((b) => b.party).join(', ') : ''}`);
  const n = (k) => rows.filter((r) => r.kind === k).length;
  ok(n('ratification') === 8 && n('accession') === 33 && n('succession') === 13 && rows.filter((r) => r.territory).length === 6, 'counts: 8 ratifications, 33 accessions, 13 successions, 6 territories');
  const last = [...rows].sort((a, b) => a.date.localeCompare(b.date)).at(-1);
  ok(last.party === 'Montenegro' && last.date === '2007-03-26' && last.kind === 'succession', `last line: ${last.party} ${last.date} (${last.kind})`);
  const firstSucc = rows.filter((r) => r.kind === 'succession').sort((a, b) => a.date.localeCompare(b.date))[0];
  ok(firstSucc.party === 'Irland' && firstSucc.date.startsWith('1926'), 'first succession: Irland, 1926');
  const sw = rows.find((r) => r.party === 'Schweden'), uk = rows.find((r) => r.party === 'Vereinigtes Königreich');
  ok(sw.date === '1920-04-10' && uk.date === '1908-12-28' && uk.kind === 'accession', 'Sweden joined 10 Apr 1920; the United Kingdom acceded 28 Dec 1908 (page says both)');
  ok(!rows.some((r) => /Vereinigte Staaten|USA/.test(r.party)), 'the United States is not in the register (page: never joined)');
  const sig = byId.get('bans-4').quote;
  ok(['Deutsche Kaiser', 'Dänemark', 'Französischen', 'Italien', 'Luxemburg'].every((s) => sig.includes(s)), 'the preamble row names Germany, Denmark, France, Italy, Luxembourg (the Netherlands and Switzerland follow it in the register text)');
}

// ── 6. Besant's article ─────────────────────────────────────────────────────────────
{
  const words = article.trim().split(/\s+/).length;
  ok(words === 1297 && /1,297 words/.test(html), `the article is ${words} words (page: 1,297)`);
  const hits = ['phosph', 'jaw', 'poison', 'necros', 'fumes', 'bone'].map((w) => [w, E.search(article, w).length]);
  ok(hits.every(([, n]) => n === 0), `words beginning phosph, jaw, poison, necros, fumes, bone: ${hits.map(([w, n]) => w + ' ' + n).join(', ')}`);
  ok(/23 per cent/.test(article) && /"burnts"/.test(article) && /accidental firing/.test(article), 'it does contain the 23 per cent dividend, the fine for "burnts" and the accidental firing of frames');
  ok(article.startsWith('AT a meeting of the Fabian Society') && article.trim().endsWith('ANNIE BESANT.'), 'the text runs from the Fabian resolution to the signature');
}

// ── 7. inside the repository: every quote is in its saved source ────────────────────
{
  const dir = join(here, 'research/matches-white-phosphorus');
  if (existsSync(join(dir, 'check-quotes.mjs'))) {
    let out = '';
    try { out = execFileSync(process.execPath, ['check-quotes.mjs'], { cwd: dir, encoding: 'utf8' }); } catch (e) { out = e.stdout || String(e); }
    ok(/302\/302 quotes found verbatim/.test(out), `saved sources: ${out.trim().split('\n').at(-1)}`);
  } else console.log('SKIP  the saved sources are in the project repository, not published; the --live checks below refetch two of them');
}

// ── 8. --live: the two sources the page leans on hardest, refetched ──────────────────
if (LIVE) {
  const reg = await (await fetch(berne.source_url)).text();
  const cells = [...reg.matchAll(/<tr>(.*?)<\/tr>/g)].map((m) => [...m[1].matchAll(/<(?:p|dd)[^>]*>(.*?)<\/(?:p|dd)>/g)].map((x) => x[1].replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').trim()))
    .filter((c) => c.length === 5 && /^\d{4}/.test(c[2]));
  const live = cells.map((c) => reparse(c.join(' | ') + ' |'));
  const diff = berne.rows.filter((r) => !live.some((l) => l.party === r.party && l.date === r.date && l.kind === r.kind));
  ok(live.length === 54 && diff.length === 0, `live register: ${live.length} lines, ${diff.length} differing from the page's${diff.length ? ': ' + diff.map((d) => d.party).join(', ') : ''}`);
  // the endpoint returns XML whose body is escaped HTML; unescape, drop the tags, fold whitespace
  const riks = (await (await fetch('https://data.riksdagen.se/dokument/DH3026/text')).text())
    .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
  const sv = claims.filter((c) => c.set === 'extra');
  const miss = sv.filter((c) => !riks.includes(c.quote.replace(/\s+/g, ' ').trim()));
  ok(miss.length === 0, `live Swedish bill: ${sv.length - miss.length}/${sv.length} quoted passages found (whitespace folded)`);
}

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