#!/usr/bin/env node
// =============================================================================
// Offline verifier for  /strata/why-damaged-qr-codes-still-scan/
//   "A Third of It Is Already Forgiven — why damaged QR codes still scan"
//
// Recomputes, FROM FIRST PRINCIPLES and the ISO/IEC 18004 constants, every
// quantitative claim the immersive page makes about QR / Reed-Solomon error
// correction, and cross-checks each against the numbers the page actually
// prints (constants + prose extracted from index.html). One PASS/FAIL line per
// claim; exit 0 iff every check passes.
//
// It carries its OWN, independent implementations of:
//   * GF(256) arithmetic with the QR primitive polynomial 0x11d,
//   * a Reed-Solomon encoder and a full errata (errors+erasures) decoder,
//   * the QR byte-mode data encoder + block/interleave layout,
//   * the QR function-pattern geometry (finder / separator / timing / align /
//     format / dark module),
//   * a BCH(15,5) format-information codec.
// Nothing is imported from the page; the page's numbers are only READ BACK and
// compared to what this file derives.
//
// Sources for the reference constants are documented in README.md
// (ISO/IEC 18004:2015/2024; DENSO Wave; Thonky block tables; Wikipedia RS/QR).
//
// Usage:  node research/why-damaged-qr-codes-still-scan/verify-why-damaged-qr-codes-still-scan.mjs
// =============================================================================

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

const HERE = dirname(fileURLToPath(import.meta.url));
const PAGE = join(HERE, '..', '..', 'public', 'strata', 'why-damaged-qr-codes-still-scan', 'index.html');
const html = readFileSync(PAGE, 'utf8');

// ---------------------------------------------------------------------------
// tiny test harness
// ---------------------------------------------------------------------------
let passed = 0, failed = 0;
function check(name, cond, detail) {
  const ok = !!cond;
  if (ok) passed++; else failed++;
  const tag = ok ? 'PASS' : 'FAIL';
  console.log(`${tag}  ${name}${detail ? '   [' + detail + ']' : ''}`);
}
function approx(a, b, eps) { return Math.abs(a - b) <= (eps == null ? 1e-9 : eps); }

// ---------------------------------------------------------------------------
// extract the page's own numbers (constants + normalized prose)
// ---------------------------------------------------------------------------
function evalObjLiteral(src) { return Function('"use strict";return (' + src + ');')(); }
function grabObj(re, label) {
  const m = html.match(re);
  if (!m) throw new Error('could not extract ' + label + ' from index.html');
  return evalObjLiteral(m[1]);
}
const PAGE_SPEC    = grabObj(/var SPEC = (\{[\s\S]*?\n\s*\});/, 'SPEC');
const PAGE_BYTECAP = grabObj(/var BYTECAP = (\{[^;]*\});/, 'BYTECAP');
const PAGE_NOMINAL = grabObj(/var NOMINAL = (\{[^;]*\});/, 'NOMINAL');
const PAGE_ECLBITS = grabObj(/var ECL_BITS = (\{[^;]*\});/, 'ECL_BITS');
const PAGE_TOTALCW = grabObj(/function totalCW\(v\) \{ return \((\{[^}]*\})\)\[v\]/, 'totalCW');
const pagePrim = (html.match(/var PRIM = (0x[0-9a-fA-F]+)/) || [])[1];
const pageGen  = (html.match(/\bGEN = (\d+)/) || [])[1];

// normalized, tag-stripped, entity-decoded prose for substring assertions
const prose = html
  .replace(/<[^>]+>/g, ' ')
  .replace(/&nbsp;/g, ' ')
  .replace(/&times;/g, 'x')
  .replace(/&minus;/g, '-')
  .replace(/&middot;/g, '.')
  .replace(/&le;/g, '<=')
  .replace(/&amp;/g, '&')
  .replace(/&larr;/g, '')
  .replace(/\s+/g, ' ')
  .trim();
const has = (s) => prose.includes(s);

// ===========================================================================
// 1. GF(256), primitive polynomial 0x11d  (the QR / Data Matrix field)
// ===========================================================================
const PRIM = 0x11d, ALPHA = 2;
const EXP = new Array(512).fill(0), LOG = new Array(256).fill(0);
(function () {
  let x = 1;
  for (let i = 0; i < 255; i++) { EXP[i] = x; LOG[x] = i; x <<= 1; if (x & 0x100) x ^= PRIM; }
  for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];
})();
const gmul = (a, b) => (a === 0 || b === 0) ? 0 : EXP[LOG[a] + LOG[b]];
const gdiv = (a, b) => (a === 0) ? 0 : EXP[(LOG[a] + 255 - LOG[b]) % 255];
const ginv = (a) => EXP[255 - LOG[a]];
const gpow = (a, n) => EXP[(((LOG[a] * n) % 255) + 255) % 255];

// prove this really is a field: exp/log inverse, 255-cyclic, all nonzero hit once
(function () {
  const seen = new Set();
  let logInverse = true;
  for (let i = 0; i < 255; i++) { seen.add(EXP[i]); if (LOG[EXP[i]] !== i) logInverse = false; }
  const fieldOK = EXP[0] === 1 && EXP[255] === 1 && logInverse && seen.size === 255 && !seen.has(0);
  check('GF(256) generated by primitive polynomial 0x11d is a valid field (255-cyclic, exp/log inverse, all 255 nonzero elements once)',
    fieldOK);
  check('page uses the same field: PRIM = 0x11d, generator alpha = 2',
    pagePrim && parseInt(pagePrim, 16) === PRIM && +pageGen === ALPHA && has('primitive polynomial 0x11d'),
    `page PRIM=${pagePrim}, GEN=${pageGen}`);
})();

