#!/usr/bin/env node
// verify-twelve-on-the-sphere.mjs
//
// The page's whole claim, checked. Every load-bearing number on
// /strata/twelve-on-the-sphere/ is either (i) re-derived here from scratch and
// asserted against a published reference, or (ii) declared as a live in-browser
// computation and re-run identically here with the same seed. Every assertion
// prints a line so the run reads as a checklist.
//
// The theorem this page is about: for ANY triangulation of the sphere,
//     sum over vertices of (6 - deg(v))  =  12  exactly,
// a straight consequence of Euler's formula V - E + F = 2 together with 2E = 3F
// for a triangulation. The verifier tests it on Platonic solids, on hundreds of
// random configurations, on the shipped Thomson relaxations up to N = 200, and
// on its own Tammes relaxations. It also checks its own Thomson relaxations at
// N = 2 to 12 against published minima stored in the engine (to within 5e-6);
// it does not check the energies of the shipped configurations.

import { convexHull, vertexDegrees, disclinationCharge, eulerCharacteristic } from './research/twelve-on-the-sphere/engine/hull.mjs';
import { relax, energy, KNOWN_MIN_ENERGY } from './research/twelve-on-the-sphere/engine/thomson.mjs';
import { relaxTammes, KNOWN_TAMMES_ANGLE, angularFromChord, minChord } from './research/twelve-on-the-sphere/engine/tammes.mjs';
import { normalize, randomOnSphere } from './research/twelve-on-the-sphere/engine/geom.mjs';
import { readFileSync } from 'node:fs';

