#!/usr/bin/env node
// verify-the-one-that-broke-off.mjs
//
// Re-derives the tablet arithmetic and compares selected page values and browser
// output with it. Historical claims need their cited sources.
//
//   node verify-the-one-that-broke-off.mjs                # everything, incl. the DOM
//   node verify-the-one-that-broke-off.mjs --no-browser   # skip the DOM section
//
// Say so if you report a green run with --no-browser: that section is the only one
// that checks what a reader actually sees.
//
// Integer and rational tablet calculations use exact BigInt arithmetic. Angles and
// their step statistics use floating-point approximations.

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

const ROOT = dirname(fileURLToPath(import.meta.url));
const R = (p) => join(ROOT, p);

const S = await import(R('research/plimpton-322/sexagesimal.mjs'));
const R322 = await import(R('research/plimpton-322/reconstruct.mjs'));
const T = await import(R('research/plimpton-322/tablet.mjs'));

const PAGE = R('public/strata/the-one-that-broke-off/index.html');
const HTML = existsSync(PAGE) ? readFileSync(PAGE, 'utf8') : null;

let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) pass++;
  else { fail++; console.log(`  FAIL  ${name}${detail ? ' — ' + detail : ''}`); }
};
const section = (s) => console.log(`\n${s}`);
const sexaInt = (str) => str.trim().split(/\s+/).reduce((a, d) => a * 60n + BigInt(d), 0n);

const rows = R322.reconstructAll();

// ── 1. the tablet is a table of Pythagorean triples, and that is checkable ───
section('1. Every row is a genuine Pythagorean triple');
ok('fifteen rows', rows.length === 15, `got ${rows.length}`);
for (const r of rows) {
  ok(`row ${r.n}: d^2 - s^2 is a perfect square`, r.isTriple);
  if (r.isTriple) {
    ok(`row ${r.n}: s^2 + l^2 = d^2 exactly`,
      r.s.n * r.s.n + r.l.n * r.l.n === r.d.n * r.d.n);
  }
}

// 2. Column I and the limit of calculation from its fractional digits.
section('2. Column I with the leading 1 and with it subtracted');
for (const r of rows) {
  ok(`row ${r.n}: column I = d^2/l^2 with the leading 1`, r.colIMatchesWithOne);
  ok(`row ${r.n}: column I = s^2/l^2 without it`, r.colIMatchesNoOne);
}
// the identity itself: the two readings differ by exactly 1, always
for (const r of rows) {
  ok(`row ${r.n}: the two readings differ by exactly 1`,
    S.rcmp(S.rsub(r.ratioSquaredWithOne, r.ratioSquaredNoOne), S.rat(1n)) === 0);
}
ok('fractional digits alone cannot select a leading 1',
  R322.theLeadingOne === 'undecidable-by-arithmetic');

// ── 3. the generating reciprocal pairs ──────────────────────────────────────
section('3. Each row comes from a reciprocal pair, and every one is regular');
for (const r of rows) {
  ok(`row ${r.n}: x times 1/x is exactly 1`, r.xTimesInverseIsOne);
  ok(`row ${r.n}: x is a regular number (2,3,5 only)`, r.xIsRegular);
  ok(`row ${r.n}: 1/x has a terminating sexagesimal expansion`, r.xInvSexa !== null);
}
let descending = true;
for (let i = 1; i < rows.length; i++) if (S.rcmp(rows[i - 1].x, rows[i].x) <= 0) descending = false;
ok('x runs strictly downward from row 1 to row 15', descending);
ok('x runs from 2;24 to 1;48', rows[0].xSexa === '2;24' && rows[14].xSexa === '1;48');

// Robson 2002 p.113: "None of them is more than four sexagesimal places long"
const fracPlaces = (sx) => { const i = sx.indexOf(';'); return i < 0 ? 0 : sx.slice(i + 1).trim().split(/\s+/).length; };
const maxPlaces = Math.max(...rows.map((r) => Math.max(fracPlaces(r.xSexa), fracPlaces(r.xInvSexa))));
ok('no pair runs past four sexagesimal places (Robson 2002, p.113)', maxPlaces === 4, `got ${maxPlaces}`);

