#!/usr/bin/env node
// ─────────────────────────────────────────────────────────────────────────────
// Cube dissections into integer cubes — the check.
//
//   T(a,b,c) = number of dissections of an a×b×c box into integer-sided,
//   axis-aligned cubes, where rotations/reflections of the WHOLE dissection are
//   counted as distinct (the box sits fixed in space). D(n) = T(n,n,n).
//
// This file re-derives everything the page claims, offline and deterministically,
// TWO INDEPENDENT WAYS, and pins the result against the one published source.
//
//   Method A — canonical "skyline" DP, memoized (counts; fast).
//   Method B — a direct 3D enumerator that actually lays cubes into a filled[]
//              grid and counts finished fillings (no counting shortcut; the
//              canonical order has to reproduce Method A's number on its own).
//
// Anchor: OEIS A228267 (R. J. Mathar & Rob Pratt) — "Number T(n,k,r) of
// dissections of an n×k×r rectangular cuboid into integer-sided cubes ... read
// by rows." Its data string opens
//   1,1,1,2,1,1,3,1,5,10,1,1,5,1,11,31,1,35,167,2098,...
// and it carries the comment: "The main diagonal T(n,n,n) is
//   1, 2, 10, 2098, 4006722, ...."   — five terms.
// We reproduce that triangle prefix term-for-term, then compute the diagonal
// PAST where the record stops: D(6) = 2954374781704, recorded in no OEIS
// sequence (checked 2026-07-08; both the 5-term diagonal and 2954374781704
// return null from oeis.org). D(7) is attempted separately in cubes.cpp.
//
// Canonical placement (why nothing is double-counted): the next cube's minimum
// corner is ALWAYS the lexicographically-first empty cell — lowest height, then
// row, then column. In profile form that is the column of minimum height, first
// in (row,col) order; a cube of side s dropped there needs an s×s footprint all
// at that same height H, with H+s ≤ C. Each dissection is generated exactly once.
// ─────────────────────────────────────────────────────────────────────────────

let checks = 0, fails = 0;
function eq(label, got, want) {
  checks++;
  const g = String(got), w = String(want);
  const ok = g === w;
  if (!ok) fails++;
  console.log(`  ${ok ? "✓" : "✗ FAIL"}  ${label}: ${g}${ok ? "" : `   (expected ${w})`}`);
}

// ── Method A: canonical profile DP ───────────────────────────────────────────
function T_dp(A, B, C) {
  const NC = A * B;
  const memo = new Map();
  function rec(prof) {
    const key = prof.join(",");
    const hit = memo.get(key);
    if (hit !== undefined) return hit;
    let H = Infinity, idx = -1;
    for (let i = 0; i < NC; i++) if (prof[i] < H) { H = prof[i]; idx = i; }
    let total = 0;
    if (H === C) {
      total = 1;
    } else {
      const r = (idx / B) | 0, c = idx % B;
      const maxs = Math.min(A - r, B - c, C - H);
      for (let s = 1; s <= maxs; s++) {
        let ok = true;
        for (let rr = r; rr < r + s && ok; rr++)
          for (let cc = c; cc < c + s; cc++)
            if (prof[rr * B + cc] !== H) { ok = false; break; }
        if (!ok) break;
        const np = prof.slice();
        for (let rr = r; rr < r + s; rr++)
          for (let cc = c; cc < c + s; cc++) np[rr * B + cc] = H + s;
        total += rec(np);
      }
    }
    memo.set(key, total);
    return total;
  }
  return rec(new Array(NC).fill(0));
}

// ── Method B: direct 3D enumerator (small boxes only) ────────────────────────
function T_enum(A, B, C) {
  const filled = new Uint8Array(A * B * C);
  const at = (r, c, z) => (r * B + c) * C + z;
  let count = 0;
  function firstEmpty() {           // lowest z, then row, then col
    for (let z = 0; z < C; z++)
      for (let r = 0; r < A; r++)
        for (let c = 0; c < B; c++)
          if (!filled[at(r, c, z)]) return [r, c, z];
    return null;
  }
  function rec() {
    const cell = firstEmpty();
    if (!cell) { count++; return; }
    const [r, c, z] = cell;
    const maxs = Math.min(A - r, B - c, C - z);
    for (let s = 1; s <= maxs; s++) {
      let ok = true;
      for (let rr = r; rr < r + s && ok; rr++)
        for (let cc = c; cc < c + s && ok; cc++)
          for (let zz = z; zz < z + s; zz++)
            if (filled[at(rr, cc, zz)]) { ok = false; break; }
      if (!ok) break;
      for (let rr = r; rr < r + s; rr++)
        for (let cc = c; cc < c + s; cc++)
          for (let zz = z; zz < z + s; zz++) filled[at(rr, cc, zz)] = 1;
      rec();
      for (let rr = r; rr < r + s; rr++)
        for (let cc = c; cc < c + s; cc++)
          for (let zz = z; zz < z + s; zz++) filled[at(rr, cc, zz)] = 0;
    }
  }
  rec();
  return count;
}

console.log("Cube dissections into integer cubes — the check\n");

