// verify.mjs: the check for /strata/how-many-points-it-takes/.
//
//   node verify.mjs
//
// Inside the project it reads the page's files from public/; anywhere else it
// downloads them from artwaste.land (the page, data.json, fit.mjs), so a reader
// with nothing but this file and Node 18+ can run it.
//
// What it checks:
//   1. The fit code the page runs (fit.mjs) reproduces, for every picture, the
//      numbers the study's Python (analyse.py) wrote into data.json: the share
//      of receding length on one point, the shares with two and three points,
//      the scatter beyond measurement, and each reader's share.
//   2. The controls: the computer-drawn room's lines agree on one point for
//      all their length, and that point is within 2 px of the true one; both
//      photographs score at least 99%.
//   3. The threshold: a picture with fewer than six distinct painted edges is
//      marked unmeasurable, and the page reports none of its numbers as data.
//   4. Every number printed on the page inside a data-v marker, recomputed
//      here from the lines, matches the page to the digit shown.
//   5. The measure can fail: moving one agreeing line in the drawn room off
//      its point lowers the room's share, and turning one line of Bouts by two
//      degrees takes it out of agreement.

import { readFileSync, existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { tmpdir } from 'node:os';
import { writeFileSync } from 'node:fs';

const HERE = dirname(fileURLToPath(import.meta.url));
const LOCAL = join(HERE, '..', '..', 'public', 'strata', 'how-many-points-it-takes');
const SITE = 'https://artwaste.land/strata/how-many-points-it-takes/';

async function get(name) {
  const p = join(LOCAL, name);
  if (existsSync(p)) return readFileSync(p, 'utf8');
  process.stderr.write(`fetching ${SITE}${name}\n`);
  const r = await fetch(SITE + name);
  if (!r.ok) throw new Error(`${name}: HTTP ${r.status}`);
  return await r.text();
}

const html = await get('index.html');
const D = JSON.parse(await get('data.json'));
let F;
if (existsSync(join(LOCAL, 'fit.mjs'))) F = await import(pathToFileURL(join(LOCAL, 'fit.mjs')).href);
else {
  const tmp = join(tmpdir(), `aw-fit-${process.pid}.mjs`);
  writeFileSync(tmp, await get('fit.mjs'));
  F = await import(pathToFileURL(tmp).href);
}

let pass = 0, fail = 0;
const out = [];
const ok = (name, cond, detail = '') => { cond ? pass++ : fail++; out.push(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  :  ' + detail : ''}`); };
const head = (t) => out.push('', `-- ${t}`);
const near = (a, b, e = 1e-6) => Math.abs(a - b) <= e;
const pct = (x) => (100 * x).toFixed(1) + '%';

const byId = Object.fromEntries(D.pictures.map((p) => [p.id, p]));
const recomputed = {};

head('1. The page\'s fit code reproduces the study\'s numbers, picture by picture');
for (const p of D.pictures) {
  const L = [...p.lines.A, ...p.lines.B], S = [...p.sigma.A, ...p.sigma.B];
  const c = F.consensus(L, 1, S), k = F.pointsNeeded(L, S, 1, 3), sc = F.scatter(L, S);
  const cA = p.lines.A.length >= 3 ? F.consensus(p.lines.A, 1, p.sigma.A).share : null;
  const cB = p.lines.B.length >= 3 ? F.consensus(p.lines.B, 1, p.sigma.B).share : null;
  recomputed[p.id] = { share1: c.share, vp1: c.vp, points: k, tau: sc.tau_deg, shareA: cA, shareB: cB, L, S };
  const same = near(c.share, p.share1) && near(sc.tau_deg, p.tau, 1e-5)
    && k.length === p.points.length && k.every((q, j) => near(q.cum_share, p.points[j].cum_share))
    && (cA == null || near(cA, p.share1_A)) && (cB == null || near(cB, p.share1_B));
  ok(`${p.id}`, same, `one point ${pct(c.share)} (py ${pct(p.share1)}); points ${k.map((q) => pct(q.cum_share)).join(' ')}; scatter ${sc.tau_deg.toFixed(3)} deg (py ${p.tau.toFixed(3)})`);
}

head('2. The controls');
{
  const s = byId['synthetic-2'], r = recomputed['synthetic-2'];
  const d = Math.hypot(r.vp1[0] - s.true_vp[0], r.vp1[1] - s.true_vp[1]) / s.scale;
  ok('drawn room: every line agrees on one point', near(r.share1, 1, 1e-12), pct(r.share1));
  ok('drawn room: that point is the true point, within 2 px', d <= 2, `${d.toFixed(2)} px in the analysis frame`);
  ok('drawn room: scatter beyond measurement under 0.1 degree', r.tau < 0.1, `${r.tau.toFixed(3)} deg`);
  for (const id of ['control-photo-1', 'control-photo-2']) ok(`${id}: at least 99% on one point`, recomputed[id].share1 >= 0.99, pct(recomputed[id].share1));
}

head('3. The six-edge threshold');
for (const p of D.pictures) if (!p.measurable) {
  ok(`${p.id}: marked unmeasurable (${p.edges} edges < 6)`, p.edges < 6);
  ok(`${p.id}: the page prints none of its figures`, !new RegExp(`data-v="${p.id}:`).test(html));
}
ok('every measurable picture has at least 6 edges', D.pictures.filter((p) => p.measurable).every((p) => p.edges >= 6));

head('4. Every number the page prints, recomputed');
const deg = (x) => x.toFixed(2) + '°';
function value(key) {
  const [id, what] = key.split(':');
  if (id === 'trend') {
    const [grp, stat] = what.split('.');
    const t = D.trend[grp];
    return stat === 'rho' ? t.spearman_rho.toFixed(2) : pct(t.p_one_sided);
  }
  const p = byId[id], r = recomputed[id];
  if (what === 'share1') return pct(r.share1);
  if (what === 'shareA') return pct(r.shareA);
  if (what === 'shareB') return pct(r.shareB);
  if (what === 'edges') return String(p.edges);
  if (what === 'tau') return deg(r.tau);
  if (what === 'pts2') return pct(r.points[1].cum_share);
  if (what === 'pts3') return pct(r.points[2].cum_share);
  if (what.endsWith('tau')) {
    const g = what.slice(0, -3);
    const all = [...p.groups.A, ...p.groups.B], idx = all.map((x, i) => (x === g ? i : -1)).filter((i) => i >= 0);
    return deg(F.scatter(idx.map((i) => r.L[i]), idx.map((i) => r.S[i])).tau_deg);
  }
  throw new Error('unknown key ' + key);
}
const marks = [...html.matchAll(/data-v="([^"]+)">([^<]+)</g)];
ok('the page carries its numbers in data-v markers', marks.length >= 30, `${marks.length} markers`);
for (const [, key, shown] of marks) {
  const v = value(key), s = shown.replace('&deg;', '°').trim();
  ok(`${key}`, v === s, `page ${s}, recomputed ${v}`);
}
{
  // the trend's own recomputation, from the measurable paintings' shares
  const rs = D.pictures.filter((p) => (p.region === 'italy' || p.region === 'north') && p.measurable && p.year);
  const rank = (a) => { // ties share their average rank, as in analyse.py
    const o = a.map((v, i) => [v, i]).sort((x, y) => x[0] - y[0] || x[1] - y[1]), r = Array(a.length);
    for (let i = 0; i < o.length;) { let j = i; while (j + 1 < o.length && o[j + 1][0] === o[i][0]) j++; for (let k = i; k <= j; k++) r[o[k][1]] = (i + j) / 2; i = j + 1; }
    return r; };
  const ry = rank(rs.map((p) => p.year)), rsh = rank(rs.map((p) => recomputed[p.id].share1));
  const m = (a) => a.reduce((s, v) => s + v, 0) / a.length, my = m(ry), ms = m(rsh);
  let n = 0, dy = 0, ds = 0; ry.forEach((v, i) => { n += (v - my) * (rsh[i] - ms); dy += (v - my) ** 2; ds += (rsh[i] - ms) ** 2; });
  const rho = n / Math.sqrt(dy * ds);
  ok('trend: Spearman rho recomputed from the shares', near(rho, D.trend.all.spearman_rho, 1e-9), `${rho.toFixed(4)} over ${rs.length} paintings`);
}

head('5. The measure can fail');
{
  const r = recomputed['synthetic-2'], L = r.L.map((l) => [...l]);
  const turn = (l, degs) => { const mx = (l[0] + l[2]) / 2, my = (l[1] + l[3]) / 2, a = degs * Math.PI / 180, c = Math.cos(a), s = Math.sin(a);
    const rot = (x, y) => [mx + (x - mx) * c - (y - my) * s, my + (x - mx) * s + (y - my) * c]; return [...rot(l[0], l[1]), ...rot(l[2], l[3])]; };
  let longest = 0; L.forEach((l, i) => { if (Math.hypot(l[2] - l[0], l[3] - l[1]) > Math.hypot(L[longest][2] - L[longest][0], L[longest][3] - L[longest][1])) longest = i; });
  L[longest] = turn(L[longest], 5);
  const c = F.consensus(L, 1, r.S);
  ok('turning the drawn room\'s longest line by 5 degrees lowers its share', c.share < r.share1 - 1e-6, `${pct(r.share1)} -> ${pct(c.share)}`);
  const b = recomputed['bouts-last-supper'], c0 = F.consensus(b.L, 1, b.S);
  const i = c0.agree[0], LB = b.L.map((l) => [...l]); LB[i] = turn(LB[i], 2 + 2 * b.S[i]);
  const c1 = F.consensus(LB, 1, b.S);
  ok('turning one agreeing Bouts line by 2 degrees beyond its doubt takes it out of agreement', !c1.agree.includes(i) && c1.share < c0.share, `${pct(c0.share)} -> ${pct(c1.share)}`);
}

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