// ===========================================================================
// Reed-Solomon over GF(256): encoder + full errata decoder (independent)
//   polynomials are coefficient arrays, index 0 = highest degree.
// ===========================================================================
function polyMul(p, q) {
  const r = new Array(p.length + q.length - 1).fill(0);
  for (let j = 0; j < q.length; j++) for (let i = 0; i < p.length; i++) r[i + j] ^= gmul(p[i], q[j]);
  return r;
}
function polyAdd(p, q) {
  const r = new Array(Math.max(p.length, q.length)).fill(0);
  for (let i = 0; i < p.length; i++) r[i + r.length - p.length] = p[i];
  for (let i = 0; i < q.length; i++) r[i + r.length - q.length] ^= q[i];
  return r;
}
function polyScale(p, s) { return p.map((c) => gmul(c, s)); }
function polyEval(p, x) { let y = p[0]; for (let i = 1; i < p.length; i++) y = gmul(y, x) ^ p[i]; return y; }
function rsGenPoly(nsym) { let g = [1]; for (let i = 0; i < nsym; i++) g = polyMul(g, [1, gpow(ALPHA, i)]); return g; }
function rsEncode(msg, nsym) {
  const gen = rsGenPoly(nsym), out = msg.concat(new Array(nsym).fill(0));
  for (let i = 0; i < msg.length; i++) { const c = out[i]; if (c) for (let j = 1; j < gen.length; j++) out[i + j] ^= gmul(gen[j], c); }
  return msg.concat(out.slice(msg.length));
}
function rsSynd(msg, nsym) { const s = [0]; for (let i = 0; i < nsym; i++) s.push(polyEval(msg, gpow(ALPHA, i))); return s; }
function rsErrataLocator(coefPos) { let e = [1]; for (const p of coefPos) e = polyMul(e, polyAdd([1], [gpow(ALPHA, p), 0])); return e; }
function rsErrEval(synd, errLoc, nsym) { const m = polyMul(synd, errLoc); return m.slice(m.length - (nsym + 1)); }
function rsForney(synd, pos, nmess) {
  const rev = pos.map((p) => nmess - 1 - p), fs = synd.slice(1);
  for (let i = 0; i < pos.length; i++) { const x = gpow(ALPHA, rev[i]); for (let j = 0; j < fs.length - 1; j++) fs[j] = gmul(fs[j], x) ^ fs[j + 1]; }
  return fs;
}
function rsErrLocatorBM(synd, nsym, eraseCount) {
  let errLoc = [1], oldLoc = [1];
  const shift = (synd.length > nsym) ? synd.length - nsym : 0;
  for (let i = 0; i < nsym - eraseCount; i++) {
    const K = i + shift; let delta = synd[K];
    for (let j = 1; j < errLoc.length; j++) delta ^= gmul(errLoc[errLoc.length - 1 - j], synd[K - j]);
    oldLoc = oldLoc.concat([0]);
    if (delta !== 0) {
      if (oldLoc.length > errLoc.length) { const nl = polyScale(oldLoc, delta); oldLoc = polyScale(errLoc, ginv(delta)); errLoc = nl; }
      errLoc = polyAdd(errLoc, polyScale(oldLoc, delta));
    }
  }
  let k = 0; while (k < errLoc.length && errLoc[k] === 0) k++; errLoc = errLoc.slice(k);
  const errs = errLoc.length - 1;
  if ((errs - eraseCount) * 2 + eraseCount > nsym) throw new Error('too many errors');
  return errLoc;
}
function rsFindErrors(errLoc, nmess) {
  const errs = errLoc.length - 1, pos = [];
  for (let i = 0; i < nmess; i++) if (polyEval(errLoc, gpow(ALPHA, i)) === 0) pos.push(nmess - 1 - i);
  if (pos.length !== errs) throw new Error('chien mismatch');
  return pos;
}
function rsCorrect(msgIn, synd, errPos) {
  const coefPos = errPos.map((p) => msgIn.length - 1 - p);
  const errLoc = rsErrataLocator(coefPos);
  const errEval = rsErrEval(synd.slice().reverse(), errLoc, errLoc.length - 1).reverse();
  const X = coefPos.map((p) => gpow(ALPHA, p));
  const E = new Array(msgIn.length).fill(0);
  for (let i = 0; i < X.length; i++) {
    const Xi = X[i], XiInv = ginv(Xi); let prime = 1;
    for (let j = 0; j < X.length; j++) if (j !== i) prime = gmul(prime, 1 ^ gmul(XiInv, X[j]));
    let y = polyEval(errEval.slice().reverse(), XiInv);
    y = gmul(gpow(Xi, 1), y);
    if (prime === 0) throw new Error('errLocPrime=0');
    E[errPos[i]] = gdiv(y, prime);
  }
  return polyAdd(msgIn, E);
}
// returns {ok, msg} ; erasePos are indices (0 = first codeword) known-missing
function rsDecode(msgIn, nsym, erasePos) {
  erasePos = erasePos || [];
  if (erasePos.length > nsym) return { ok: false };
  const msg = msgIn.slice();
  for (const p of erasePos) msg[p] = 0;
  const synd = rsSynd(msg, nsym);
  if (Math.max(...synd) === 0) return { ok: true, msg };
  try {
    const fs = rsForney(synd, erasePos, msg.length);
    const errLoc = rsErrLocatorBM(fs, nsym, erasePos.length);
    const errPos = rsFindErrors(errLoc.slice().reverse(), msg.length);
    const corrected = rsCorrect(msg, synd, erasePos.concat(errPos));
    if (Math.max(...rsSynd(corrected, nsym)) > 0) return { ok: false };
    return { ok: true, msg: corrected };
  } catch (e) { return { ok: false }; }
}

