#!/usr/bin/env node
/* THE BARE PROPOSITION — offline verifier
 *
 * Asserts:
 *  (1) The Tractatus has 526 propositions.
 *  (2) Of the 7 top-level propositions, only proposition 7 has zero descendants.
 *  (3) The descendant counts are { 1→6, 2→78, 3→73, 4→108, 5→150, 6→104, 7→0 }.
 *  (4) The depth distribution is { 1:7, 2:25, 3:124, 4:245, 5:118, 6:7 }.
 *  (5) The preface and proposition 7 use distinct verbs (reden vs sprechen).
 *  (6) Ogden's English uses "speak" for both — the flattening is real.
 *
 * Source: Project Gutenberg eBook 5740 — Tractatus, bilingual edition
 * (German + Ogden 1922 English), TeX source.
 *
 * Run: node research/the-bare-proposition/verify.mjs
 */

import { readFileSync, existsSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const TEX_PATH = path.join(__dirname, "tractatus-5740.tex");

if (!existsSync(TEX_PATH)) {
  console.error("Missing Gutenberg 5740 TeX source at", TEX_PATH);
  console.error("Download with: curl -sL 'https://www.gutenberg.org/files/5740/5740-t/5740-t.tex' -o", TEX_PATH);
  process.exit(2);
}

const tex = readFileSync(TEX_PATH, "utf8");

let passed = 0, failed = 0;
function check(label, ok, detail) {
  const tag = ok ? "✓" : "✗";
  console.log(`  ${tag} ${label}${detail ? "  " + detail : ""}`);
  if (ok) passed++; else failed++;
}

console.log("\nTHE BARE PROPOSITION — verify\n");
console.log("Source: Gutenberg 5740 (Tractatus bilingual, Kegan Paul 1922)\n");

// ---- extract propositions ---------------------------------------------------
const reG = /\\PropositionG\{([0-9.]+)\}/g;
const reE = /\\PropositionE\{([0-9.]+)\}/g;
const propsG = [...tex.matchAll(reG)].map(m => m[1]);
const propsE = [...tex.matchAll(reE)].map(m => m[1]);

console.log("[A] STRUCTURAL FINDINGS\n");

// (1) — same number in both languages
check("German section has the same proposition numbers as English",
  propsG.length === propsE.length && propsG.every((p, i) => p === propsE[i]),
  `  (G=${propsG.length}, E=${propsE.length})`);

// (2) — 526 propositions
check("Total proposition count is 526",
  propsG.length === 526,
  `  (found ${propsG.length})`);

// (3) — exact descendant counts per top-level
const expected = { 1: 6, 2: 78, 3: 73, 4: 108, 5: 150, 6: 104, 7: 0 };
const counts = {};
for (const p of propsG) {
  const top = p.split(".")[0];
  // count this proposition under its top-level (excluding the top-level itself,
  // which is the "0" depth for its own subtree). Use `in` because 0 is falsy.
  if (!(top in counts)) counts[top] = -1; // start at -1 so the top-level itself counts as 0
  counts[top]++;
}

for (let n = 1; n <= 7; n++) {
  check(`Proposition ${n} has ${expected[n]} descendants`,
    counts[String(n)] === expected[n],
    `  (found ${counts[String(n)]})`);
}

// (4) — proposition 7 stands ALONE — the load-bearing structural fact
// Read from the computed counts (until 2026-09-29 this filtered `expected`, so it could not fail).
const onlyBare = Object.entries(counts).filter(([, c]) => c === 0).map(([n]) => n);
check("Exactly one top-level proposition has zero descendants",
  onlyBare.length === 1 && onlyBare[0] === "7",
  `  (the only bare top-level is prop ${onlyBare.join(", ")})`);

// (4b) — "only one" is true of the seven top-level propositions, not of all 526:
// many deeper propositions have no comments either (1.11, 6.54, ...). The page says "top-level".
{
  const set = new Set(propsG);
  const hasChild = q => propsG.some(r => r !== q && (q.includes(".") ? r.startsWith(q) && r.length === q.length + 1 : r.startsWith(q + ".") && r.split(".")[1].length === 1));
  const leaves = propsG.filter(q => !hasChild(q));
  check("Propositions with no comments at all: more than one (so the claim must say 'top-level')",
    leaves.length > 1 && set.has("6.54") && leaves.includes("6.54"), `  (${leaves.length} of ${propsG.length}, e.g. 1.11, 6.54)`);
}

// (4c) — the proposition is nine German words
check("Proposition 7 in German is nine words",
  "Wovon man nicht sprechen kann, darüber muss man schweigen.".split(/\s+/).length === 9 && /Wovon man nicht sprechen kann, darüber muss\s+man schweigen/.test(tex),
  "  (Wovon man nicht sprechen kann, darüber muss man schweigen.)");

// (5) — depth distribution
const depthCounts = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0 };
for (const p of propsG) {
  const parts = p.split(".");
  const depth = parts.length === 1 ? 1 : 1 + parts[1].length;
  depthCounts[depth]++;
}
const expectedDepth = { 1: 7, 2: 25, 3: 124, 4: 245, 5: 118, 6: 7 };
for (const d of Object.keys(expectedDepth)) {
  check(`Depth ${d}: ${expectedDepth[d]} propositions`,
    depthCounts[d] === expectedDepth[d],
    `  (found ${depthCounts[d]})`);
}

