#!/usr/bin/env node
// verify.mjs — recompute everything this layer states, and check the page against it.
//
//   node research/every-cell-costs-the-same/verify.mjs
//
// Two jobs, and the second is the one that matters.
//
//   1. RECOMPUTE. Every figure in data.json is derived again here, from the
//      committed corpora and from liblouis, by code that does not import
//      analyze.mjs. If the two disagree, the check goes red.
//
//   2. READ THE PAGE. The prose figures are not compared against a private copy
//      of the answers kept in this file. They are pulled out of the page's own
//      markdown and HTML with regular expressions and matched against the
//      recomputation. Edit a number on the page without changing the world and
//      this turns red; change the world without editing the page and it turns
//      red too. That coupling is the point.
//
// Requires liblouis for the cell counts:
//   sudo apt-get install -y liblouis-bin liblouis-data

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  LETTERS, INTERNATIONAL, AMERICAN, INTL_TIMING, AMERICAN_TIMINGS, FRENCH_SERIES,
  duration, haveLiblouis, louis, dotsOf, selfCheck,
} from './codes.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const CORP = path.join(HERE, 'corpora');
const PAGE = path.join(ROOT, 'public/strata/every-cell-costs-the-same/index.html');
const MD = path.join(ROOT, 'src/content/strata/every-cell-costs-the-same.md');
const DATA_JS = path.join(ROOT, 'public/strata/every-cell-costs-the-same/data.js');

let pass = 0, fail = 0;
const failures = [];
function ok(name, cond, detail) {
  if (cond) { pass++; console.log(`  ✓ ${name}`); }
  else { fail++; failures.push(`${name}${detail ? ' — ' + detail : ''}`); console.log(`  ✗ ${name}${detail ? ' — ' + detail : ''}`); }
}
function near(name, got, want, tol, unit) {
  ok(name, Math.abs(got - want) <= tol, `page says ${want}${unit || ''}, recomputed ${typeof got === 'number' ? Number(got.toFixed(4)) : got}${unit || ''}`);
}
function head(t) { console.log(`\n── ${t} ──`); }

const LOUIS = haveLiblouis();
if (!LOUIS) {
  console.error('✗ liblouis is not installed, and most of this check needs it.');
  console.error('  sudo apt-get install -y liblouis-bin liblouis-data');
  process.exit(2);
}

const pageHtml = fs.readFileSync(PAGE, 'utf8');
const md = fs.readFileSync(MD, 'utf8');

// ── recomputation, independent of analyze.mjs ────────────────────────────────

const alphabet = {};
{
  const cells = [...louis(LETTERS.join(''), 'en-ueb-g1.ctb')];
  LETTERS.forEach((L, i) => { alphabet[L] = dotsOf(cells[i]); });
}
const dots = Object.fromEntries(LETTERS.map(L => [L, alphabet[L].length]));

function letterFreq(slug) {
  const text = fs.readFileSync(path.join(CORP, `${slug}.txt`), 'utf8')
    .normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
  const c = Object.fromEntries(LETTERS.map(L => [L, 0]));
  let n = 0;
  for (const ch of text) if (ch >= 'a' && ch <= 'z') { c[ch]++; n++; }
  return { freq: Object.fromEntries(LETTERS.map(L => [L, c[L] / n])), letters: n };
}
const meanOf = (freq, cost) => LETTERS.reduce((s, L) => s + freq[L] * cost[L], 0);
function bestMean(freq, costArr) {
  const byFreq = [...LETTERS].sort((a, b) => freq[b] - freq[a]);
  const sorted = [...costArr].sort((a, b) => a - b);
  return byFreq.reduce((s, L, i) => s + freq[L] * sorted[i], 0);
}
function spearman(xs, ys) {
  const rank = arr => {
    const idx = arr.map((v, i) => [v, i]).sort((a, b) => a[0] - b[0]);
    const r = new Array(arr.length); let i = 0;
    while (i < idx.length) {
      let j = i; while (j + 1 < idx.length && idx[j + 1][0] === idx[i][0]) j++;
      const avg = (i + j) / 2 + 1;
      for (let k = i; k <= j; k++) r[idx[k][1]] = avg;
      i = j + 1;
    }
    return r;
  };
  const rx = rank(xs), ry = rank(ys), n = xs.length;
  const mx = rx.reduce((a, b) => a + b) / n, my = ry.reduce((a, b) => a + b) / n;
  let num = 0, dx = 0, dy = 0;
  for (let i = 0; i < n; i++) { num += (rx[i] - mx) * (ry[i] - my); dx += (rx[i] - mx) ** 2; dy += (ry[i] - my) ** 2; }
  return num / Math.sqrt(dx * dy);
}

