#!/usr/bin/env node
/* THE BREAD WITH NO NAME: offline verifier
 *
 * Checks selected quotation strings, named LINEUP excerpts and author-assigned
 * flags in public/strata/the-bread-with-no-name/index.html. Recomputes the tally
 * for those five witnesses. It does not independently verify every historical
 * claim or compare every quotation with an external edition.
 *
 * A: selected Greek strings. B: the two Latin adjectives.
 * C: selected English excerpts in their named rows, then the stored-data tally.
 * D: the page's Douay split statement. E: selected qualifications and parse.
 * F: key strings present in sources.txt.
 *
 * Run: node research/the-bread-with-no-name/verify.mjs
 */

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

const __dir = path.dirname(fileURLToPath(import.meta.url));
const PAGE = readFileSync(
  path.join(__dir, "..", "..", "public", "strata", "the-bread-with-no-name", "index.html"),
  "utf8",
);
const SRC = readFileSync(path.join(__dir, "sources.txt"), "utf8");

let pass = 0, fail = 0;
const ok  = (m) => { pass++; console.log("  \x1b[32m✓\x1b[0m " + m); };
const bad = (m) => { fail++; console.log("  \x1b[31m✗ " + m + "\x1b[0m"); };
const on  = (needle, label) =>
  PAGE.includes(needle) ? ok(label + "  «" + needle.slice(0, 46) + (needle.length > 46 ? "…" : "") + "»")
                        : bad(label + ": NOT FOUND: «" + needle + "»");

console.log("\nA · Greek: selected strings");
on("τὸν ἄρτον ἡμῶν τὸν ", "Mt/Lk stem");
on("ἐπιούσιον", "the word");
on("δὸς ἡμῖν σήμερον", "Mt: give-today (aorist)");
on("δίδου ἡμῖν τὸ καθ’ ἡμέραν", "Lk: keep-giving day-by-day (present)");
// Count occurrences in the source; this is not a check of both complete clauses.
{
  const n = (PAGE.match(/ἐπιούσιον/g) || []).length;
  n >= 2 ? ok(`ἐπιούσιον appears at least twice (${n}× in page source)`)
         : bad(`ἐπιούσιον should appear ≥2×, found ${n}`);
}

console.log("\nB · Latin — Jerome's fork");
on("supersubstantialem", "Vulgate Matthew");
on("cotidianum", "Vulgate Luke");
("supersubstantialem" !== "cotidianum") ? ok("the two Latin words are distinct")
                                        : bad("Latin words not distinct");

// Read the displayed row data, so historical wording in Corrections cannot
// satisfy a quotation check for a wrongly labelled row.
const lineupMatch = PAGE.match(/var LINEUP = (\[[\s\S]*?\]);/);
let rows = null;
try { if (lineupMatch) rows = eval(lineupMatch[1]); } catch { /* reported below */ }
const rowOn = (matches, needle, label) =>
  rows?.some((row) => matches(row) && row.rd.includes(needle))
    ? ok(label) : bad(label + ": excerpt absent from the named row");

console.log("\nC · English line-up: selected excerpts in named rows");
rowOn((r) => /Earlier/.test(r.who), "breed ouer other substaunce", "Wyclif Earlier: Forshall and Madden, p. 14");
rowOn((r) => /Later.*Noble/.test(r.who) && r.note.includes("variant"), "each day’s bread", "Wyclif Later: Noble's modern rendering of a daily variant");
rowOn((r) => /Tyndale/.test(r.who), "oure dayly breede", "Tyndale 1526 (Mt)");
rowOn((r) => /Douay/.test(r.who), "supersubstantial bread", "Douay-Rheims (Mt)");
rowOn((r) => /King James/.test(r.who), "daily bread", "KJV 1611 (Mt)");

