#!/usr/bin/env node
// verify-said-twice-checked-once.mjs: checks /strata/said-twice-checked-once/ ("Said Twice, Checked Once").
//
//   node verify-said-twice-checked-once.mjs
//
// Needs only Node 18+. Inside the repository it reads the local page and data; from an empty directory it
// downloads index.html, app.js and data/sweep.json from https://artwaste.land into ./said-twice-checked-once-files/.
// Exit 0 = every check passed.
//
// The page is about checks that find a figure in one place and let every other printed copy say anything.
// So this one checks every copy: each figure the page derives from the sweep is printed inside
// <span data-fig="key">, every such span must equal the value recomputed here from data/sweep.json, and a
// figure of three or more digits may not appear anywhere else in the page's visible text unmarked. The
// computation below is written separately from research/self-reading-verifiers/build-page-data.mjs, which
// fills the page, so the two are not one function agreeing with itself. Inside the repository it also runs
// that script's --check, which ties data/sweep.json to the raw records it was made from.

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

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'said-twice-checked-once';
let dir = join(here, 'public/strata', slug);
const inRepo = existsSync(join(dir, 'data/sweep.json'));
if (!inRepo) {
  dir = resolve(`${slug}-files`); mkdirSync(join(dir, 'data'), { recursive: true });
  for (const f of ['index.html', 'app.js', 'data/sweep.json']) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);
const html = readFileSync(join(dir, 'index.html'), 'utf8');
const app = readFileSync(join(dir, 'app.js'), 'utf8');
const S = JSON.parse(readFileSync(join(dir, 'data/sweep.json'), 'utf8'));

let pass = 0, fail = 0;
function check(name, ok, detail = '') {
  if (ok) pass++; else fail++;
  console.log(`${ok ? 'ok  ' : 'FAIL'} ${name}${detail ? '  (' + detail + ')' : ''}`);
  return ok;
}
const n = (x) => x.toLocaleString('en-US');

