#!/usr/bin/env node
// verify.mjs — the offline check behind "The Grey That Isn't There"
// (/strata/the-grey-that-isnt-there/). Reproduces every dithering algorithm
// the page uses, in plain Node, and checks the one honest claim the whole
// stratum rests on: a good ditherer chooses black-and-white dots so that the
// LOCAL AVERAGE tone is preserved — which is why your eye, an averaging
// instrument, rebuilds a photograph from nothing but dots.
//
// Run: node research/dithering/verify.mjs
// No dependencies. Images are Float64 arrays in [0,1], row-major.
'use strict';

let PASS = 0, FAIL = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function check(name, cond, detail) {
  if (cond) { PASS++; console.log(`  ok   ${name}${detail ? '  —  ' + detail : ''}`); }
  else { FAIL++; console.log(`  FAIL ${name}${detail ? '  —  ' + detail : ''}`); }
}

// ---------------------------------------------------------------- test images
function flat(w, h, v) { const a = new Float64Array(w * h); a.fill(v); return { w, h, d: a }; }
function ramp(w, h) { // horizontal 0..1 ramp
  const a = new Float64Array(w * h);
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) a[y * w + x] = x / (w - 1);
  return { w, h, d: a };
}
function sphere(w, h) { // a lambert-shaded sphere on a soft gradient — smooth tone, no banding
  const a = new Float64Array(w * h);
  const cx = w * 0.5, cy = h * 0.5, R = Math.min(w, h) * 0.42;
  const lx = -0.5, ly = -0.6, lz = 0.62; const ll = Math.hypot(lx, ly, lz);
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
    let v = 0.16 + 0.12 * (y / h);                    // background gradient
    const dx = (x - cx) / R, dy = (y - cy) / R, r2 = dx * dx + dy * dy;
    if (r2 <= 1) {
      const nz = Math.sqrt(1 - r2);
      let diff = (dx * lx + dy * ly + nz * lz) / ll;   // n·l
      diff = Math.max(0, diff);
      v = 0.06 + 0.9 * diff * diff;                    // shading + a touch of ambient
    }
    a[y * w + x] = Math.min(1, Math.max(0, v));
  }
  return { w, h, d: a };
}
const meanOf = (img) => { let s = 0; for (let i = 0; i < img.d.length; i++) s += img.d[i]; return s / img.d.length; };

// -------------------------------------------------------------- the quantizers
// Each returns a NEW image whose pixels are exactly 0 or 1.
function threshold(img) {
  const o = new Float64Array(img.d.length);
  for (let i = 0; i < o.length; i++) o[i] = img.d[i] >= 0.5 ? 1 : 0;
  return { w: img.w, h: img.h, d: o };
}

// Bayer / ordered dither. bayerMatrix(n) returns an n×n matrix that is a
// permutation of 0..n*n-1, built by the classic recursion.
function bayerMatrix(n) {
  if (n === 1) return [[0]];
  const half = bayerMatrix(n / 2), m = [];
  for (let y = 0; y < n; y++) m.push(new Array(n).fill(0));
  const q = half.length;
  for (let y = 0; y < q; y++) for (let x = 0; x < q; x++) {
    const b = half[y][x];
    m[y][x]           = 4 * b + 0;
    m[y][x + q]       = 4 * b + 2;
    m[y + q][x]       = 4 * b + 3;
    m[y + q][x + q]   = 4 * b + 1;
  }
  return m;
}
function ordered(img, n) {
  const M = bayerMatrix(n), N = n * n, o = new Float64Array(img.d.length);
  for (let y = 0; y < img.h; y++) for (let x = 0; x < img.w; x++) {
    const t = (M[y % n][x % n] + 0.5) / N;             // threshold in (0,1)
    o[y * img.w + x] = img.d[y * img.w + x] > t ? 1 : 0;
  }
  return { w: img.w, h: img.h, d: o };
}