console.log("\nC · English line-up — recompute the tally from the page's own data");
// Recompute only the claims made about the selected rows.
if (!rows) {
  bad("could not read LINEUP data block on the page");
} else {
  const sub = rows.filter((r) => r.substance);
  const subAllLatin = sub.length > 0 && sub.every((r) => r.fromLatin);
  const greek = rows.filter((r) => r.src === "Greek");
  const greekAllDaily = greek.length === 2 && greek.every((r) => !r.substance && /dayly|daily/.test(r.rd));
  const latin = rows.filter((r) => r.fromLatin);
  const latinButDaily = latin.filter((r) => !r.substance);
  rows.length === 5 && latin.length === 3
    ? ok("line-up has 5 selected witnesses, 3 marked Vulgate-derived")
    : bad(`expected 5 witnesses and 3 Vulgate flags, got ${rows.length} and ${latin.length}`);
  sub.length === 2 ? ok('exactly 2 displayed rows keep a "substance" reading (Wyclif Earlier + Douay)')
                   : bad(`expected exactly 2 substance readings, got ${sub.length}`);
  subAllLatin ? ok("both displayed substance rows are marked as from the Vulgate")
              : bad("a displayed substance row is not marked as Vulgate-derived");
  greekAllDaily ? ok('the two displayed Greek-based rows read "dayly" or "daily"')
                : bad('the displayed Greek-based rows do not both read "dayly" or "daily"');
  latinButDaily.length === 1 && /Noble/.test(latinButDaily[0].who)
    ? ok("one Vulgate-derived row is marked daily: Noble's Later Version rendering")
    : bad("expected one Vulgate-derived daily row, identified as Noble's rendering");
  const dr = rows.find((r) => /Douay/.test(r.who));
  const wev = rows.find((r) => /Earlier/.test(r.who));
  dr && dr.substance && dr.fromLatin && wev && wev.substance && wev.fromLatin
    ? ok("the two stored substance witnesses are Wyclif Earlier + Douay, both marked Vulgate")
    : bad("substance witnesses are not the expected Wyclif-Earlier + Douay/Vulgate pair");
  /subCount \+ ' of ' \+ LINEUP\.length/.test(PAGE)
    ? ok("the on-page readout is composed from these same recomputed counts")
    : bad("could not find the readout composition in the page script");
}

console.log("\nD · Douay-Rheims reproduces Jerome's split");
(/supersubstantial bread[\s\S]{0,120}Matthew[\s\S]{0,200}daily bread[\s\S]{0,40}Luke/i.test(PAGE)
  || /Matthew[\s\S]{0,120}supersubstantial[\s\S]{0,400}Luke[\s\S]{0,120}daily/i.test(PAGE))
  ? ok("page states Douay Mt=supersubstantial, Lk=daily")
  : bad("could not find the Douay Mt/Lk split statement");

console.log("\nE · Honesty disciplines actually present on the page");
on("ἐλαίου", "papyrus re-read as “of oil” (the vanished attestation)");
on("Sammelbuch", "names the papyrus (Sayce/Metzger story)");
on("essentially", "hedges the hapax claim precisely");
on("mahar", "Jerome's Gospel-of-the-Hebrews “tomorrow” note");
on("Later Version", "Wyclif version disambiguated");
on("Origen", "Origen's coinage testimony attributed");
/does not tell you which derivation is correct/i.test(PAGE)
  ? ok("names the etymology as unresolved, refuses to pick")
  : bad("does not flag the etymology as unresolved");
// The proposed participial derivation must not prefix epi a second time.
let epiousa = null;
try {
  const match = PAGE.match(/var READINGS = ({[\s\S]*?});/);
  if (match) epiousa = eval("(" + match[1] + ")").epiousa;
} catch { /* reported below */ }
(epiousa && epiousa.parse.length === 1 && epiousa.parse[0] === "ἡ ἐπιοῦσα (ἡμέρα)"
  && epiousa.meta.includes("ἔπειμι") && epiousa.meta.includes("not of εἰμί"))
  ? ok("tomorrow option uses the already-prefixed participle, from ἔπειμι, without an extra epi")
  : bad("the proposed ἐπιοῦσα parse or its verb attribution is wrong");
on("Challoner", "Douay wording attributed to Challoner, not verbatim-1582");
on("Clementine", "Latin text-form (cotidie/hodie) noted");

console.log("\nF · Source record present");
SRC.includes("supersubstantialem") && SRC.includes("cotidianum") && SRC.includes("ἐπιούσιον")
  ? ok("sources.txt records the key Greek+Latin verbatim strings")
  : bad("sources.txt missing key strings");

console.log(`\n${fail === 0 ? "\x1b[32m" : "\x1b[31m"}${pass}/${pass + fail} checks passed\x1b[0m`);
process.exit(fail ? 1 : 0);
