#!/usr/bin/env node
/* THE WORD THEY DID NOT USE — offline verifier
 *
 * The page (public/strata/the-word-they-did-not-use/index.html) sets four documents side
 * by side: the Māori and English texts of the Treaty of Waitangi (1840) and of He
 * Whakaputanga (1835). Its central showing is a word count that has to come out a
 * particular way. This file recomputes that count from the shipped page, offline, with no
 * browser, and fails if it moves.
 *
 *   A · The four documents are on the page, and each load-bearing clause is verbatim.
 *   B · The counts. Recomputed by the same rule the page uses (whole words, macron-folded)
 *       over the text extracted from the page's own paragraphs:
 *         kingitanga and mana are ABSENT from the 1840 Māori text;
 *         both are PRESENT in the 1835 Māori text;
 *         kawanatanga and rangatiratanga are present in both.
 *       If any of those changes, the page's argument has changed, and this goes red.
 *   C · Every keyed phrase in texts.js really is a substring of the paragraph it claims.
 *       (The page checks this in the browser too and says so out loud; this is the same
 *       check made to block a build.)
 *   D · The source record lists the witnesses and the disagreements between them.
 *   E · The honesty disciplines the page commits to are actually on the page: it does not
 *       adjudicate the constitutional question, it names the Tribunal's own scope limit,
 *       it names the 1844 dictionary gap, it prints the counter-positions.
 *   F · Every plate the page references exists on disk.
 *
 * Run: node research/te-tiriti/verify.mjs
 */

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