// Floyd–Steinberg error diffusion. Coefficients, as fractions of 16:
//   right 7 · below-left 3 · below 5 · below-right 1   (sum 16, left→right, top→bottom)
const FS = [[1, 0, 7 / 16], [-1, 1, 3 / 16], [0, 1, 5 / 16], [1, 1, 1 / 16]];
// Atkinson (Bill Atkinson, Mac 1984): 1/8 to each of six neighbours — only 6/8
// of the error is propagated, which lifts local contrast.
const ATK = [[1, 0, 1 / 8], [2, 0, 1 / 8], [-1, 1, 1 / 8], [0, 1, 1 / 8], [1, 1, 1 / 8], [0, 2, 1 / 8]];
function diffuse(img, stencil) {
  const w = img.w, h = img.h, buf = Float64Array.from(img.d), o = new Float64Array(w * h);
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
    const i = y * w + x, old = buf[i], nw = old >= 0.5 ? 1 : 0, err = old - nw;
    o[i] = nw;
    for (const [dx, dy, k] of stencil) {
      const nx = x + dx, ny = y + dy;
      if (nx >= 0 && nx < w && ny >= 0 && ny < h) buf[ny * w + nx] += err * k;
    }
  }
  return { w, h, d: o };
}
const floydSteinberg = (img) => diffuse(img, FS);
const atkinson = (img) => diffuse(img, ATK);

// ------------------------------------------------------------------ blur (eye)
// Separable Gaussian with reflected edges. sigma in pixels.
function gaussBlur(img, sigma) {
  const rad = Math.max(1, Math.ceil(sigma * 3));
  const k = []; let sum = 0;
  for (let i = -rad; i <= rad; i++) { const v = Math.exp(-(i * i) / (2 * sigma * sigma)); k.push(v); sum += v; }
  for (let i = 0; i < k.length; i++) k[i] /= sum;
  const w = img.w, h = img.h;
  const refl = (i, n) => { i = Math.abs(i); if (i >= n) i = 2 * n - 2 - i; return Math.max(0, Math.min(n - 1, i)); };
  const tmp = new Float64Array(w * h), out = new Float64Array(w * h);
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
    let s = 0; for (let j = -rad; j <= rad; j++) s += img.d[y * w + refl(x + j, w)] * k[j + rad];
    tmp[y * w + x] = s;
  }
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
    let s = 0; for (let j = -rad; j <= rad; j++) s += tmp[refl(y + j, h) * w + x] * k[j + rad];
    out[y * w + x] = s;
  }
  return { w, h, d: out };
}
function mae(a, b) { let s = 0; for (let i = 0; i < a.d.length; i++) s += Math.abs(a.d[i] - b.d[i]); return s / a.d.length; }

// ================================================================ CHECKS
console.log('\nThe Grey That Isn\'t There — offline verifier\n');

// A · Coefficient bookkeeping ------------------------------------------------
console.log('A · Error-diffusion coefficients are exactly conservative');
const fsSum = FS.reduce((s, c) => s + c[2], 0);
check('Floyd–Steinberg weights sum to 1 (7+3+5+1 = 16 sixteenths)', approx(fsSum, 1, 1e-12), `Σ = ${fsSum}`);
const atkSum = ATK.reduce((s, c) => s + c[2], 0);
check('Atkinson propagates exactly 6/8 = 0.75 of the error (drops 1/4 on purpose)',
  approx(atkSum, 0.75, 1e-12), `Σ = ${atkSum}`);

// B · The claim, on flat fields ---------------------------------------------
// On a constant grey v, thresholding gives pure black or pure white — the tone
// is destroyed. Error diffusion sets a dot density equal to v.
console.log('\nB · On a flat grey, the dot density tracks the tone (threshold cannot)');
let fsMax = 0, thrMax = 0;
for (let v = 0.05; v <= 0.951; v += 0.05) {
  const img = flat(160, 160, v);
  const fsErr = Math.abs(meanOf(floydSteinberg(img)) - v);
  const thrErr = Math.abs(meanOf(threshold(img)) - v);
  fsMax = Math.max(fsMax, fsErr); thrMax = Math.max(thrMax, thrErr);
}
check('Floyd–Steinberg dot density matches tone across v=0.05..0.95 (worst error < 0.01)',
  fsMax < 0.01, `worst |density − v| = ${fsMax.toFixed(4)}`);
check('Thresholding destroys the tone on flat fields (worst error ≈ 0.45)',
  thrMax > 0.4, `worst |density − v| = ${thrMax.toFixed(4)}`);