// ===========================================================================
// 2. ISO/IEC 18004 error-correction block table, Versions 1-4  (REFERENCE).
//    Independent authoritative copy (ISO/IEC 18004 Table 9 / Thonky):
//    per level -> { blocks, data (per block), ec (per block) }.
// ===========================================================================
const REF_SPEC = {
  1: { L: { blocks: 1, data: 19, ec: 7 }, M: { blocks: 1, data: 16, ec: 10 }, Q: { blocks: 1, data: 13, ec: 13 }, H: { blocks: 1, data: 9, ec: 17 } },
  2: { L: { blocks: 1, data: 34, ec: 10 }, M: { blocks: 1, data: 28, ec: 16 }, Q: { blocks: 1, data: 22, ec: 22 }, H: { blocks: 1, data: 16, ec: 28 } },
  3: { L: { blocks: 1, data: 55, ec: 15 }, M: { blocks: 1, data: 44, ec: 26 }, Q: { blocks: 2, data: 17, ec: 18 }, H: { blocks: 2, data: 13, ec: 22 } },
  4: { L: { blocks: 1, data: 80, ec: 20 }, M: { blocks: 2, data: 32, ec: 18 }, Q: { blocks: 2, data: 24, ec: 26 }, H: { blocks: 4, data: 9, ec: 16 } }
};
// ISO/IEC 18004 Table 1: total data-region modules (bits) available per version.
const REF_DATA_MODULES = { 1: 208, 2: 359, 3: 567, 4: 807 };
const LEVELS = ['L', 'M', 'Q', 'H'];

// -- 2a: page SPEC matches the standard cell-for-cell
(function () {
  let ok = true, bad = [];
  for (let v = 1; v <= 4; v++) for (const l of LEVELS) {
    const r = REF_SPEC[v][l], p = PAGE_SPEC[v][l];
    if (!p || p.blocks !== r.blocks || p.data !== r.data || p.ec !== r.ec) { ok = false; bad.push(`V${v}${l}`); }
  }
  check('page block table (Versions 1-4, all 4 EC levels) matches ISO/IEC 18004 cell-for-cell',
    ok, bad.length ? 'mismatch: ' + bad.join(',') : 'all 16 version/level cells match');
})();

// -- 2b: Version 1 headline table  H=9+17, Q=13+13, M=16+10, L=19+7 ; total 26
(function () {
  const v1 = REF_SPEC[1];
  const ok = v1.H.data === 9 && v1.H.ec === 17 && v1.Q.data === 13 && v1.Q.ec === 13 &&
             v1.M.data === 16 && v1.M.ec === 10 && v1.L.data === 19 && v1.L.ec === 7 &&
             (9 + 17) === 26 && (13 + 13) === 26 && (16 + 10) === 26 && (19 + 7) === 26;
  check('Version 1 codeword split (26 total): H 9+17, Q 13+13, M 16+10, L 19+7', ok);
  check('page prose states the Version 1 split "26 total; H = 9+17, Q = 13+13, M = 16+10, L = 19+7"',
    has('26 total') && has('H = 9+17') && has('Q = 13+13') && has('M = 16+10') && has('L = 19+7'));
  check('page prose states the Version 1 split as data+EC "H = 9 data + 17 EC, Q = 13 + 13, M = 16 + 10, L = 19 + 7"',
    has('H = 9 data + 17 EC') && has('Q = 13 + 13') && has('M = 16 + 10') && has('L = 19 + 7'));
})();

// ===========================================================================
// 3. total codewords per version — three independent derivations must agree
//    (a) blocks*(data+ec) from the block table
//    (b) floor(data-region modules / 8), modules from ISO Table 1
//    (c) floor(function-pattern geometry / 8), geometry rebuilt below
// ===========================================================================
function totalFromTable(v) {
  // must be identical across all four levels (an interleave invariant)
  const vals = LEVELS.map((l) => REF_SPEC[v][l].blocks * (REF_SPEC[v][l].data + REF_SPEC[v][l].ec));
  return vals.every((x) => x === vals[0]) ? vals[0] : NaN;
}