// ── 4. how many pairs are in the standard reciprocal table ──────────────────
// A pair {x, 1/x} IS a standard entry when either member equals a standard head
// number times a power of 60, because the notation is floating.
section('4. How many of the fifteen pairs stand in the standard reciprocal table');
const isPow60Multiple = (v, n) => {
  const r = S.rdiv(v, S.rat(BigInt(n)));
  for (let j = -8; j <= 8; j++) {
    const p = j >= 0 ? S.rat(60n ** BigInt(j)) : S.rat(1n, 60n ** BigInt(-j));
    if (S.rcmp(r, p) === 0) return true;
  }
  return false;
};
const inStandard = rows.filter((r) =>
  T.STANDARD_RECIPROCAL_HEADS_COMPLETED.some((n) => isPow60Multiple(r.x, n) || isPow60Multiple(r.xInv, n)));
ok('four pairs, on the count this page states and shows', inStandard.length === 4, `got ${inStandard.length}`);
ok('they are rows 1, 6, 11 and 13',
  inStandard.map((r) => r.n).join(',') === '1,6,11,13', inStandard.map((r) => r.n).join(','));
// Robson 2002 p.113 says five. The page reports the discrepancy rather than hiding it,
// and this check pins the fact that we could not reach five under any reading we tried.
ok('the count does not reach five even with 72, 75 and 80 added to the table',
  inStandard.length < 5);

// ── 5. the tablet is not exhaustive, and that is worth knowing ──────────────
section('5. The fifteen rows are a selection, not everything available');
const P = (b, e) => (e >= 0 ? b ** BigInt(e) : 1n);
const lo = S.rat(108n, 60n), hi = S.rat(144n, 60n);
const candidates = new Map();
for (let a = -30; a <= 30; a++) for (let b = -20; b <= 20; b++) for (let c = -15; c <= 15; c++) {
  const v = S.rat(P(2n, a) * P(3n, b) * P(5n, c), P(2n, -a) * P(3n, -b) * P(5n, -c));
  if (S.rcmp(v, lo) < 0 || S.rcmp(v, hi) > 0) continue;
  let q = v.d, al = 0, be = 0, ga = 0;
  while (q % 2n === 0n) { q /= 2n; al++; } while (q % 3n === 0n) { q /= 3n; be++; } while (q % 5n === 0n) { q /= 5n; ga++; }
  const k = Math.max(Math.ceil(al / 2), be, ga);
  const t = S.toSexa(v);
  const key = S.showDigits(t.digits, t.intPlaces);
  if (!candidates.has(key) || candidates.get(key) > k) candidates.set(key, k);
}
const onTablet = new Set(rows.map((r) => r.xSexa));
for (const key of onTablet) ok(`row generator ${key} is regular and in range`, candidates.has(key));
const within3 = [...candidates.entries()].filter(([, k]) => k <= 3);
const unusedWithin3 = within3.filter(([key]) => !onTablet.has(key));
ok('28 regular generators sit in range at three places or fewer', within3.length === 28, `got ${within3.length}`);
ok('the scribe used 15 of them and left 13 unused', unusedWithin3.length === 13, `got ${unusedWithin3.length}`);

// ── 6. the errors, and their arithmetic signatures ──────────────────────────
section('6. The seven errors of Robson 2001 Table 2, checked as arithmetic');
ok('seven errors tabulated', T.ERRORS.length === 7, `got ${T.ERRORS.length}`);
ok('one of them is marked disputed (I,13)', T.ERRORS.filter((e) => e.disputed).length === 1);
ok('one of them is marked a fork (line 15)', T.ERRORS.filter((e) => e.fork).length === 1);

const err = (col, line) => T.ERRORS.find((e) => e.col === col && e.line === line);

// I,2 and I,8: two adjacent places merged into their sum.
for (const [col, line, a, b, merged] of [['I', 2, 50, 6, 56], ['I', 8, 45, 14, 59]]) {
  const e = err(col, line);
  ok(`${col},${line}: the raw place ${merged} is ${a} + ${b}`, a + b === merged);
  ok(`${col},${line}: raw reading contains ${merged}`, e.raw.split(/\s+/).includes(String(merged).padStart(2, '0')) || e.raw.split(/\s+/).includes(String(merged)));
  ok(`${col},${line}: corrected reading contains ${a} then ${b}`,
    e.corrected.includes(`${a} ${String(b).padStart(2, '0')}`));
}