// Headline example the page quotes: a flat 20% grey.
const g20 = flat(200, 200, 0.2);
const fs20 = meanOf(floydSteinberg(g20)) * 100, thr20 = meanOf(threshold(g20)) * 100;
console.log(`     flat 20% grey → Floyd–Steinberg dots cover ${fs20.toFixed(1)}% ; threshold covers ${thr20.toFixed(1)}%`);
check('Headline: 20% grey → FS ≈ 20% coverage, threshold = 0% (all black)',
  approx(fs20, 20, 0.5) && thr20 === 0, `FS ${fs20.toFixed(1)}% vs threshold ${thr20.toFixed(1)}%`);

// C · Reconstruction under blur (the eye averaging the dots) -----------------
// Blur the 1-bit result and compare to the original continuous tone. This is
// literally what the page's "squint" slider does. Lower MAE = a better lie.
console.log('\nC · Squint (blur) the dots back to grey — error diffusion reconstructs best');
const scenes = { ramp: ramp(256, 160), sphere: sphere(220, 220) };
for (const [nm, img] of Object.entries(scenes)) {
  const sigma = 2.2;
  const rows = {
    threshold: mae(gaussBlur(threshold(img), sigma), img),
    'ordered 8×8': mae(gaussBlur(ordered(img, 8), sigma), img),
    atkinson: mae(gaussBlur(atkinson(img), sigma), img),
    'floyd–steinberg': mae(gaussBlur(floydSteinberg(img), sigma), img),
  };
  console.log(`     ${nm} (σ=${sigma}px):  ` +
    Object.entries(rows).map(([k, v]) => `${k} ${v.toFixed(4)}`).join('  ·  '));
  check(`${nm}: Floyd–Steinberg reconstructs closer than threshold`,
    rows['floyd–steinberg'] < rows.threshold * 0.6,
    `FS ${rows['floyd–steinberg'].toFixed(4)} vs threshold ${rows.threshold.toFixed(4)}`);
  check(`${nm}: ordered dither also beats threshold`, rows['ordered 8×8'] < rows.threshold);
}
// And the reconstruction gets better the more you squint (larger blur).
const sph = scenes.sphere;
const e1 = mae(gaussBlur(floydSteinberg(sph), 1.2), sph);
const e3 = mae(gaussBlur(floydSteinberg(sph), 3.5), sph);
check('The more you squint, the truer the grey (FS MAE falls as blur grows)', e3 < e1,
  `σ1.2 → ${e1.toFixed(4)} ; σ3.5 → ${e3.toFixed(4)}`);

// D · The Bayer matrix is a genuine permutation (every threshold used once) ---
console.log('\nD · The ordered-dither matrix visits every threshold exactly once');
for (const n of [2, 4, 8]) {
  const M = bayerMatrix(n).flat().sort((a, b) => a - b);
  let perm = M.length === n * n; for (let i = 0; i < M.length; i++) if (M[i] !== i) perm = false;
  check(`Bayer ${n}×${n} is a permutation of 0..${n * n - 1}`, perm);
}

// E · A hand-checkable case: dots conserve the total ---------------------------
// The simplest ditherer of all — 1-D error diffusion, carrying the whole error
// to the next pixel on the right. A constant 0.25 grey, 40 pixels long. If dot
// density equals tone, there must be 40×0.25 = 10 white dots. You can count
// them: the pattern settles into 0,1,0,0 repeating (one white every fourth).
console.log('\nE · Hand-check: a 40-pixel row of 25% grey, 1-D error diffusion → ten white dots');
function diffuse1D(vals) {
  const out = []; let e = 0;
  for (const v of vals) { const old = v + e, nw = old >= 0.5 ? 1 : 0; e = old - nw; out.push(nw); }
  return out;
}
const row = diffuse1D(new Array(40).fill(0.25));
const whites = row.reduce((s, v) => s + v, 0);
check('1-D error diffusion lays exactly 10 white dots in a 40-px 25% row', whites === 10, `${whites} dots`);
check('…settling into the pattern 0,1,0,0 repeating', row.slice(0, 8).join('') === '01000100',
  `first 8: ${row.slice(0, 8).join('')}`);

// ---------------------------------------------------------------------- report
console.log(`\n${FAIL === 0 ? 'ALL CHECKS PASSED' : FAIL + ' CHECK(S) FAILED'} — ${PASS} passed, ${FAIL} failed.\n`);
process.exit(FAIL === 0 ? 0 : 1);