const MOBY = letterFreq('moby-dick');
const intlCost = Object.fromEntries(LETTERS.map(L => [L, duration(INTERNATIONAL[L], INTL_TIMING)]));

// ── 1. the code tables hold their shape ──────────────────────────────────────
head('the code tables');
const problems = selfCheck();
ok('Morse tables pass their structural self-checks', problems.length === 0, problems.join('; '));
ok('the braille alphabet has 26 distinct cells',
  new Set(LETTERS.map(L => alphabet[L].join(''))).size === 26);
ok('the cell has exactly 63 non-empty patterns', (1 << 6) - 1 === 63);

// ── 2. the arithmetic the page describes ─────────────────────────────────────
head('the decades, recomputed');
const eq = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
const plus = (L, extra) => [...new Set([...alphabet[L], ...extra])].sort((a, b) => a - b);
ok('a to j use only dots 1, 2, 4, 5',
  'abcdefghij'.split('').every(L => alphabet[L].every(d => [1, 2, 4, 5].includes(d))));
ok('k to t are a to j plus dot 3',
  'klmnopqrst'.split('').every((L, i) => eq(alphabet[L], plus('abcdefghij'[i], [3]))));
ok('u, v, x, y, z are a to e plus dots 3 and 6',
  'uvxyz'.split('').every((L, i) => eq(alphabet[L], plus('abcde'[i], [3, 6]))));
ok('w is j plus dot 6', eq(alphabet.w, plus('j', [6])));
ok('w is the only English letter in that fourth series',
  LETTERS.filter(L => 'abcdefghij'.split('').some(D => eq(alphabet[L], plus(D, [6])))).join('') === 'w');

head('the French series, against the French table');
{
  const fr = s => [...louis(s, 'fr-bfu-comp6.utb')].map(dotsOf);
  const f1 = fr(FRENCH_SERIES[1].join('')), f3 = fr(FRENCH_SERIES[3].join('')), f4 = fr(FRENCH_SERIES[4].join(''));
  const add = (d, e) => [...new Set([...d, ...e])].sort((a, b) => a - b);
  ok('the French first series matches the English one', f1.every((c, i) => eq(c, alphabet[FRENCH_SERIES[1][i]])));
  ok('the third series has ten members, each first series plus dots 3 and 6',
    f3.length === 10 && f3.every((c, i) => eq(c, add(f1[i], [3, 6]))));
  ok('the fourth series has ten members, each first series plus dot 6',
    f4.length === 10 && f4.every((c, i) => eq(c, add(f1[i], [6]))));
  ok('w is the tenth member of the fourth series', eq(fr('w')[0], add(f1[9], [6])));
  ok('English inherits 5 of the third series and 1 of the fourth',
    FRENCH_SERIES[3].filter(L => LETTERS.includes(L)).length === 5 &&
    FRENCH_SERIES[4].filter(L => LETTERS.includes(L)).length === 1);
}

head('one decade, three jobs');
{
  const LOWER = { 1: 2, 2: 3, 4: 5, 5: 6 };
  const lower = d => d.every(x => LOWER[x]) ? d.map(x => LOWER[x]).sort((a, b) => a - b) : null;
  const digits = [...louis('1234567890', 'en-ueb-g1.ctb')].map(dotsOf);
  ok('UEB digits are the first decade behind one indicator cell',
    digits.length === 11 && digits.slice(1).every((c, i) => eq(c, alphabet['abcdefghij'[i]])));
  ok('the numeric indicator is dots 3456', digits[0].join('') === '3456');
  const marks = [[',', 'a'], [';', 'b'], [':', 'c'], ['.', 'd'], ['!', 'f'], ['?', 'h']];
  for (const [ch, src] of marks) {
    const cells = [...louis('one' + ch + ' two', 'en-ueb-g1.ctb')].map(dotsOf);
    ok(`"${ch}" is the letter ${src} lowered one row`, eq(cells[3], lower(alphabet[src])));
  }
  const dec1 = 'abcdefghij'.split('');
  const occupied = new Set(dec1.map(L => alphabet[L].join('')));
  const shadows = new Set(dec1.map(L => lower(alphabet[L]).join('')));
  ok('the ten letters and their ten shadows do not collide',
    [...occupied].every(k => !shadows.has(k)) && occupied.size === 10 && shadows.size === 10);
  let topFour = 0;
  for (let b = 1; b <= 63; b++) {
    const d = []; for (let i = 0; i < 6; i++) if (b & (1 << i)) d.push(i + 1);
    if (d.every(x => [1, 2, 4, 5].includes(x))) topFour++;
  }
  ok('exactly 15 of the 63 patterns can be lowered at all', topFour === 15);
}