// II,13: the scribe wrote the square of the right answer.
{
  const e = err('II', 13);
  ok('II,13: the raw value is exactly the square of the corrected value',
    sexaInt(e.raw) === sexaInt(e.corrected) ** 2n,
    `${sexaInt(e.raw)} vs ${sexaInt(e.corrected) ** 2n}`);
  ok('II,13: and that value is 25921 = 161^2', sexaInt(e.raw) === 25921n && sexaInt(e.corrected) === 161n);
}

// II,15: exactly double.
{
  const e = err('II', 15);
  ok('II,15: the raw value is exactly twice the corrected value',
    sexaInt(e.raw) === 2n * sexaInt(e.corrected));
}

// I,13: an empty place lost, so the value is not equal but the digits are a subsequence.
{
  const e = err('I', 13);
  ok('I,13: the two readings are different numbers',
    sexaInt(e.raw) !== sexaInt(e.corrected));
  ok('I,13: the corrected reading is the raw one with an empty place restored',
    e.corrected.replace(/\b00\s/, '') === e.raw);
}

// II,9: one wedge.
{
  const e = err('II', 9);
  ok('II,9: the raw and corrected differ by exactly 60 (one wedge in the upper place)',
    sexaInt(e.raw) - sexaInt(e.corrected) === 60n);
}

// III,2: Robson's Table 2 records no numerical relationship. Check we claim none.
{
  const e = err('III', 2);
  ok('III,2: recorded as unexplained, per Robson Table 2', e.signature === 'unexplained');
  ok('III,2: and it is indeed neither double, half, nor the square',
    sexaInt(e.raw) !== 2n * sexaInt(e.corrected)
    && sexaInt(e.raw) * 2n !== sexaInt(e.corrected)
    && sexaInt(e.raw) !== sexaInt(e.corrected) ** 2n);
}

// The corrected values in ERRORS must be the values the ROWS table carries, or the
// two halves of this study disagree about the tablet and one of them is publishing
// a number it did not check.
section('7. The error table and the row table agree about the corrected readings');
for (const e of T.ERRORS) {
  const row = T.ROWS.find((r) => r.n === e.line);
  const cell = e.col === 'I' ? row.colI : e.col === 'II' ? row.colII : row.colIII;
  if (e.fork) { ok(`line ${e.line} ${e.col}: fork, row table carries Robson's preference`, cell === e.corrected, `row has ${cell}`); continue; }
  ok(`line ${e.line} column ${e.col}: corrected value matches the row table`, cell === e.corrected, `row has ${cell}, errors table has ${e.corrected}`);
}

// ── 8. the angles, for the trigonometric reading ────────────────────────────
section('8. The angle sequence the trigonometric reading appeals to');
const angles = rows.map((r) => r.angleDeg);
ok('angles descend monotonically', angles.every((a, i) => i === 0 || a < angles[i - 1]));
const steps = angles.slice(1).map((a, i) => angles[i] - a);
const mn = Math.min(...steps), mx = Math.max(...steps);
ok('the smallest step is under half a degree', mn < 0.5, `min ${mn.toFixed(4)}`);
ok('the largest step is over one and a half degrees', mx > 1.5, `max ${mx.toFixed(4)}`);
ok('so the steps are not "approximately 1 degree" apart: they vary by a factor over 4',
  mx / mn > 4, `ratio ${(mx / mn).toFixed(2)}`);
ok('first angle is 44.76 deg', Math.abs(angles[0] - 44.7603) < 5e-4, angles[0].toFixed(4));
ok('last angle is 31.89 deg', Math.abs(angles[14] - 31.8908) < 5e-4, angles[14].toFixed(4));

// ── 9. the shipped page says what this file computed ────────────────────────
section('9. The shipped page carries these numbers');
if (!HTML) {
  console.log('  (page not built yet — skipping)');
} else {
  const has = (needle, label) => ok(`page states ${label}`, HTML.includes(needle), `missing "${needle}"`);
  has('25921', 'the square 25921 behind the row 13 error');
  has('2;24', 'the first generating number');
  has('1;48', 'the last generating number');
  has('44.76', 'the first angle');
  has('31.89', 'the last angle');
  for (const r of rows) has(r.sDec, `row ${r.n} short side ${r.sDec}`);
  for (const r of rows) has(r.dDec, `row ${r.n} diagonal ${r.dDec}`);
  ok('page names Robson 2001 as the source of the error table', /Historia Mathematica/.test(HTML) && /Robson/.test(HTML));
  ok('page names the row 15 fork', /1 46/.test(HTML));
  ok('page reports the four-not-five discrepancy openly', /four/i.test(HTML) && /five/i.test(HTML));
}