// independent QR function-pattern geometry -> count of NON-function (data) modules
function geometryDataModules(v) {
  const n = 17 + 4 * v;
  const F = Array.from({ length: n }, () => new Array(n).fill(false));
  const mark = (r, c) => { if (r >= 0 && c >= 0 && r < n && c < n) F[r][c] = true; };
  // finder + separator: 8x8 at three corners
  for (let r = 0; r < 8; r++) for (let c = 0; c < 8; c++) { mark(r, c); mark(r, n - 1 - c); mark(n - 1 - r, c); }
  // timing patterns
  for (let i = 8; i < n - 8; i++) { mark(6, i); mark(i, 6); }
  // single alignment pattern (Versions 2-4)
  const ac = { 1: null, 2: 18, 3: 22, 4: 26 }[v];
  if (ac != null) for (let dr = -2; dr <= 2; dr++) for (let dc = -2; dc <= 2; dc++) mark(ac + dr, ac + dc);
  // dark module
  mark(4 * v + 9, 8);
  // format information (two copies, 15 modules each, flanking the finders)
  for (let c = 0; c <= 8; c++) if (c !== 6) mark(8, c);
  for (let c = n - 8; c < n; c++) mark(8, c);
  for (let r = 0; r <= 8; r++) if (r !== 6) mark(r, 8);
  for (let r = n - 7; r < n; r++) mark(r, 8);
  let fn = 0; for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) if (F[r][c]) fn++;
  // count the format-info modules alone (dual 15-bit storage claim)
  let fmt = 0, G = Array.from({ length: n }, () => new Array(n).fill(false));
  const mk = (r, c) => { if (r >= 0 && c >= 0 && r < n && c < n && !G[r][c]) { G[r][c] = true; fmt++; } };
  for (let c = 0; c <= 8; c++) if (c !== 6) mk(8, c);
  for (let c = n - 8; c < n; c++) mk(8, c);
  for (let r = 0; r <= 8; r++) if (r !== 6) mk(r, 8);
  for (let r = n - 7; r < n; r++) mk(r, 8);
  return { n, dataModules: n * n - fn, fmtModules: fmt };
}

(function () {
  let ok = true, rows = [];
  for (let v = 1; v <= 4; v++) {
    const fromTable = totalFromTable(v);
    const g = geometryDataModules(v);
    const fromModulesISO = Math.floor(REF_DATA_MODULES[v] / 8);
    const fromGeometry = Math.floor(g.dataModules / 8);
    const page = PAGE_TOTALCW[v];
    const agree = fromTable === fromModulesISO && fromTable === fromGeometry && fromTable === page &&
                  g.dataModules === REF_DATA_MODULES[v];
    if (!agree) ok = false;
    rows.push(`V${v}=${fromTable}`);
  }
  check('total codewords per version derived 3 independent ways (block table / ISO module count / rebuilt geometry) all agree with the page',
    ok, rows.join(' '));
})();

// -- 3b: the geometry proves finder & timing are FUNCTION patterns (outside RS)
(function () {
  // rebuild the function map and assert the three finder squares and the two
  // timing lines are all marked function (i.e. carry no data/EC codeword).
  function funcMap(v) {
    const n = 17 + 4 * v;
    const F = Array.from({ length: n }, () => new Array(n).fill(false));
    const mark = (r, c) => { if (r >= 0 && c >= 0 && r < n && c < n) F[r][c] = true; };
    for (let r = 0; r < 8; r++) for (let c = 0; c < 8; c++) { mark(r, c); mark(r, n - 1 - c); mark(n - 1 - r, c); }
    for (let i = 8; i < n - 8; i++) { mark(6, i); mark(i, 6); }
    return { n, F };
  }
  let ok = true;
  for (let v = 1; v <= 4; v++) {
    const { n, F } = funcMap(v);
    // finder cores
    for (const [tr, tc] of [[0, 0], [0, n - 7], [n - 7, 0]])
      for (let r = 0; r < 7; r++) for (let c = 0; c < 7; c++) if (!F[tr + r][tc + c]) ok = false;
    // timing lines
    for (let i = 8; i < n - 8; i++) { if (!F[6][i] || !F[i][6]) ok = false; }
  }
  check('function-pattern assertion: the three finder squares and both timing lines are reserved (no Reed-Solomon codeword can live there), so damage to them is outside error correction at 0% data damage',
    ok);
  check('page states the sacred-squares mechanism (finder/timing are function patterns outside error correction; destroying one kills the code)',
    has('function patterns') && (has('outside Reed-Solomon') || has('outside error correction')) && has('zero percent'));
})();

// ===========================================================================
// 4. t = floor(EC/2), error ceilings and erasure ceilings (per symbol)
//    error ceiling  = floor(EC/2)*blocks / total      (unknown positions)
//    erasure ceiling = EC*blocks / total = (d-1)/total (known positions)
// ===========================================================================
function tOf(v, l) { return Math.floor(REF_SPEC[v][l].ec / 2); }
function errCeil(v, l) { const s = REF_SPEC[v][l]; return Math.floor(s.ec / 2) * s.blocks; }
function eraCeil(v, l) { const s = REF_SPEC[v][l]; return s.ec * s.blocks; } // = d-1 per block, summed
function pct(num, den) { return +(num / den * 100).toFixed(1); }

// -- 4a: V1 t values  8/6/5/3
(function () {
  const ok = tOf(1, 'H') === 8 && tOf(1, 'Q') === 6 && tOf(1, 'M') === 5 && tOf(1, 'L') === 3;
  check('Version 1 Reed-Solomon correctable-error counts t = floor(EC/2) (what the live decoder forgives): H 8, Q 6, M 5, L 3', ok);
  check('page prose lists "t = 8 / 6 / 5 / 3"', has('t = 8 / 6 / 5 / 3'));
})();

// -- 4b: V1 error-ceiling percentages 30.8 / 23.1 / 19.2 / 11.5
(function () {
  const tot = 26;
  const h = pct(errCeil(1, 'H'), tot), q = pct(errCeil(1, 'Q'), tot), m = pct(errCeil(1, 'M'), tot), l = pct(errCeil(1, 'L'), tot);
  const ok = h === 30.8 && q === 23.1 && m === 19.2 && l === 11.5;
  check('Version 1 Reed-Solomon algebraic error limits floor(EC/2)/26 (what the live decoder forgives): H 30.8%, Q 23.1%, M 19.2%, L 11.5%', ok, `${h}/${q}/${m}/${l}`);
  check('page prose states the headline exact figure "8/26 = 30.8%"', has('8/26 = 30.8%'));
})();