// ── 3. the measurement, and the page's own numbers ───────────────────────────
head('what each code costs, recomputed on Moby-Dick');
const brailleActual = meanOf(MOBY.freq, dots);
const brailleBest = bestMean(MOBY.freq, LETTERS.map(L => dots[L]));
const cheapest26 = [];
for (let b = 1; b <= 63; b++) { let n = 0, x = b; while (x) { n += x & 1; x >>= 1; } cheapest26.push(n); }
const brailleBest63 = bestMean(MOBY.freq, cheapest26.sort((a, b) => a - b).slice(0, 26));
const intlActual = meanOf(MOBY.freq, intlCost);
const intlBest = bestMean(MOBY.freq, LETTERS.map(L => intlCost[L]));

const overBraille = 100 * (brailleActual / brailleBest - 1);
const over63 = 100 * (brailleActual / brailleBest63 - 1);
const overIntl = 100 * (intlActual / intlBest - 1);

console.log(`    braille ${brailleActual.toFixed(4)} dots, best ${brailleBest.toFixed(4)} (+${overBraille.toFixed(2)}%), best of 63 ${brailleBest63.toFixed(4)} (+${over63.toFixed(2)}%)`);
console.log(`    intl Morse ${intlActual.toFixed(4)} units, best ${intlBest.toFixed(4)} (+${overIntl.toFixed(2)}%)`);

// the markdown dek and body are typed by hand: check them against the above
{
  const m1 = md.match(/(\d+)% more dots than the best arrangement/);
  ok('the layer text\'s "% more dots" matches', m1 && Math.abs(Number(m1[1]) - overBraille) < 0.5,
    m1 ? `text says ${m1[1]}%, recomputed ${overBraille.toFixed(2)}%` : 'phrase not found');
  const m2 = md.match(/(\d+)% more than the best twenty-six/);
  ok('the layer text\'s "% more than the best 26 of 63" matches', m2 && Math.abs(Number(m2[1]) - over63) < 0.5,
    m2 ? `text says ${m2[1]}%, recomputed ${over63.toFixed(2)}%` : 'phrase not found');
  const m3 = md.match(/within ([\d.]+)% of the best arrangement of its own/);
  ok('the layer text\'s International Morse gap matches', m3 && Math.abs(Number(m3[1]) - overIntl) < 0.05,
    m3 ? `text says ${m3[1]}%, recomputed ${overIntl.toFixed(2)}%` : 'phrase not found');
}

head('American Morse, one row per cited convention');
const amRuns = AMERICAN_TIMINGS.map(t => {
  const cost = Object.fromEntries(LETTERS.map(L => [L, duration(AMERICAN[L], t)]));
  const a = meanOf(MOBY.freq, cost), b = bestMean(MOBY.freq, LETTERS.map(L => cost[L]));
  return { name: t.name, actual: a, over: 100 * (a / b - 1) };
});
for (const r of amRuns) console.log(`    ${r.name.padEnd(12)} ${r.actual.toFixed(4)} units, +${r.over.toFixed(2)}%`);
ok('every American Morse convention beats International Morse against its own optimum',
  amRuns.every(r => r.over < overIntl), `intl +${overIntl.toFixed(2)}%`);
{
  const lo = Math.min(...amRuns.map(r => r.over)), hi = Math.max(...amRuns.map(r => r.over));
  const m = md.match(/the code Vail actually built, within ([\d.]+)% to ([\d.]+)%/);
  ok('the layer text\'s American Morse range matches',
    m && Math.abs(Number(m[1]) - lo) < 0.05 && Math.abs(Number(m[2]) - hi) < 0.05,
    m ? `text says ${m[1]}% to ${m[2]}%, recomputed ${lo.toFixed(2)}% to ${hi.toFixed(2)}%` : 'phrase not found');
}