console.log("\n[B] LEXICAL FINDINGS\n");

// (6) — preface verb is reden, prop 7 verb is sprechen — same word otherwise
const PREFACE_DE = /Was sich überhaupt sagen lässt, lässt\s+sich klar sagen; und wovon man nicht (reden|sprechen) kann, darüber\s+muss man (schweigen|reden|sprechen)\./;
const prefM = tex.match(PREFACE_DE);
check("Preface ending uses the verb 'reden'",
  !!prefM && prefM[1] === "reden",
  prefM ? `  (verb is '${prefM[1]}')` : "  (regex did not match — investigate)");
check("Preface ending uses the verb 'schweigen'",
  !!prefM && prefM[2] === "schweigen",
  prefM ? `  (verb is '${prefM[2]}')` : "");

const PROP7_DE = /\\PropositionG\{7\}\s*\{Wovon man nicht (\w+) kann, darüber muss\s+man (\w+)\.\}/;
const p7M = tex.match(PROP7_DE);
check("Proposition 7 uses the verb 'sprechen'",
  !!p7M && p7M[1] === "sprechen",
  p7M ? `  (verb is '${p7M[1]}')` : "");
check("Proposition 7 uses the verb 'schweigen'",
  !!p7M && p7M[2] === "schweigen",
  p7M ? `  (verb is '${p7M[2]}')` : "");

check("THE FINDING: preface verb differs from proposition 7 verb (reden ≠ sprechen)",
  !!prefM && !!p7M && prefM[1] !== p7M[1],
  prefM && p7M ? `  ('${prefM[1]}' vs '${p7M[1]}')` : "");

// (7) — Ogden flattens both to "speak"
const PREFACE_EN = /summed up\s+somewhat as follows: What can be said at all can be said\s+clearly; and whereof one cannot (\w+) thereof one must\s+be (\w+)\./;
const prefEnM = tex.match(PREFACE_EN);
check("Ogden's preface English uses 'speak'",
  !!prefEnM && prefEnM[1] === "speak",
  prefEnM ? `  (verb is '${prefEnM[1]}')` : "");

const PROP7_EN = /\\PropositionE\{7\}\s*\{Whereof one cannot (\w+), thereof one must be\s+(\w+)\.\}/;
const p7EnM = tex.match(PROP7_EN);
check("Ogden's prop 7 English uses 'speak'",
  !!p7EnM && p7EnM[1] === "speak",
  p7EnM ? `  (verb is '${p7EnM[1]}')` : "");

check("THE FLATTENING: Ogden uses the same English verb for both German verbs",
  !!prefEnM && !!p7EnM && prefEnM[1] === p7EnM[1],
  prefEnM && p7EnM ? `  (both '${prefEnM[1]}')` : "");

// (8) — the ladder image is in proposition 6.54
const LADDER = /\\PropositionG\{6\.54\}[\s\S]*?Leiter[\s\S]*?wegwerfen/;
check("Proposition 6.54 (German) contains 'die Leiter wegwerfen' — throw away the ladder",
  LADDER.test(tex), "");

// (9) — the dedication is to David Pinsent (factual nail-down)
check("Tractatus is dedicated to David H. Pinsent",
  /DAVID H\. PINSENT/.test(tex), "");

// (10) — the decimal-numbering footnote
const DECIMAL = /decimal figures as numbers of the separate propositions indicate the logical/;
check("Wittgenstein's decimal-numbering footnote is present in the English text",
  DECIMAL.test(tex), "");

// ---- summary ----------------------------------------------------------------
console.log("");
console.log("=".repeat(60));
console.log(`PASSED: ${passed}`);
console.log(`FAILED: ${failed}`);
console.log("=".repeat(60));

if (failed > 0) {
  console.log("\nVerifier FAILED — do not publish until the offline check passes.");
  process.exit(1);
}
console.log("\nVerifier PASSED — the structural and lexical findings hold.\n");
process.exit(0);