// -- 4b2: the STANDARD's error capacity holds back p misdecode-protection codewords
//    (ISO/IEC 18004:2006 6.5.1: p = 3 in 1-L; p = 2 in 1-M, 2-L; p = 1 in 1-Q, 1-H, 3-L;
//    p = 0 otherwise) and Table 9 prints r = floor((EC-p)/2): 1-L (26,19,2), 1-M (26,16,4),
//    1-Q (26,13,6), 1-H (26,9,8), 2-L (44,34,4). Added by the assay line, 2026-10-18.
(function () {
  const REF_P = { 1: { L: 3, M: 2, Q: 1, H: 1 }, 2: { L: 2, M: 0, Q: 0, H: 0 }, 3: { L: 1, M: 0, Q: 0, H: 0 }, 4: { L: 0, M: 0, Q: 0, H: 0 } };
  const TABLE9_R = { '1L': 2, '1M': 4, '1Q': 6, '1H': 8, '2L': 4, '3L': 7 };
  const isoR = (v, l) => Math.floor((REF_SPEC[v][l].ec - REF_P[v][l]) / 2);
  const okR = Object.entries(TABLE9_R).every(([k, r]) => isoR(+k[0], k[1]) === r);
  check('ISO capacity floor((EC-p)/2) reproduces Table 9 r: 1-L 2, 1-M 4, 1-Q 6, 1-H 8, 2-L 4, 3-L 7', okR);
  const PAGE_P = grabObj(/var MISDECODE_P = (\{[^;]*\});/, 'MISDECODE_P');
  const okP = [1, 2, 3, 4].every((v) => LEVELS.every((l) => PAGE_P[v][l] === REF_P[v][l]));
  check('page MISDECODE_P table matches ISO 6.5.1 for all 16 Version 1-4 cells', okP);
  const pc = LEVELS.slice().reverse().map((l) => pct(isoR(1, l) * REF_SPEC[1][l].blocks, 26));
  check('Version 1 ISO error ceilings r/26: H 30.8%, Q 23.1%, M 15.4%, L 7.7%', pc.join('/') === '30.8/23.1/15.4/7.7', pc.join('/'));
  check('page prose gives the standard\'s figures "t = 8 / 6 / 4 / 2" and "30.8 / 23.1 / 15.4 / 7.7%"', has('its error capacity is t = 8 / 6 / 4 / 2 and the error fractions are 30.8 / 23.1 / 15.4 / 7.7%'));
  check('page no longer calls floor(EC/2)/total the exact or true fraction', !has('exact correctable fraction is floor(EC/2)/total') && !has('true per-symbol error fraction is floor(EC/2)/total'));
})();

// -- 4c: the "up to 30%" headline = DENSO nominal H, exact 30.8%
(function () {
  const exactH = pct(errCeil(1, 'H'), 26);
  const ok = PAGE_NOMINAL.H === 30 && exactH === 30.8 && Math.abs(exactH - 30) < 1.5;
  check('"up to 30%" headline: DENSO nominal H = 30% is the rounding of the exact Version-1-H error ceiling 30.8%',
    ok, `nominal=${PAGE_NOMINAL.H} exact=${exactH}`);
  check('page title/description carry the "up to 30%" headline', /30\s*%/.test(html) && (has('up to about 30 percent') || has('Up to 30%')));
})();

// -- 4d: erasure ceiling = d-1 = EC (NOT 2t); V1 H = 17/26 = 65.4%; ~2x error ceiling
(function () {
  const tot = 26;
  const eraH = pct(eraCeil(1, 'H'), tot);
  const okNum = eraCeil(1, 'H') === 17 && eraH === 65.4;
  check('Version 1 H ERASURE ceiling = d-1 = EC = 17 codewords = 17/26 = 65.4%', okNum, `${eraCeil(1, 'H')}/26 = ${eraH}%`);
  // the correct ceiling is d-1 = EC, and for ODD EC this is NOT 2*floor(EC/2)
  const oddLevels = [];
  for (let v = 1; v <= 4; v++) for (const l of LEVELS) if (REF_SPEC[v][l].ec % 2 === 1) oddLevels.push(`V${v}${l}`);
  const eraNe2t = REF_SPEC[1].H.ec !== 2 * tOf(1, 'H'); // 17 !== 16
  check('erasure ceiling is d-1 = EC, which is strictly greater than 2t for odd-EC levels (e.g. V1 H: 17 vs 2t=16) — so the page must NOT claim "2t = d-1"',
    eraNe2t && oddLevels.length > 0, 'odd-EC levels: ' + oddLevels.join(','));
  check('erasure ceiling is about twice the error ceiling (V1 H: 17 vs 8, ratio ' + (17 / 8).toFixed(2) + 'x), matching the "roughly doubles" narrative',
    eraCeil(1, 'H') > errCeil(1, 'H') && Math.abs(eraCeil(1, 'H') / errCeil(1, 'H') - 2) < 0.3);
  check('page prose states "17/26 = 65.4%" for the erasure ceiling', has('17/26 = 65.4%'));
  check('page uses the CORRECT errata bound "2 x (errors) + (erasures) <= d - 1" and no longer prints the false identity "2t = d-1"',
    has('2 x (errors) + (erasures) <= d - 1') && !prose.includes('2t = d'));
})();