head('does each code know its language');
{
  const f = LETTERS.map(L => MOBY.freq[L]);
  const rB = spearman(f, LETTERS.map(L => dots[L]));
  const rI = spearman(f, LETTERS.map(L => intlCost[L]));
  const rA = spearman(f, LETTERS.map(L => duration(AMERICAN[L], AMERICAN_TIMINGS[0])));
  console.log(`    braille ${rB.toFixed(3)} · international ${rI.toFixed(3)} · american ${rA.toFixed(3)}`);
  ok('braille\'s dot count is the weakest of the three', Math.abs(rB) < Math.abs(rI) && Math.abs(rB) < Math.abs(rA));
  ok('both Morse codes correlate negatively and strongly', rI < -0.7 && rA < -0.7);
  const m = md.match(/correlate at rho = (-[\d.]+) and (-[\d.]+)/);
  ok('the layer text\'s two Morse rhos match',
    m && Math.abs(Number(m[1]) - rI) < 0.006 && Math.abs(Number(m[2]) - rA) < 0.006,
    m ? `text says ${m[1]} and ${m[2]}, recomputed ${rI.toFixed(3)} and ${rA.toFixed(3)}` : 'phrase not found');
}

// ── 4. cells, contractions, and the shelf ────────────────────────────────────
head('cells and contractions');
const SAMPLE = 400000;
function sampleCells(slug, lang) {
  const text = fs.readFileSync(path.join(CORP, `${slug}.txt`), 'utf8');
  const start = Math.floor((text.length - SAMPLE) / 2);
  const s = text.length > SAMPLE ? text.slice(start, start + SAMPLE) : text;
  const t1 = lang === 'fr' ? 'fr-bfu-comp6.utb' : 'en-ueb-g1.ctb';
  const t2 = lang === 'fr' ? 'fr-bfu-g2.ctb' : 'en-ueb-g2.ctb';
  const c = str => [...louis(s, str)].filter(ch => ch !== '\n').length;
  const g1 = c(t1), g2 = c(t2);
  return { g1, g2, saved: 100 * (1 - g2 / g1) };
}
const EN = ['moby-dick', 'pride', 'douglass', 'huck-finn', 'holmes'];
const FR = ['les-miserables', 'madame-bovary', 'tour-du-monde'];
const enSaved = EN.map(s => sampleCells(s, 'en').saved);
const frSaved = FR.map(s => sampleCells(s, 'fr').saved);
console.log(`    English ${Math.min(...enSaved).toFixed(1)}% to ${Math.max(...enSaved).toFixed(1)}%`);
console.log(`    French  ${Math.min(...frSaved).toFixed(1)}% to ${Math.max(...frSaved).toFixed(1)}%`);
ok('grade 2 saves roughly a quarter on English literary prose',
  Math.min(...enSaved) > 20 && Math.max(...enSaved) < 27);
ok('the French abrégé saves more than English grade 2', Math.min(...frSaved) > Math.max(...enSaved));
{
  const m = md.match(/contractions take\s*\n?about (\d+)% off English prose and about (\d+)% off French/);
  const enMid = (Math.min(...enSaved) + Math.max(...enSaved)) / 2;
  const frMid = (Math.min(...frSaved) + Math.max(...frSaved)) / 2;
  ok('the layer text\'s contraction percentages match',
    m && Math.abs(Number(m[1]) - enMid) < 1.5 && Math.abs(Number(m[2]) - frMid) < 1.5,
    m ? `text says ${m[1]}% and ${m[2]}%, recomputed midpoints ${enMid.toFixed(1)}% and ${frMid.toFixed(1)}%` : 'phrase not found');
}

// the language guard that caught a real error: the corpora must be the language claimed
head('the corpus is the language it claims to be');
{
  // French uses accented characters at a rate English never reaches. This is a
  // crude but decisive discriminator, and it is here because the first run of
  // this analysis measured an English translation through the French tables.
  const rate = slug => {
    const t = fs.readFileSync(path.join(CORP, `${slug}.txt`), 'utf8').slice(0, 300000);
    const acc = (t.match(/[à-ÿ]/g) || []).length;
    return acc / t.length;
  };
  for (const s of FR) ok(`${s} really is French`, rate(s) > 0.005, `accent rate ${rate(s).toExponential(2)}`);
  for (const s of EN) ok(`${s} really is English`, rate(s) < 0.002, `accent rate ${rate(s).toExponential(2)}`);
}

