#!/usr/bin/env node
/* FOR WANT OF A BETTER TERM — offline verifier
 *
 * The page reproduces, byte-for-byte (modulo line-wrapping, Gutenberg
 * italic underscores, [n] footnote markers, and straight-vs-curly
 * quotes), the Chinese Analects passages that contain 仁 and three
 * public-domain English translations of them. Everything checkable on
 * the page is checked here against the named local source.
 *
 *   A · Chinese. Each 仁-bearing passage quoted on the page is checked
 *       against the received text saved from the Chinese Text Project
 *       (ctext.org/analects), one JSON file per book.
 *
 *   B · The count. 仁 is recomputed across all 20 books: it must occur
 *       109 times in 59 passages, exactly as the page claims.
 *
 *   C · Three English translators. Every English quotation on the page
 *       is checked against its named Project Gutenberg text — Legge 1893
 *       (ebook 3330), Giles 1907 (ebook 46389), Lyall 1909 (ebook 24055).
 *
 *   D · Ku Hung-ming (1898). The page reports his gloss from an OCR scan;
 *       the one quoted phrase ("means literally ... humanity") is checked
 *       to be present in that scan.
 *
 *   E · Etymology. The Shuōwén Jiězì gloss 親也。从人从二 quoted on the
 *       page is checked against the saved ctext dictionary page for 仁.
 *
 *   F · Honest-edge tags. Small disciplines the page commits to perform.
 *
 * Run: node research/analects-ren/verify.mjs
 */

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

const __dir = path.dirname(fileURLToPath(import.meta.url));
const R = (f) => readFileSync(path.join(__dir, f), "utf8");
const PAGE = readFileSync(path.join(__dir, "..", "..", "public", "strata", "for-want-of-a-better-term", "index.html"), "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"); };

// --- normalisers ---
const normEN = (s) => s
  .replace(/[‘’]/g, "'")
  .replace(/[“”]/g, '"')
  .replace(/_/g, "")             // Gutenberg italic markers
  .replace(/\[\d+\]/g, "")       // footnote markers, e.g. True virtue[2]
  .replace(/\s+/g, " ")
  .trim();
const normZH = (s) => s.replace(/\s+/g, "");
const pageEN = normEN(PAGE.replace(/<[^>]+>/g, ""));   // strip tags, normalise
const pageZH = normZH(PAGE.replace(/<[^>]+>/g, ""));

// ---------- A · Chinese passages ----------
console.log("\nA · Chinese passages (ctext received text)");
const ZH = {
  "xue-er":        ["巧言令色，鮮矣仁"],
  "li-ren":        ["里仁為美"],
  "yong-ye":       ["夫仁者，己欲立而立人，己欲達而達人"],
  "yan-yuan":      ["克己復禮為仁", "樊遲問仁。子曰：「愛人。」"],
  "wei-ling-gong": ["志士仁人，無求生以害仁，有殺身以成仁"],
};
for (const [book, passages] of Object.entries(ZH)) {
  const src = normZH(JSON.parse(R(`zh-${book}.json`)).fulltext.join(""));
  for (const p of passages) {
    const pn = normZH(p);
    const inSrc = src.includes(pn);
    const onPage = pageZH.includes(pn);
    (inSrc && onPage) ? ok(`${book}: 「${p}」 — in source & on page`)
                      : bad(`${book}: 「${p}」 — source:${inSrc} page:${onPage}`);
  }
}

// ---------- B · the 109 / 59 count ----------
console.log("\nB · occurrence count of 仁");
let total = 0, passages = 0;
for (const f of readdirSync(__dir).filter(f => f.startsWith("zh-") && f.endsWith(".json"))) {
  for (const para of JSON.parse(R(f)).fulltext) {
    const c = (para.match(/仁/g) || []).length;
    total += c;
    if (c) passages++;
  }
}
(total === 109) ? ok(`仁 occurs ${total} times (page claims 109)`) : bad(`仁 occurs ${total}, expected 109`);
(passages === 59) ? ok(`仁 appears in ${passages} passages (page claims 59)`) : bad(`仁 in ${passages} passages, expected 59`);
(pageEN.includes("109 times in 59 passages") || pageEN.includes("109 OCCURRENCES")) ? ok("page states the count") : bad("page omits the count");