// -- 4e: consistency of every printed error/erasure percentage across V1-4
(function () {
  let ok = true, rows = [];
  for (let v = 1; v <= 4; v++) for (const l of LEVELS) {
    const tot = PAGE_TOTALCW[v];
    const e = pct(errCeil(v, l), tot), s = pct(eraCeil(v, l), tot);
    // erasure ceiling must always be >= error ceiling, and error ceiling < 50%
    if (!(s >= e && e < 50 && s <= 100)) ok = false;
  }
  check('for all Versions 1-4 / all levels: error ceiling < 50%, erasure ceiling >= error ceiling, both well-formed', ok);
})();

// ===========================================================================
// 5. DENSO nominal restore percentages L 7 / M 15 / Q 25 / H 30
// ===========================================================================
(function () {
  const DENSO = { L: 7, M: 15, Q: 25, H: 30 };
  const ok = LEVELS.every((l) => PAGE_NOMINAL[l] === DENSO[l]);
  check('page NOMINAL restore percentages match DENSO Wave: L 7, M 15, Q 25, H 30', ok);
  check('page prose lists "L 7% / M 15% / Q 25% / H 30%"', has('L 7% / M 15% / Q 25% / H 30%'));
})();

// ===========================================================================
// 6. byte-mode data capacity derived from first principles
//    cap_bytes = floor((total_data_codewords*8 - 4 - 8) / 8)
//      4 bits mode indicator + 8 bits char-count indicator (byte mode, V1-9)
// ===========================================================================
(function () {
  let ok = true, bad = [];
  for (let v = 1; v <= 4; v++) for (const l of LEVELS) {
    const s = REF_SPEC[v][l], totalData = s.blocks * s.data;
    const derived = Math.floor((totalData * 8 - 4 - 8) / 8);
    if (derived !== PAGE_BYTECAP[v][l]) { ok = false; bad.push(`V${v}${l}:${derived}!=${PAGE_BYTECAP[v][l]}`); }
  }
  check('byte-mode capacities derived as floor((dataCW*8 - 12)/8) match the page BYTECAP table (all 16 cells)',
    ok, bad.length ? bad.join(' ') : 'all match');
})();

// ===========================================================================
// QR byte-mode encoder + block/interleave (independent) for round-trips
// ===========================================================================
function toBytes(text) { return Array.from(Buffer.from(text, 'utf8')); }
function encodeDataCW(bytes, v, l) {
  const totalData = REF_SPEC[v][l].blocks * REF_SPEC[v][l].data, capBits = totalData * 8, bits = [];
  const push = (val, n) => { for (let i = n - 1; i >= 0; i--) bits.push((val >> i) & 1); };
  push(0x4, 4); push(bytes.length, 8);
  for (const b of bytes) push(b, 8);
  for (let t = 0; t < 4 && bits.length < capBits; t++) bits.push(0);
  while (bits.length % 8) bits.push(0);
  const pads = [0xEC, 0x11]; let pi = 0;
  while (bits.length < capBits) { push(pads[pi++ % 2], 8); }
  const cw = [];
  for (let k = 0; k < bits.length; k += 8) { let b = 0; for (let j = 0; j < 8; j++) b = (b << 1) | bits[k + j]; cw.push(b); }
  return cw;
}
function buildInterleaved(dataCW, v, l) {
  const s = REF_SPEC[v][l], dataBlocks = [], ecBlocks = [];
  for (let b = 0; b < s.blocks; b++) {
    const blk = dataCW.slice(b * s.data, (b + 1) * s.data);
    dataBlocks.push(blk); ecBlocks.push(rsEncode(blk, s.ec).slice(s.data));
  }
  const inter = [];
  for (let i = 0; i < s.data; i++) for (let b = 0; b < s.blocks; b++) inter.push(dataBlocks[b][i]);
  for (let i = 0; i < s.ec; i++) for (let b = 0; b < s.blocks; b++) inter.push(ecBlocks[b][i]);
  return inter;
}
function deinterleaveDecode(inter, v, l, damagedGlobalIdx, mode) {
  const s = REF_SPEC[v][l], nb = s.blocks;
  const blocks = []; for (let b = 0; b < nb; b++) blocks.push({ cw: [], gi: [] });
  let gi = 0;
  for (let i = 0; i < s.data; i++) for (let b = 0; b < nb; b++) { blocks[b].cw.push(inter[gi]); blocks[b].gi.push(gi); gi++; }
  for (let i = 0; i < s.ec; i++) for (let b = 0; b < nb; b++) { blocks[b].cw.push(inter[gi]); blocks[b].gi.push(gi); gi++; }
  const dmg = new Set(damagedGlobalIdx || []);
  const recoveredData = [];
  for (let b = 0; b < nb; b++) {
    const erasures = [];
    for (let i = 0; i < blocks[b].gi.length; i++) if (dmg.has(blocks[b].gi[i])) erasures.push(i);
    const res = (mode === 'erasure') ? rsDecode(blocks[b].cw, s.ec, erasures) : rsDecode(blocks[b].cw, s.ec, []);
    if (!res.ok) return { ok: false, failBlock: b };
    for (let i = 0; i < s.data; i++) recoveredData[b * s.data + i] = res.msg[i];
  }
  return { ok: true, data: recoveredData };
}
function parsePayload(dataCW) {
  const bits = []; for (const c of dataCW) for (let q = 7; q >= 0; q--) bits.push((c >> q) & 1);
  let p = 0; const rd = (n) => { let v = 0; for (let j = 0; j < n; j++) v = (v << 1) | bits[p++]; return v; };
  if (rd(4) !== 0x4) return null;
  const count = rd(8), by = []; for (let i = 0; i < count; i++) by.push(rd(8));
  return Buffer.from(by).toString('utf8');
}
function autoVersion(bytes, l) { for (let v = 1; v <= 4; v++) if (bytes.length <= PAGE_BYTECAP[v][l]) return v; return 4; }