// ------------------------------------------------------------------ 1. the figures, recomputed
// baseline rows: [code, exitCode, ms, pages opened, pages printing a verbatim copy]
const B = S.baseline.rows;
const G = B.filter((r) => r[1] === 0);
const own = G.filter((r) => r[3] > 0 && r[3] <= S.wide);
const surveys = G.filter((r) => r[3] > S.wide);
const copyPairs = own.filter((r) => r[4] > 0);
let copyPages = new Set();
for (const p of S.probes) for (const r of p.results) copyPages.add(r.page);
const selfRead = (p) => p.results.reduce((s, r) => s + r.figures.filter((f) => f[1] === 'SELF-READING').length, 0);
const probeAt = (h) => S.probes.find((p) => p.checksAt.startsWith(h));
const before = probeAt('5cdd3bc6'), between = probeAt('5a5bca36');
const after = S.probes.find((p) => p.file === 'probe.json');
const T = S.shadow.results.filter((r) => !r.skipped);
let copies = 0, g = 0, a = 0, o = 0, readFigs = 0, repeated = 0;
for (const r of T) {
  repeated += r.repeated;
  for (const f of r.figures) if (f.occ) { readFigs++; for (const c of f.occ) { copies++; if (c[1] === 'g') g++; else if (c[1] === 'a') a++; else o++; } }
}
let sc = 0, sg = 0;
for (const r of (S.self ? S.self.results : [])) if (!r.skipped) for (const f of r.figures) if (f.occ) for (const c of f.occ) { sc++; if (c[1] === 'g') sg++; }
// the per-page split: pages where every figure printed more than once (at least allMin of them) was read
const per = [];
for (const r of T) { let k = 0, gg = 0, rf = 0; for (const f of r.figures) if (f.occ) { rf++; for (const c of f.occ) { k++; if (c[1] === 'g') gg++; } } if (k) per.push({ r, k, gg, all: rf === r.repeated && r.repeated >= S.shadow.allMin }); }
const allP = per.filter((x) => x.all), restP = per.filter((x) => !x.all);
const sum = (xs, f) => xs.reduce((t, x) => t + f(x), 0);
const sh = per.map((x) => x.gg / x.k).sort((p, q) => p - q), mid = sh.length >> 1;
const med = sh.length % 2 ? sh[mid] : (sh[mid - 1] + sh[mid]) / 2;
const hashed = allP.filter((x) => S.shadow.hashPinned.includes(x.r.code));
const want = {
  files: n(B.length), green: n(G.length), red: n(B.length - G.length), readers: n(own.length), wide: n(surveys.length),
  copyPages: n(copyPages.size), slow: n(own.filter((r) => r[2] > S.shadow.slowMs).length),
  probeBefore: before && n(selfRead(before)), probeBetween: between && n(selfRead(between)), probeAfter: after && n(selfRead(after)),
  pairs: n(T.length), repeated: n(repeated), readFigs: n(readFigs), copies: n(copies), guarded: n(g), anyCopy: n(a), outOfSight: n(o),
  guardedPct: `${(Math.round(1000 * g / copies) / 10).toFixed(1)}%`,
  skippedRun: n(S.shadow.results.length - T.length), pairsRead: n(per.length), pairsUnguarded: n(per.filter((x) => x.gg < x.k).length),
  allReadPages: n(allP.length), allReadCopies: n(sum(allP, (x) => x.k)), hashPinned: n(hashed.length),
  restCopies: n(sum(restP, (x) => x.k)), restGuarded: n(sum(restP, (x) => x.gg)),
  restPct: `${(Math.round(1000 * sum(restP, (x) => x.gg) / sum(restP, (x) => x.k)) / 10).toFixed(1)}%`, medianPct: `${(Math.round(1000 * med) / 10).toFixed(1)}%`, selfCopies: n(sc), selfGuarded: n(sg),
};
check('the sweep ran every verifier file once', new Set(B.map((r) => r[0])).size === B.length, `${B.length} files`);
check('green + not green = every file', G.length + (B.length - G.length) === B.length);
// the control probe (checks as of 5cdd3bc6) was run on every-edge-but-one alone; the other two on every pair
const nPairs = copyPairs.reduce((t, r) => t + r[4], 0);
check('both full probes ran on every (check, page) pair with a verbatim copy; the control on every-edge-but-one', [between, after].every((p) => p && p.results.length === nPairs) && before && before.results.length === 1, `${nPairs} pairs`);
check('three probes: before the 27 September fix, after it, and after tonight\'s', !!(before && between && after));
check('the three tallies of a copy add up to the copies', g + a + o === copies, `${g} + ${a} + ${o} = ${copies}`);
check('the pages counted apart plus the rest are every page with a checked repeated figure', allP.length + restP.length === per.length);
if (inRepo) {
  const pins = allP.filter((x) => /createHash\(\s*['"]sha256['"]\s*\)/.test(readFileSync(join(here, x.r.code), 'utf8'))).map((x) => x.r.code).sort();
  check('the hash-pinned list in sweep.json is what those checks\' sources say', JSON.stringify(pins) === JSON.stringify([...S.shadow.hashPinned].sort()), `${pins.length} of ${allP.length}`);
}

// ------------------------------------------------------------------ 2. every printed copy
const spans = [...html.matchAll(/<span data-fig="([A-Za-z]+)">([^<]*)<\/span>/g)];
const printed = new Set(spans.map((m) => m[1]));
for (const key of Object.keys(want)) check(`the page prints ${key}`, printed.has(key));
for (const [, key, text] of spans) check(`data-fig ${key} = ${want[key]}`, key in want && text === want[key], `page says ${text}`);
// no unmarked copy of a figure of three or more digits anywhere a reader can see
const visible = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ')
  .replace(/<span data-fig="[A-Za-z]+">[^<]*<\/span>/g, ' ').replace(/<[^>]+>/g, ' ').replace(/&[#\w]+;/g, ' ');
for (const [key, v] of Object.entries(want)) {
  const digits = (v || '').replace(/\D/g, '');
  if (digits.length < 3) continue;
  const re = new RegExp(`(?<![\\d.,])${v.replace(/[.*+?^${}()|[\]\\%]/g, '\\$&')}(?![\\d]|[.,]\\d)`);
  check(`${v} (${key}) appears nowhere on the page unmarked`, !re.test(visible));
}

// and the figures the prose quotes from the excerpt: outside the excerpt, every number written with a
// thousands separator must be a marked figure or one the excerpt itself prints, so "33,162" in a sentence
// cannot drift to 33,163 (the first sweep of this check found those prose copies unguarded)
const exBlock = (html.match(/<div class="excerpt" id="excerpt">[\s\S]*?<\/pre>/) || [''])[0];
const exFigs = new Set(exBlock.replace(/<[^>]+>/g, ' ').match(/\d{1,3}(?:,\d{3})+/g) || []);
const outside = html.replace(exBlock, ' ').replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ')
  .replace(/<span data-fig="[A-Za-z]+">[^<]*<\/span>/g, ' ').replace(/<[^>]+>/g, ' ')
  // one exception, in one place: the sentence naming the planted fault, whose number is the plant's own
  .replace(/the sentence saying 33,163 while the transcript still says 33,162/, ' ');
const stray = (outside.match(/(?<![\d.,])\d{1,3}(?:,\d{3})+(?![\d]|[.,]\d)/g) || []).filter((x) => !exFigs.has(x));
check('the plant the page names is the plant every-edge-but-one\'s verifier writes', /the sentence saying 33,163 while the transcript still says 33,162/.test(html) &&
  (!inRepo || readFileSync(join(here, 'research/every-edge-but-one/verify.mjs'), 'utf8').includes("'33,162 avoid all 74', '33,163 avoid all 74'")));
check('the character reference the page names is &frac12;', html.includes('<code>&amp;frac12;</code> is not the figure 12'));
check('every separated number outside the excerpt is marked or printed in the excerpt', exFigs.size >= 5 && stray.length === 0, stray.join(', ') || `${exFigs.size} excerpt figures`);

// ------------------------------------------------------------------ 3. what the prose says about the records
const eebo = (p) => p.results.find((r) => r.code === 'research/every-edge-but-one/verify.mjs');
const selfSet = (p) => new Set(eebo(p).figures.filter((f) => f[1] === 'SELF-READING').map((f) => f[0]));
const bs = selfSet(before), ws = selfSet(between), as = selfSet(after);
check('before the fix, the probe found 33,162 accepted from the transcript', bs.has('33,162'));
check('after the first fix it still did', ws.has('33,162'));
check('after tonight\'s, no figure of every-edge-but-one is accepted from its transcript', as.size === 0);
const gained = [...ws].filter((t) => !bs.has(t));
const readingBefore = Object.fromEntries(eebo(before).figures);
check('the two figures the first fix added were matched inside longer numbers before it (read as unread then)',
  gained.length === ws.size - bs.size && gained.every((t) => readingBefore[t] === 'unread'), gained.join(', '));
const parl = S.probes.every((p) => p.results.filter((r) => /a-parliament-made-like-a-photograph/.test(r.page)).every((r) => r.figures.every((f) => f[1] !== 'SELF-READING')));
check('the other page with a verbatim copy (a-parliament-made-like-a-photograph) has no figure accepted from it', parl);
// the carrots paragraph
const car = T.find((r) => r.code === 'research/carrots-eyesight/verify.mjs' && /do-carrots-improve-eyesight\/index\.html$/.test(r.page));
const kinds = (t) => { const f = car && car.figures.find((x) => x.t === t && x.occ); return f ? f.occ.map((c) => c[1]).sort().join('') : ''; };
check('carrots: "459" is accepted from either of two copies, and a third is out of sight', kinds('459') === 'aao', kinds('459'));
check('carrots: "1940" is guarded in one place and out of sight in six', kinds('1940') === 'goooooo', kinds('1940'));
// outside the repository, read the carrots check where a reader can: its published copy
const carrotsSrc = inRepo ? readFileSync(join(here, 'research/carrots-eyesight/verify.mjs'), 'utf8')
  : await (await fetch('https://artwaste.land/checks/research/carrots-eyesight/verify.mjs')).text();
check('carrots: its check asks for "459 µg RAE" (the regex the page quotes)', /459\\s\*µg\\s\*RAE/.test(carrotsSrc));

// ------------------------------------------------------------------ 4. the excerpt runs the real code
const src = html.match(/<p id="ex-prose">([\s\S]*?)<\/p>/);
const tr = html.match(/<pre id="ex-transcript">([\s\S]*?)<\/pre>/);
const strip = (s) => s.replace(/<[^>]+>/g, '');
check('the excerpt\'s sentence is on the every-edge-but-one page word for word', !!src && (!inRepo || strip(readFileSync(join(here, 'public/strata/every-edge-but-one/index.html'), 'utf8')).includes(strip(src[1]))));
check('the excerpt\'s transcript line is from its verifier\'s printed run', !!tr && (!inRepo || readFileSync(join(here, 'research/every-edge-but-one/verify-output.txt'), 'utf8').includes(strip(tr[1]))));
const G_OLD = "PAGE.replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\\s+/g, ' ')";
check('the toy\'s old check is section G of 26 September: tags stripped, then text.includes(s)', app.includes(`var text = ${G_OLD};`) && app.includes('return !text.includes(s);'));
const CUT = 'var CUT = /<pre\\b[^>]*\\bid="verify-summary"[^>]*>[\\s\\S]*?<\\/pre>/;';
check('the toy\'s new check cuts the transcript with the pattern the verifier now uses, and matches whole numbers', app.includes(CUT) && app.includes("(?<![\\\\d,.])") &&
  (!inRepo || readFileSync(join(here, 'research/every-edge-but-one/verify.mjs'), 'utf8').includes(CUT.slice(4))));

// ------------------------------------------------------------------ 5. the raw records (repository only)
if (inRepo) {
  const r = spawnSync(process.execPath, [join(here, 'research/self-reading-verifiers/build-page-data.mjs'), '--check'], { encoding: 'utf8' });
  check('data/sweep.json and the page match the raw records in research/self-reading-verifiers/', r.status === 0, (r.stdout + r.stderr).trim().split('\n').pop());
}

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