console.log("── the two methods agree on small boxes (DP vs a genuine enumerator) ──");
for (const [A, B, C] of [[1,1,1],[2,2,2],[2,2,3],[3,3,2],[3,3,3],[2,3,3],[2,2,4],[3,3,4],[4,4,2],[4,4,3]]) {
  const dp = T_dp(A, B, C), en = T_enum(A, B, C);
  eq(`T(${A},${B},${C})  DP=ENUM`, dp === en ? dp : `${dp}≠${en}`, dp === en ? dp : `${dp}=${en}`);
}

console.log("\n── the published triangle A228267, reproduced term-for-term (rows n≥k≥r≥1, n=1..4) ──");
const pub = "1,1,1,2,1,1,3,1,5,10,1,1,5,1,11,31,1,35,167,2098";
const mine = [];
for (let n = 1; n <= 4; n++)
  for (let k = 1; k <= n; k++)
    for (let r = 1; r <= k; r++) mine.push(T_dp(n, k, r));
eq("triangle prefix == A228267 data string", mine.join(","), pub);

console.log("\n── the published anchors ──");
eq("T(2,2,r), r=1..7 is Fibonacci", [1,2,3,4,5,6,7].map(r => T_dp(2,2,r)).join(","), "1,2,3,5,8,13,21");
eq("T(3,3,r), r=1..6", [1,2,3,4,5,6].map(r => T_dp(3,3,r)).join(","), "1,5,10,31,76,210");
eq("T(4,4,2)", T_dp(4,4,2), 35);
eq("T(4,4,3)", T_dp(4,4,3), 167);

console.log("\n── the diagonal D(n)=T(n,n,n): the 5 published terms, then PAST the record ──");
const D = [];
for (let n = 1; n <= 6; n++) { const t0 = Date.now(); D.push(T_dp(n, n, n)); if (n >= 5) console.error(`    (D(${n}) took ${((Date.now()-t0)/1000).toFixed(1)}s)`); }
eq("D(1..5) == the OEIS comment", D.slice(0,5).join(","), "1,2,10,2098,4006722");
eq("D(6)  [recorded in no OEIS sequence]", D[5], 2954374781704);

// D(7): computed by the committed C++ solver (needs ~8.6 GB / a few minutes — not
// a CI-time recompute). Its value is recorded in data.json with provenance; this
// check confirms the C++ solver reproduces the whole diagonal we DID recompute
// here, so a reader who runs `cubes.cpp` for n≤6 gets the same numbers verify.mjs
// proves live — which is the trust bridge to its D(7).
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
const here = dirname(fileURLToPath(import.meta.url));
try {
  const data = JSON.parse(readFileSync(join(here, "data.json"), "utf8"));
  eq("data.json diagonal[0..5] matches the live recompute", data.diagonal.slice(0,6).join(","), D.join(","));
  if (data.diagonal.length >= 7 && data.diagonal[6] != null)
    console.log(`  •  data.json records D(7) = ${data.diagonal[6]} (provenance: cubes.cpp; see README)`);
  else
    console.log("  •  data.json records D(7) as not-yet-landed (see README for the attempt's status)");
} catch (e) {
  console.log("  •  data.json not present yet (diagonal recomputed above is the source of truth)");
}

// The page's words about D(7). On 2026-07-xx the adversarial fact-check behind
// /strata/the-anatomy-of-error/ caught this page still calling D(7) "a number with
// nineteen or twenty digits" after it had been computed at 21. The prose was fixed and
// the-anatomy-of-error said "an assertion added so they cannot drift back", but no
// assertion existed until 2026-09-26. These two are it. The page is read from the
// checkout, or else from what artwaste.land serves.
{
  const { existsSync } = await import("node:fs");
  const local = join(here, "../../public/strata/the-count-that-ran-off-the-page/index.html");
  let html = "";
  if (existsSync(local)) html = readFileSync(local, "utf8");
  else { const r = await fetch("https://artwaste.land/strata/the-count-that-ran-off-the-page/"); html = r.ok ? await r.text() : ""; }
  let d7 = null;
  try { d7 = JSON.parse(readFileSync(join(here, "data.json"), "utf8")).diagonal[6]; } catch {}
  // Outside a checkout data.json is absent; take D(7) from the page itself, digits grouped by
  // spaces or by any HTML space entity.
  if (d7 == null) d7 = (html.match(/\d{3}(?:(?:\s|&[a-z]+;|&#\d+;|\u2009|\u00a0|\u202f)\d{3}){6}/) || [""])[0].replace(/&[a-z]+;|&#\d+;/g, "").replace(/\D/g, "");
  const words = { 19: "nineteen", 20: "twenty", 21: "twenty-one", 22: "twenty-two" };
  const n = String(d7).replace(/\D/g, "").length;
  eq("the page names D(7)'s digit count in words", html.includes(`<strong>${words[n]}</strong> digits`), true);
  // The page's own correction note quotes the old sentence, which is allowed; saying it is not.
  const unquoted = html.replace(/"nineteen or twenty digits"/g, "").match(/nineteen or twenty/gi) || [];
  eq('the old "nineteen or twenty digits" survives only as a quotation', unquoted.length, 0);
}

console.log(`\n${fails === 0 ? "ALL PASSED" : "SOME FAILED"} — ${checks - fails}/${checks} checks`);
process.exit(fails === 0 ? 0 : 1);