// ── 10. the DOM a reader actually gets ──────────────────────────────────────
const wantBrowser = !process.argv.includes('--no-browser');
section('10. The page in a real browser');
if (!wantBrowser) {
  console.log('  (skipped by --no-browser; nothing here has been checked)');
} else if (!HTML) {
  console.log('  (page not built yet — skipping)');
} else {
  let chromium = null;
  try { ({ chromium } = await import('playwright')); } catch { /* not installed */ }
  if (!chromium) {
    console.log('  (playwright not installed — DOM section not run)');
  } else {
    const server = createServer((req, res) => {
      const p = decodeURIComponent(req.url.split('?')[0]);
      const file = p.endsWith('/') ? R('public' + p + 'index.html') : R('public' + p);
      if (!existsSync(file)) { res.writeHead(404); res.end('no'); return; }
      const ext = file.split('.').pop();
      res.writeHead(200, { 'content-type': { html: 'text/html', js: 'text/javascript', css: 'text/css', json: 'application/json', png: 'image/png', jpg: 'image/jpeg', woff2: 'font/woff2' }[ext] || 'application/octet-stream' });
      res.end(readFileSync(file));
    });
    await new Promise((r) => server.listen(0, r));
    const port = server.address().port;
    // This container ships a chromium that may not match the installed playwright's
    // pinned build, so fall back to the one on disk rather than reporting a red run
    // that is really a packaging mismatch.
    const onDisk = ['/opt/pw-browsers/chromium-1194/chrome-linux/chrome']
      .filter((p) => existsSync(p))[0];
    const browser = await chromium.launch(onDisk ? { executablePath: onDisk } : {});
    const page = await browser.newPage();
    const errors = [];
    page.on('pageerror', (e) => errors.push(String(e)));
    page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
    await page.goto(`http://127.0.0.1:${port}/strata/the-one-that-broke-off/`, { waitUntil: 'networkidle' });
    ok('no JavaScript errors on load', errors.length === 0, errors.slice(0, 3).join(' | '));

    const rowCount = await page.locator('[data-row]').count();
    ok('fifteen rows render', rowCount === 15, `got ${rowCount}`);

    // Compare the actual displayed results, not just the number of check cells.
    const checks = await page.locator('[data-check="triple"]').allTextContents();
    ok('every rendered corrected-row check matches the reconstruction',
      checks.length === 15 && checks.every((v, i) => v.trim() === rows[i].lDec));

    await page.locator('[data-row="13"]').click();
    const angle13 = await page.locator('#detail .stat').filter({ hasText: 'acute angle' }).locator('dd').textContent();
    ok('row 13 displays 33.86 degrees, as in Robson Figure 4', angle13 === '33.86°', angle13);

    await page.locator('#btn-raw').click();
    const raw15 = page.locator('[data-row="15"]');
    const rawSides = await raw15.locator('.digits').allTextContents();
    const rawChecks = await page.locator('[data-check="triple"]').allTextContents();
    const checkHeading = await page.locator('table.tablet thead th').last().textContent();
    const checkNote = await page.locator('#table-check-note').textContent();
    ok('raw mode identifies the retained results as corrected-row checks',
      rawSides[1] === '56' && rawSides[2] === '53'
      && rawChecks.length === 15 && rawChecks.every((v, i) => v.trim() === rows[i].lDec)
      && checkHeading.includes('corrected-row check')
      && checkNote.includes('use the corrected readings in both modes')
      && (await raw15.getAttribute('aria-label')).includes('short side 56, diagonal 53'));
    await page.locator('#btn-corrected').click();

    for (const w of [390, 768, 1440]) {
      await page.setViewportSize({ width: w, height: 900 });
      await page.waitForTimeout(120);
      const overflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1);
      ok(`no horizontal overflow at ${w}px`, !overflow);
    }
    await browser.close();
    server.close();
  }
}

console.log(`\n${fail === 0 ? 'ALL GREEN' : 'FAILURES'} — ${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