head('the shelf');
{
  const reflow = txt => txt.replace(/\r\n/g, '\n')
    .split(/\n[ \t]*\n/).map(p => p.replace(/\n/g, ' ').replace(/ {2,}/g, ' ').trim())
    .filter(Boolean).join('\n');
  const moby = reflow(fs.readFileSync(path.join(CORP, 'moby-dick.txt'), 'utf8'));
  const count = table => {
    let n = 0;
    for (let i = 0; i < moby.length; i += 200000)
      n += [...louis(moby.slice(i, i + 200000), table)].filter(c => c !== '\n').length;
    return n;
  };
  const g1 = count('en-ueb-g1.ctb'), g2 = count('en-ueb-g2.ctb');
  console.log(`    Moby-Dick: ${g1.toLocaleString()} grade 1 cells, ${g2.toLocaleString()} grade 2`);
  const m = md.match(/difference between ([\d,]+) and ([\d,]+) cells/);
  const num = s => Number(s.replace(/,/g, ''));
  ok('the layer text\'s two cell counts round to the recomputed ones',
    m && Math.abs(num(m[1]) - g1) < 1500 && Math.abs(num(m[2]) - g2) < 1500,
    m ? `text says ${m[1]} and ${m[2]}, recomputed ${g1} and ${g2}` : 'phrase not found');
  ok('a braille page of 40 by 25 cells puts Moby-Dick near a thousand pages',
    Math.ceil(g2 / 1000) > 900 && Math.ceil(g2 / 1000) < 1000, `${Math.ceil(g2 / 1000)}`);
}

// ── 5. the page ships what the analysis produced ─────────────────────────────
head('the page and the analysis agree');
{
  const data = JSON.parse(fs.readFileSync(path.join(HERE, 'data.json'), 'utf8'));
  near('data.json braille mean dots', brailleActual, data.corpora['moby-dick'].braille.meanDotsActual, 0.0002);
  near('data.json braille best permutation', brailleBest, data.corpora['moby-dick'].braille.meanDotsBestPermutation, 0.0002);
  near('data.json International Morse mean', intlActual, data.corpora['moby-dick'].morseIntl.meanUnitsActual, 0.0002);
  ok('data.js exists and carries the same generation stamp',
    fs.existsSync(DATA_JS) && fs.readFileSync(DATA_JS, 'utf8').includes(JSON.stringify(data.generated)),
    'run: node research/every-cell-costs-the-same/emit-page-data.mjs');

  // the browser translator must land where the tables file says it does
  const tables = JSON.parse(fs.readFileSync(path.join(HERE, 'tables.json'), 'utf8'));
  ok('the browser grade 2 table is within 3% of liblouis on the probe',
    Math.abs(tables.coverage.differencePct) < 3, `${tables.coverage.differencePct}%`);
  ok('the browser word list covers over 90% of running tokens',
    tables.coverage.tokenCoveragePct > 90, `${tables.coverage.tokenCoveragePct}%`);
  // every grade 1 entry in the shipped table is what liblouis gives
  let drift = 0;
  const KEY = tables.key;
  for (const [ch, enc] of Object.entries(tables.g1)) {
    const want = [...louis(ch, 'en-ueb-g1.ctb')].filter(c => c !== '\n')
      .map(c => KEY[c.codePointAt(0) - 0x2800]).join('');
    if (want !== enc) drift++;
  }
  ok('every shipped grade 1 character still matches liblouis', drift === 0, `${drift} drifted`);
}

head('the page states nothing the check has not seen');
{
  // The page's own figures are injected from data.js at run time rather than
  // typed, which is deliberate: there is nothing to drift. What IS typed is the
  // head matter, so check those.
  ok('the page carries its canonical URL',
    pageHtml.includes('https://artwaste.land/strata/every-cell-costs-the-same/'));
  ok('the page quotes ISO 17049 clause 3.1 on vacant dots',
    pageHtml.includes('Vacant dots shall not be neglected'));
  ok('no figure on the page is hard-coded where data.js should fill it',
    !/id="(m-dots|m-c1|m-c2|brl-over|mor-over|am-range)"[^>]*>\s*[0-9]/.test(pageHtml));
  const ids = [...pageHtml.matchAll(/\bid="([a-z0-9-]+)"/g)].map(m => m[1]);
  const referenced = [...pageHtml.matchAll(/\$\('([a-z0-9-]+)'\)/g)].map(m => m[1]);
  const missing = [...new Set(referenced)].filter(i => !ids.includes(i));
  ok('every element the script fills exists in the markup', missing.length === 0, missing.join(', '));
}

// ── report ───────────────────────────────────────────────────────────────────
console.log(`\n${fail === 0 ? '✓' : '✗'} ${pass}/${pass + fail} checks passed`);
if (fail) { console.log('\nfailures:'); for (const f of failures) console.log('  · ' + f); }
process.exit(fail ? 1 : 0);