// ===========================================================================
// 7. round-trip: encode a payload and decode it back with zero damage
// ===========================================================================
(function () {
  // the page's default: payload "artwaste.land" at level H
  const text = 'artwaste.land', l = 'H';
  const bytes = toBytes(text), v = autoVersion(bytes, l);
  const inter = buildInterleaved(encodeDataCW(bytes, v, l), v, l);
  const dec = deinterleaveDecode(inter, v, l, [], 'error');
  const payload = dec.ok ? parsePayload(dec.data) : null;
  check('round-trip (the page default): encode "artwaste.land" at level H -> Version 2 -> decode recovers the exact payload',
    v === 2 && dec.ok && payload === text, `version=${v} payload=${JSON.stringify(payload)}`);
})();

(function () {
  // multi-block symbol (Version 4 H = 4 interleaved blocks) exercises interleave
  const text = 'artificial.wasteland/qr!!', l = 'H', v = 4;
  const bytes = toBytes(text);
  const inter = buildInterleaved(encodeDataCW(bytes, v, l), v, l);
  const dec = deinterleaveDecode(inter, v, l, [], 'error');
  const payload = dec.ok ? parsePayload(dec.data) : null;
  check('round-trip through a 4-block interleaved symbol (Version 4 H) recovers the payload exactly',
    REF_SPEC[4].H.blocks === 4 && dec.ok && payload === text, `blocks=${REF_SPEC[4].H.blocks} payload=${JSON.stringify(payload)}`);
})();

// ===========================================================================
// 8. ERROR ceiling empirically: exactly t errors recover, t+1 fails.
//    (single-block Version 1, every EC level; positions UNKNOWN to decoder)
// ===========================================================================
(function () {
  let ok = true, rows = [];
  for (const l of LEVELS) {
    const s = REF_SPEC[1][l], t = Math.floor(s.ec / 2);
    const data = Array.from({ length: s.data }, (_, i) => (i * 37 + 11) & 0xff);
    const code = rsEncode(data, s.ec);
    const flip = (arr, i) => { arr[i] ^= 0x9d; if (arr[i] === code[i]) arr[i] ^= 0x33; }; // guarantee a real change
    // exactly t errors at fixed positions -> must recover
    const eT = code.slice(); for (let i = 0; i < t; i++) flip(eT, i);
    const rT = rsDecode(eT, s.ec, []);
    const okT = rT.ok && rT.msg.slice(0, s.data).every((x, i) => x === data[i]);
    // t+1 errors -> must NOT reproduce the original message
    const eT1 = code.slice(); for (let i = 0; i <= t; i++) flip(eT1, i);
    const rT1 = rsDecode(eT1, s.ec, []);
    const failT1 = !(rT1.ok && rT1.msg.slice(0, s.data).every((x, i) => x === data[i]));
    if (!(okT && failT1)) ok = false;
    rows.push(`${l}:t=${t}`);
  }
  check('ERROR ceiling holds for every Version-1 level: exactly t = floor(EC/2) unknown-position errors are corrected; t+1 is not',
    ok, rows.join(' '));
})();

// ===========================================================================
// 9. ERASURE ceiling empirically: exactly EC (= d-1) erasures recover, EC+1 fails.
// ===========================================================================
(function () {
  let ok = true, rows = [];
  for (const l of LEVELS) {
    const s = REF_SPEC[1][l], EC = s.ec;
    const data = Array.from({ length: s.data }, (_, i) => (i * 53 + 7) & 0xff);
    const code = rsEncode(data, s.ec);
    // EC erasures at the first EC positions
    const posEC = Array.from({ length: EC }, (_, i) => i);
    const dmgEC = code.slice(); for (const p of posEC) dmgEC[p] ^= 0xff;
    const rEC = rsDecode(dmgEC, s.ec, posEC);
    const okEC = rEC.ok && rEC.msg.slice(0, s.data).every((x, i) => x === data[i]);
    // EC+1 erasures -> exceeds d-1, must fail (decoder rejects > nsym erasures)
    const posEC1 = Array.from({ length: EC + 1 }, (_, i) => i);
    const rEC1 = rsDecode(code.slice(), s.ec, posEC1);
    const failEC1 = !rEC1.ok;
    if (!(okEC && failEC1)) ok = false;
    rows.push(`${l}:EC=${EC}`);
  }
  check('ERASURE ceiling holds for every Version-1 level: exactly EC = d-1 known-position erasures are corrected; EC+1 is not',
    ok, rows.join(' '));
})();

// ===========================================================================
// 10. mixed errata bound  2*errors + erasures <= d-1  (V1 H, d-1 = 17)
// ===========================================================================
(function () {
  const s = REF_SPEC[1].H, EC = s.ec; // 17
  const data = Array.from({ length: s.data }, (_, i) => (i * 29 + 3) & 0xff);
  const code = rsEncode(data, s.ec);
  function trial(e, sN) {
    // sN erasures (known) at positions [0..sN), then e errors (unknown) at [sN..sN+e)
    const recv = code.slice(), erq = [];
    for (let i = 0; i < sN; i++) { recv[i] ^= 0xa5; erq.push(i); }
    for (let i = 0; i < e; i++) { const p = sN + i; recv[p] ^= 0x9d; if (recv[p] === code[p]) recv[p] ^= 0x11; }
    const r = rsDecode(recv, s.ec, erq);
    return r.ok && r.msg.slice(0, s.data).every((x, i) => x === data[i]);
  }
  // 2e + s = 17 (on the bound) should recover; = 18 (over) should not
  const onBound = trial(4, 9);   // 8 + 9 = 17
  const overBound = !trial(5, 8); // 10 + 8 = 18
  check('mixed errata bound: 2*errors + erasures = d-1 = 17 recovers (e=4,s=9); = 18 does not (e=5,s=8)',
    onBound && overBound, `onBound=${onBound} overFails=${overBound}`);
})();