const __dir = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(__dir, "..", "..");
const PAGE_DIR = path.join(ROOT, "public", "strata", "the-word-they-did-not-use");
const PAGE = readFileSync(path.join(PAGE_DIR, "index.html"), "utf8");
const KEYSJS = readFileSync(path.join(PAGE_DIR, "texts.js"), "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 flat = (s) => String(s).replace(/\s+/g, " ");
const FLAT = flat(PAGE);
const on = (needle, label, hay = FLAT) =>
  flat(hay).includes(flat(needle))
    ? ok(label + "  «" + needle.slice(0, 52) + (needle.length > 52 ? "…" : "") + "»")
    : bad(label + " — NOT FOUND: «" + needle + "»");

/* ---------- pull the four documents out of the shipped page ---------- */

function decode(s) {
  return s
    .replace(/<[^>]+>/g, "")
    .replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"').replace(/&#39;/g, "'")
    .replace(/&#8212;/g, "—").replace(/&nbsp;/g, " ")
    .replace(/&#(\d+);/g, (_, d) => String.fromCharCode(Number(d)));
}

function extractDoc(pair, lang) {
  const alignRe = new RegExp(
    `<div class="align" data-pair="${pair}"[^>]*>([\\s\\S]*?)\\n  </div>`, "m");
  const m = PAGE.match(alignRe);
  if (!m) return null;
  const block = m[1];
  const colRe = new RegExp(`<div class="col ${lang}">([\\s\\S]*?)<p class="src">`);
  const c = block.match(colRe);
  if (!c) return null;
  const parts = [...c[1].matchAll(/<section class="part"[\s\S]*?<\/section>/g)].map((x) => x[0]);
  const paras = [];
  for (const sec of parts) {
    for (const p of sec.matchAll(/<p>([\s\S]*?)<\/p>/g)) paras.push(decode(p[1]).trim());
  }
  return paras.join("\n");
}

const DOCS = {
  "mi1840": extractDoc("1840", "mi"),
  "en1840": extractDoc("1840", "en"),
  "mi1835": extractDoc("1835", "mi"),
  "en1835": extractDoc("1835", "en"),
};

console.log("\nA · The four documents are on the page");
for (const [id, t] of Object.entries(DOCS)) {
  t && t.length > 200
    ? ok(`${id} extracted from the page (${t.split(/\s+/).length} words)`)
    : bad(`${id} could not be extracted from index.html`);
}

console.log("\n   the load-bearing clauses, verbatim");
on("te Kawanatanga katoa o o ratou wenua", "1840 mi, article 1: what is ceded");
on("te tino rangatiratanga o o ratou wenua o ratou kainga me o ratou taonga katoa",
   "1840 mi, article 2: what is kept");
on("all the rights and powers of Sovereignty", "1840 en, article 1");
on("the full exclusive and undisturbed possession", "1840 en, article 2 (no commas: the sheet's own)");
on("Ko te Kingitanga, ko te mana i te wenua", "1835 mi, clause 2");
on("All Sovereign powers and authority within the territories", "1835 en, clause 2");
on("me tetahi Kawanatanga hoki kia meatia", "1835 mi: kawanatanga as a function of government");
on("nor any function of Government to be exercised", "1835 en: its English half");
on("Ka wakaputa i te Rangatiratanga o to matou wenua", "1835 mi, clause 1");
on("declare the independence of our country", "1835 en, clause 1");
on("me nga Motu", "1840 mi preamble reads Motu, not notu");

/* ---------- the counts, by the page's own rule ---------- */

const WORD_RE = /[A-Za-zĀĒĪŌŪāēīōū][A-Za-zĀĒĪŌŪāēīōū'’]*/g;
const fold = (s) => String(s)
  .replace(/[āĀ]/g, "a").replace(/[ēĒ]/g, "e").replace(/[īĪ]/g, "i")
  .replace(/[ōŌ]/g, "o").replace(/[ūŪ]/g, "u")
  .toLowerCase();

function count(docId, word) {
  const t = DOCS[docId] || "";
  const q = fold(word);
  return (t.match(WORD_RE) || []).filter((w) => fold(w) === q).length;
}

console.log("\nB · The counts — recomputed from the page's own paragraphs");
const expect = [
  ["mi1840", "kingitanga", 0, "ABSENT from the 1840 Māori text"],
  ["mi1840", "mana", 0, "ABSENT from the 1840 Māori text"],
  ["mi1835", "kingitanga", 1, "present once in 1835"],
  ["mi1835", "mana", 1, "present once in 1835"],
];
for (const [d, w, n, note] of expect) {
  const got = count(d, w);
  got === n ? ok(`${w} in ${d} = ${got}  (${note})`)
            : bad(`${w} in ${d} = ${got}, expected ${n}  (${note})`);
}
for (const [d, w] of [["mi1840", "kawanatanga"], ["mi1835", "kawanatanga"],
                      ["mi1840", "rangatiratanga"], ["mi1835", "rangatiratanga"]]) {
  const got = count(d, w);
  got > 0 ? ok(`${w} in ${d} = ${got}  (present, as the page says)`)
          : bad(`${w} in ${d} = 0, expected at least one`);
}
// the negative claim is only interesting if the search would have found the word:
// prove the counter works by finding a word we know is there.
count("mi1840", "rangatira") > 0
  ? ok(`control: rangatira in mi1840 = ${count("mi1840", "rangatira")} (the counter is not simply blind)`)
  : bad("control failed: rangatira not found in mi1840, so the zeroes prove nothing");
// and prove whole-word matching really is whole-word
count("mi1840", "ranga") === 0
  ? ok("control: 'ranga' = 0, so the counter is not substring-matching")
  : bad("counter appears to substring-match: 'ranga' should be 0");

/* ---------- keyed phrases ---------- */

console.log("\nC · Every keyed phrase in texts.js is really on the page");
{
  const KEYS_ONLY = KEYSJS.slice(0, KEYSJS.indexOf("var PAIRS"));
  const keys = [...KEYS_ONLY.matchAll(/mi:\s*(['"])([\s\S]*?)\1,?\s*\n?\s*en:\s*(['"])([\s\S]*?)\3/g)]
    .map((m) => ({ mi: m[2], en: m[4] }));
  keys.length >= 12 ? ok(`${keys.length} keyed pairs found in texts.js`)
                    : bad(`only ${keys.length} keyed pairs parsed from texts.js, expected 12+`);
  let missing = [];
  for (const k of keys) {
    if (!PAGE.includes(k.mi)) missing.push("mi: " + k.mi);
    if (!PAGE.includes(k.en)) missing.push("en: " + k.en);
  }
  missing.length === 0
    ? ok(`all ${keys.length * 2} keyed phrases are substrings of index.html`)
    : bad(`${missing.length} keyed phrase(s) not on the page: ${missing.join(" | ")}`);
}

/* ---------- source record ---------- */

console.log("\nD · The source record names its witnesses and their disagreements");
on("Waitangi Sheet", "sources.txt records the 1840 Māori witness", SRC);
on("Buick", "sources.txt records the public-domain printed witness", SRC);
on("1837", "sources.txt records the 1837 printing of He Whakaputanga", SRC);
on("me nga notu", "sources.txt records the Wikisource error it corrects", SRC);
on("ne nga Rangatira", "sources.txt records the second Wikisource error", SRC);
on("not proofread", "sources.txt states the comparison witness's own quality flag", SRC);

/* ---------- honesty disciplines ---------- */

console.log("\nE · The honesty disciplines are actually on the page");
on("takes no position on the constitutional question", "refuses to adjudicate");
on("we say nothing about how and when the Crown acquired the sovereignty",
   "prints the Tribunal's own scope limit, not just its finding");
on("This report doesn't change that fact", "prints the Crown's response too");
on("Fletcher", "prints the serious counter-position");
on("Hohepa", "prints the argument that the text was easy to understand");
on("Te Haara", "prints the argument that kāwana named a lesser office");
on("first edition of 1844 is the one we wanted", "names the dictionary we could not get");
on("It counts word forms, not meanings", "states what the counter is not");
on("Contrast has been raised", "declares the only change made to the photographs");
on("in copyright", "explains why Kāwharu's translation is not used");
on("does not entirely satisfy me as an historian", "gives the Littlewood doubt its own words");
/[Tt]he 1871 edition/.test(PAGE) || /third edition of\s*\n?\s*1871/.test(PAGE)
  ? ok("confirms the dictionary gap against a second edition")
  : bad("does not confirm the dictionary gap against the 1871 edition");

console.log("\nF · Plates on disk");
for (const f of [...new Set([...PAGE.matchAll(/src="\.\/([^"]+\.jpg)"/g)].map((m) => m[1]))]) {
  existsSync(path.join(PAGE_DIR, f)) ? ok("plate present: " + f)
                                     : bad("plate MISSING: " + f);
}

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