// ---------- C · English translators ----------
console.log("\nC · English quotations (Project Gutenberg)");
const SRC = {
  legge: normEN(R("legge-1893-gutenberg3330.txt")),
  giles: normEN(R("giles-1907-gutenberg46389.txt")),
  lyall: normEN(R("lyall-1909-gutenberg24055.txt")),
};
const QUOTES = {
  legge: [
    "Fine words and an insinuating appearance are seldom associated with true virtue.",
    "It is virtuous manners which constitute the excellence of a neighborhood.",
    "Now the man of perfect virtue, wishing to be established himself, seeks also to establish others; wishing to be enlarged himself, he seeks also to enlarge others.",
    "Yen Yuan asked about perfect virtue. The Master said, 'To subdue one's self and return to propriety, is perfect virtue.",
    "Fan Ch'ih asked about benevolence. The Master said, 'It is to love all men.'",
    "The determined scholar and the man of virtue will not seek to live at the expense of injuring their virtue. They will even sacrifice their lives to preserve their virtue complete.",
    "the root of all benevolent actions?",
  ],
  giles: [
    "True virtue rarely goes with artful speech and insinuating looks.",
    "It is the spirit of charity which makes a locality good to dwell in.",
    "The man of moral virtue, wishing to stand firm himself, will lend firmness unto others; wishing himself to be illuminated, he will illuminate others.",
    "Yen Yuan inquired as to the meaning of true goodness.",   // ü normalises below
    "The most important word in the Confucian vocabulary is jen, which in the following extracts is translated \"virtue\" only for want of a better term.",
  ],
  lyall: [
    "Smooth words and fawning looks are seldom found with love.",
    "Love makes a spot beautiful: who chooses not to dwell in love, has he got wisdom?",
    "Seeking a foothold for self, love finds a foothold for others; seeking light for itself, it enlightens others too.",
    "Yen Yuean asked, What is love? The Master said, Love is to conquer self and turn to courtesy.",
    "Fan Ch'ih asked, What is love? The Master said, To love men.",
    "A high will, or a loving heart, will not seek life at cost of love. To fulfil love they will kill the body.",
  ],
};
// strip the umlaut/diacritic for the one Giles line that uses Yen Yüan / jên
const deDia = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "");
for (const [who, quotes] of Object.entries(QUOTES)) {
  const src = deDia(SRC[who]);
  for (const q of quotes) {
    const qn = deDia(normEN(q));
    const inSrc  = src.includes(qn);
    const onPage = deDia(pageEN).includes(qn);
    (inSrc && onPage) ? ok(`${who}: “${q.slice(0,42)}…” — in source & on page`)
                      : bad(`${who}: “${q.slice(0,42)}…” — source:${inSrc} page:${onPage}`);
  }
}

// Check the opening quotation separately from the later Giles witness.
const openingGiles = PAGE.match(/<p>Lionel Giles,[\s\S]*?<\/p>/)?.[0] || "";
const openingWords = normEN(openingGiles.replace(/<[^>]+>/g, ""));
const openingQuote = "is jên, which in the following extracts is translated";
(openingWords.includes(openingQuote) && SRC.giles.includes(openingQuote))
  ? ok("Giles opening quotation retains the source's jên")
  : bad("Giles opening quotation differs from the source's jên");

// ---------- D · Ku Hung-ming (OCR scan) ----------
console.log("\nD · Ku Hung-ming gloss (OCR scan)");
const ku = normEN(R("ku-hungming-1898-archive.txt"));
(ku.includes("means literally") && ku.toLowerCase().includes("humanity"))
  ? ok('Ku scan contains "means literally … humanity"')
  : bad("Ku scan missing the quoted gloss");
pageEN.includes('"humanity."') || pageEN.includes("'humanity.'") || pageEN.includes("means literally")
  ? ok("page reports Ku's gloss") : bad("page omits Ku's gloss");

// ---------- E · etymology ----------
console.log("\nE · Shuōwén etymology");
const shuowen = R("shuowen-ctext-ren.html").replace(/\s+/g, "");
shuowen.includes("親也。从人从二")
  ? ok("Shuōwén source contains 親也。从人从二") : bad("Shuōwén source missing the gloss");
pageZH.includes("親也。从人从二")
  ? ok("page quotes 親也。从人从二") : bad("page omits the Shuōwén gloss");

// ---------- F · honest-edge tags ----------
console.log("\nF · honest-edge disciplines");
const tags = [
  ["names Lyall's single-word strategy", /Lyall.{0,40}love/i],
  ["names Giles's confession",            /for want of a better term/i],
  ["names the XII.22 irony (愛人 / love people)", /love people/i],
  ["names the public-domain gallery as an editorial choice", /gallery[’']s restriction to public-domain translations is an editorial choice/i],
  ["names that Giles/Ku are selections",  /selection|abridg/i],
  ["names no-translator-is-wrong",        /no one was wrong|never that a translator erred|No one is wrong/i],
];
for (const [label, re] of tags) {
  re.test(PAGE) ? ok(label) : bad("missing: " + label);
}

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