// ===========================================================================
// 11. BCH(15,5) format-information code
//     generator 0x537, mask 0x5412, minimum distance 7 -> corrects 3, dual copy
// ===========================================================================
function bchEncode(data5) { let rem = data5; for (let i = 0; i < 10; i++) rem = (rem << 1) ^ (((rem >> 9) & 1) * 0x537); return (data5 << 10) | rem; }
function bchEncodeMasked(data5) { return bchEncode(data5) ^ 0x5412; }
function popcount(x) { let c = 0; while (x) { c += x & 1; x >>>= 1; } return c; }
function bchDecodeMasked(word15) {
  let best = -1, bd = 99;
  for (let d = 0; d < 32; d++) { const dist = popcount((bchEncodeMasked(d) ^ word15) & 0x7fff); if (dist < bd) { bd = dist; best = d; } }
  return bd > 3 ? null : { data5: best, dist: bd };
}
(function () {
  // brute-force minimum distance over the 32 codewords (masking is a constant
  // offset, so it does not change pairwise distances)
  let dmin = 99;
  for (let a = 0; a < 32; a++) for (let b = a + 1; b < 32; b++) { const w = popcount(bchEncode(a) ^ bchEncode(b)); if (w < dmin) dmin = w; }
  const corrects = Math.floor((dmin - 1) / 2);
  check('BCH(15,5) format code: brute-forced minimum distance = 7, so it corrects floor((7-1)/2) = 3 bit errors',
    dmin === 7 && corrects === 3, `dmin=${dmin} corrects=${corrects}`);
  check('page prose states BCH(15,5), minimum distance 7, corrects up to 3, generator 0x537, mask 0x5412',
    has('BCH(15,5)') && has('minimum distance 7') && has('corrects up to 3') && has('0x537') && has('0x5412'));

  // masked round-trip: every level/mask recovers under <=3 flips; a 4-flip can misread
  let rtOK = true, foundMisread = false;
  for (let data5 = 0; data5 < 32; data5++) {
    const word = bchEncodeMasked(data5);
    // all single/double/triple flips recover
    for (let a = 0; a < 15 && rtOK; a++) {
      const w1 = word ^ (1 << a); if (!bchDecodeMasked(w1) || bchDecodeMasked(w1).data5 !== data5) rtOK = false;
      for (let b = a + 1; b < 15 && rtOK; b++) {
        const w2 = w1 ^ (1 << b); if (!bchDecodeMasked(w2) || bchDecodeMasked(w2).data5 !== data5) rtOK = false;
        for (let c = b + 1; c < 15 && rtOK; c++) {
          const w3 = w2 ^ (1 << c); const d3 = bchDecodeMasked(w3); if (!d3 || d3.data5 !== data5) rtOK = false;
        }
      }
    }
  }
  // exhibit a 4-bit error that is mis-decoded (distance 7 => some 4-flip lands within 3 of a wrong word)
  outer:
  for (let data5 = 0; data5 < 32; data5++) {
    const word = bchEncodeMasked(data5);
    for (let a = 0; a < 15; a++) for (let b = a + 1; b < 15; b++) for (let c = b + 1; c < 15; c++) for (let e = c + 1; e < 15; e++) {
      const w = word ^ (1 << a) ^ (1 << b) ^ (1 << c) ^ (1 << e);
      const d = bchDecodeMasked(w);
      if (d && d.data5 !== data5) { foundMisread = true; break outer; }
    }
  }
  check('BCH(15,5) masked round-trip: EC level recovers under any <=3 flipped bits (all 32 words x all 1/2/3-flips); some 4-flip misreads',
    rtOK && foundMisread, `recoverAll<=3=${rtOK} misreadAt4=${foundMisread}`);

  // dual storage: geometry reserves two 15-module format copies
  let dualOK = true;
  for (let v = 1; v <= 4; v++) if (geometryDataModules(v).fmtModules !== 30) dualOK = false;
  check('format information is stored TWICE: geometry reserves 30 = 2 x 15 format modules per symbol',
    dualOK && has('stored twice') || (dualOK && has('stored a second time')), 'fmtModules=30');

  // the page's ECL_BITS mapping matches the standard (L=01, M=00, Q=11, H=10)
  const ok = PAGE_ECLBITS.L === 1 && PAGE_ECLBITS.M === 0 && PAGE_ECLBITS.Q === 3 && PAGE_ECLBITS.H === 2;
  check('page format-info EC-level bits match the standard (L=01, M=00, Q=11, H=10)', ok);
})();

// ===========================================================================
// summary
// ===========================================================================
console.log('');
console.log(`${passed}/${passed + failed} checks passed.`);
if (failed > 0) { console.error(`FAILED: ${failed} check(s) did not reproduce the page's numbers.`); process.exit(1); }
console.log('All quantitative claims on the page reproduce from first principles / the QR spec. Exit 0.');
process.exit(0);