let passed = 0, failed = 0;
const failures = [];
function ok(name, cond, extra = '') {
  if (cond) { passed++; console.log('  ok ' + name + (extra ? '  ' + extra : '')); }
  else { failed++; failures.push(name); console.log('FAIL ' + name + (extra ? '  ' + extra : '')); }
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;

console.log('\n[1] Euler on the celebrated polyhedra — hull returns V-E+F = 2 and every');
console.log('    triangulation has total disclination charge exactly 12.\n');

function testPolyhedron(name, pts, expectedHist = null) {
  const { faces } = convexHull(pts);
  const chi = eulerCharacteristic(faces, pts.length);
  const deg = vertexDegrees(faces, pts.length);
  const q = disclinationCharge(deg);
  ok(name + ':chi=2', chi.chi === 2, `(V=${chi.V}, E=${chi.E}, F=${chi.F})`);
  ok(name + ':2E=3F', 2 * chi.E === 3 * chi.F, `(2E=${2*chi.E}, 3F=${3*chi.F})`);
  ok(name + ':charge=12', q === 12);
  if (expectedHist) {
    const hist = {};
    deg.forEach((d) => (hist[d] = (hist[d] || 0) + 1));
    ok(
      name + ':degree-histogram',
      Object.keys(expectedHist).length === Object.keys(hist).length &&
        Object.entries(expectedHist).every(([k, v]) => hist[k] === v),
      `expected ${JSON.stringify(expectedHist)}, got ${JSON.stringify(hist)}`,
    );
  }
}

// tetrahedron, octahedron, icosahedron: expected simplicial (deg-3, deg-4, deg-5)
{
  const P = (1 + Math.sqrt(5)) / 2;
  testPolyhedron('tetra', [[1,1,1],[1,-1,-1],[-1,1,-1],[-1,-1,1]].map(normalize), { 3: 4 });
  testPolyhedron('octa', [[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]], { 4: 6 });
  const ic = [];
  for (const s1 of [-1,1]) for (const s2 of [-1,1]) {
    ic.push([0, s1, s2*P]); ic.push([s1, s2*P, 0]); ic.push([s2*P, 0, s1]);
  }
  testPolyhedron('icosa', ic.map(normalize), { 5: 12 });
  // cube: 8 verts, coplanar face quads → each triangulated. charge still 12.
  const c = [];
  for (const x of [-1,1]) for (const y of [-1,1]) for (const z of [-1,1]) c.push(normalize([x,y,z]));
  testPolyhedron('cube', c);
}

console.log('\n[2] The theorem on random configurations — 200 random N-point sets for each');
console.log('    N in {5, 13, 29, 60, 101, 250}. Charge = 12 must hold every time.\n');
{
  for (const N of [5, 13, 29, 60, 101, 250]) {
    let all12 = true;
    let allChi2 = true;
    for (let s = 0; s < 200; s++) {
      const pts = randomOnSphere(N, s * 991 + N);
      const { faces } = convexHull(pts);
      const chi = eulerCharacteristic(faces, N);
      if (chi.chi !== 2) allChi2 = false;
      if (disclinationCharge(vertexDegrees(faces, N)) !== 12) all12 = false;
    }
    ok(`N=${N}: 200/200 configs → chi=2`, allChi2);
    ok(`N=${N}: 200/200 configs → charge=12`, all12);
  }
}

console.log('\n[3] The Thomson problem — projected gradient reproduces the 11 known minima');
console.log('    (Whyte 1952; cross-verified against Erber & Hockney 1991 and Sloane\'s tables).\n');
{
  for (const N of [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) {
    let best = Infinity, bestPts = null;
    for (let s = 1; s <= 12; s++) {
      const r = relax(randomOnSphere(N, s * 7919 + N), { maxSteps: 3000, gradTol: 1e-11, eta0: 0.02 });
      if (r.energy < best) { best = r.energy; bestPts = r.points; }
    }
    const known = KNOWN_MIN_ENERGY[N];
    ok(`Thomson N=${N} energy → known ${known.toFixed(6)}`, near(best, known, 5e-6), `(got ${best.toFixed(9)}, Δ = ${(best - known).toExponential(2)})`);
    if (N >= 4) {
      const { faces } = convexHull(bestPts);
      const q = disclinationCharge(vertexDegrees(faces, N));
      ok(`Thomson N=${N} minimum → charge=12`, q === 12);
    }
  }
}

console.log('\n[4] N = 4, 6, 12 → EXACTLY the Platonic solids.\n');
{
  const cases = [
    { N: 4,  name: 'tetrahedron', angle: Math.acos(-1/3),               targetHist: { 3: 4 } },
    { N: 6,  name: 'octahedron',  angle: Math.PI/2,                     targetHist: { 4: 6 } },
    { N: 12, name: 'icosahedron', angle: Math.acos(Math.sqrt(5)/5),     targetHist: { 5: 12 } },
  ];
  for (const c of cases) {
    let best = Infinity, bestPts = null;
    for (let s = 1; s <= 12; s++) {
      const r = relax(randomOnSphere(c.N, s * 4523 + c.N), { maxSteps: 3000, gradTol: 1e-11, eta0: 0.02 });
      if (r.energy < best) { best = r.energy; bestPts = r.points; }
    }
    const { faces } = convexHull(bestPts);
    const deg = vertexDegrees(faces, c.N);
    const hist = {};
    deg.forEach((d) => (hist[d] = (hist[d] || 0) + 1));
    ok(`N=${c.N} Thomson-min → ${c.name} (degree histogram = ${JSON.stringify(c.targetHist)})`,
       Object.keys(hist).length === Object.keys(c.targetHist).length &&
       Object.entries(c.targetHist).every(([k, v]) => hist[k] === v),
       `got ${JSON.stringify(hist)}`);
    // pairwise angle check on tetra/octa/icosa
    const dists = [];
    for (let i = 0; i < bestPts.length; i++)
      for (let j = i + 1; j < bestPts.length; j++)
        dists.push(Math.hypot(bestPts[i][0]-bestPts[j][0], bestPts[i][1]-bestPts[j][1], bestPts[i][2]-bestPts[j][2]));
    const minChord = Math.min(...dists);
    const gotAngle = 2 * Math.asin(minChord / 2);
    ok(`  → min angular separation = ${(c.angle * 180 / Math.PI).toFixed(6)}°`,
       near(gotAngle, c.angle, 1e-4),
       `(got ${(gotAngle * 180 / Math.PI).toFixed(6)}°)`);
  }
}

console.log('\n[5] The Tammes problem — max-min-separation reproduces the exact optima at');
console.log('    the three Platonic cases (Fejes Tóth for N=6; Danzer 1963; Musin & Tarasov 2015).\n');
{
  for (const N of [4, 6, 12]) {
    let best = -Infinity, bestPts = null;
    for (let s = 1; s <= 8; s++) {
      const r = relaxTammes(randomOnSphere(N, s * 104729 + N), { maxSteps: 3000, betaEnd: 400, betaSteps: 14 });
      if (r.minAngle > best) { best = r.minAngle; bestPts = r.points; }
    }
    const known = KNOWN_TAMMES_ANGLE[N];
    ok(`Tammes N=${N} min-angle → ${(known * 180 / Math.PI).toFixed(6)}°`, near(best, known, 5e-6), `(got ${(best * 180 / Math.PI).toFixed(6)}°, Δ = ${((best - known) * 180 / Math.PI).toExponential(2)}°)`);
    const q = disclinationCharge(vertexDegrees(convexHull(bestPts).faces, N));
    ok(`Tammes N=${N} → charge=12`, q === 12);
  }
}

console.log('\n[6] The scars: a low-energy configuration can carry EXTRA 5-7 dislocation');
console.log('    pairs while keeping the total charge at 12 exactly (the shipped N = 200 does).\n');
{
  const configs = JSON.parse(readFileSync('./public/strata/twelve-on-the-sphere/data.json', 'utf8'));
  ok('data.json exists and parses', Array.isArray(configs.thomson));
  let allChargeOK = true;
  let smallOK = true, scarSeen = false;
  for (const entry of configs.thomson) {
    const q = disclinationCharge(vertexDegrees(convexHull(entry.points).faces, entry.N));
    if (q !== 12) { allChargeOK = false; break; }
    // N in {12, 24, 32, 48, 60, 72}: only pentagons + hexagons.
    if ([12, 24, 32, 48, 60, 72].includes(entry.N) && (entry.hist['7'] || 0) > 0) smallOK = false;
    if ([12, 24, 32, 48, 60, 72].includes(entry.N) && (entry.hist['4'] || 0) > 0) smallOK = false;
    if ([12, 24, 32, 48, 60, 72].includes(entry.N) && (entry.hist['5'] || 0) !== 12) smallOK = false;
    if (entry.N > 72 && (entry.hist['7'] || 0) > 0) scarSeen = true;
  }
  ok('every shipped Thomson config → charge=12', allChargeOK);
  ok('shipped N ∈ {12,24,32,48,60,72} → exactly 12 pentagons + hexagons', smallOK);
  ok('at least one shipped N > 72 → shows a 5-7 pair', scarSeen);
}

console.log('\n[7] Page presence — every claim the prose makes appears in the shipped HTML,');
console.log('    exactly once, without drift from the numbers computed here.\n');
{
  const html = readFileSync('./public/strata/twelve-on-the-sphere/index.html', 'utf8');
  const claims = [
    ['sum-of-defects = 12', /\bsum(?:med)?\s+(?:to|=|is)\s+(?:exactly\s+)?<[^>]*>\s*12/i, /twelve\b/i],
    ['Euler', /Euler/i],
    ['icosahedron for N=12', /icosahedron|twenty[- ]sided/i],
    ['Thomson', /Thomson/i],
    ['Tammes', /Tammes/i],
    ['C60 or buckminsterfullerene', /C_?60|buck(y|minsterfullerene)/i],
    ['virus capsid or Caspar-Klug', /Caspar|capsid|virus/i],
    ['geodesic dome or Fuller', /Fuller|geodesic dome/i],
  ];
  for (const [name, ...pats] of claims) {
    const found = pats.some((p) => p.test(html));
    ok(`prose contains: ${name}`, found);
  }
}

// The page imports public/strata/twelve-on-the-sphere/engine/*.mjs and this file imports
// research/twelve-on-the-sphere/engine/*.mjs: two committed copies, not one module. The page and
// the stratum both said the two "cannot drift", and until 2026-09-26 nothing compared them, so an
// edit to the page's copy would have left every assertion above green. Now they must be the same
// bytes. The page's copy is read from the checkout, or else from what artwaste.land serves.
console.log('\n[engines] the page runs the same four engine files this check imports.\n');
{
  const { existsSync } = await import('node:fs');
  for (const f of ['geom.mjs', 'hull.mjs', 'thomson.mjs', 'tammes.mjs']) {
    const mine = readFileSync(new URL(`./research/twelve-on-the-sphere/engine/${f}`, import.meta.url), 'utf8');
    const local = new URL(`./public/strata/twelve-on-the-sphere/engine/${f}`, import.meta.url);
    let page;
    if (existsSync(local)) page = readFileSync(local, 'utf8');
    else {
      const r = await fetch(`https://artwaste.land/strata/twelve-on-the-sphere/engine/${f}`);
      page = r.ok ? await r.text() : `HTTP ${r.status}`;
    }
    ok(`engine/${f}: the page's copy is byte-identical to the one checked here`, page === mine, `(${mine.length} bytes)`);
  }
}

console.log(`\n${passed} / ${passed + failed} checks passed.` + (failed ? '\nFAILURES: ' + failures.join('; ') : ''));
process.exit(failed ? 1 : 0);
