#!/usr/bin/env node
/* THE COLOUR OF THE SEA — offline verifier
 *
 * The page (public/strata/wine-dark-sea/index.html) dissects Homer's epithet
 * οἶνοψ πόντος ("wine-faced / wine-dark sea") across six public-domain English
 * translations, alongside the genuine 19th-c. "no word for blue" controversy.
 * What it checks is listed below; it checks key phrases, not every word, and
 * it trusts each excerpt's header for the locus the excerpt comes from (it does
 * not re-derive a locus from the Greek). Figures and dates are not checked,
 * except the one count in A.
 *
 *   A · Greek. Key Greek phrases quoted on the page are checked against the
 *       Perseus/Scaife lines saved in greek-perseus.txt, and confirmed present
 *       on the page. The page's count of οἶνοψ used of the sea (17: 5 Il.,
 *       12 Od.) is recounted from the [SEA ...] lines saved there.
 *
 *   B · English translators. A key phrase of each English rendering that KEEPS
 *       a sea-colour (alignment rows, the Cowper and Chapman lines quoted in the
 *       prose, and Worsley's 1861 line quoted in the dated correction note) is
 *       checked to be present BOTH in its named source excerpt (Gutenberg, or the
 *       Internet Archive for Chapman's Iliads and Worsley) AND on the page.
 *       Each alignment row's excerpt is cut from that row's locus (Od. 1.183 or
 *       Il. 2.613), as its header records.
 *
 *   C · The dropped epithets. Where the page shows a translator dropping the
 *       sea-colour (Pope's Iliad and Odyssey, Butler), the verbatim line it shows
 *       is confirmed in the source excerpt for that locus.
 *
 *   D · Gladstone. Both halves of the block-quotation from Studies on Homer
 *       vol. III, and his conclusion on colour (p. 488), are checked
 *       (OCR-normalised) against the saved excerpt; "in the bud only" (his
 *       phrase for the picturesque, p. 419) must NOT be given as his verdict.
 *
 *   E · Honest-edge disciplines the page commits to.
 *
 * Run: node research/wine-dark-sea/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 R = (f) => readFileSync(path.join(__dir, f), "utf8");
// The excerpt files open with a header (SOURCE, URL, what the excerpt is) ended by a
// line "---". A source check must find its phrase in the excerpt itself, never in
// the header that describes it, so sources are read from after that line (2026-10-11,
// claims pass: the header of one new excerpt quoted the very phrase it was checked for).
const BODY = (f) => { const t = R(f); const m = t.match(/^---[ \t]*$/m); return m ? t.slice(m.index + m[0].length) : t; };
const PAGE = readFileSync(
  path.join(__dir, "..", "..", "public", "strata", "wine-dark-sea", "index.html"),
  "utf8",
);

// The authored page, for checks that a corrected claim has not come back: the
// generated blocks (aw-*:start … aw-*:end) are rewritten by the site's backfill
// scripts from other files and are excluded, and so is the dated "Corrected …"
// note, which names the old wording on purpose.
const AUTHORED = PAGE
  .replace(/<!--aw-([a-z]+):start-->[\s\S]*?<!--aw-\1:end-->/g, "")
  .replace(/<p>Corrected \d{4}-\d{2}-\d{2}[\s\S]*?<\/p>/g, "");

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, " ")        // strip HTML tags
  .replace(/&amp;/g, "&")
  .replace(/&middot;|&nbsp;/g, " ")
  .replace(/[‘’]/g, "'")
  .replace(/[“”]/g, '"')
  .replace(/[–—]/g, "-")           // en/em dash -> hyphen (Gutenberg vs page)
  .replace(/_/g, "")               // Gutenberg italic markers
  .replace(/\[\d+\]/g, "")         // footnote markers
  .replace(/\s+/g, " ")
  .replace(/\s+([,.;:!?])/g, "$1") // tag-strip leaves a space before punctuation
  .trim();
const normGK = (s) => s
  .replace(/<[^>]+>/g, " ")
  .replace(/\s+/g, " ")
  .trim();

const pageEN = normEN(PAGE);
const pageGK = normGK(PAGE);

// ---------- A · Greek ----------
console.log("\nA · Greek (Perseus / Scaife)");
const GK = normGK(BODY("greek-perseus.txt"));
const GK_CHECKS = [
  ["οἴνοπα πόντον", "the wine-faced-sea formula (Od. 1.183 / Il. 2.613)"],
  ["ἁλὸς πολιῆς", "the GREY sea (Il. 1.350)"],
  ["ἰοειδέα πόντον", "the VIOLET sea (Od. 11.107)"],
  ["πολιῆς ἁλὸς", "Cowper's GREY sea in Telemachus' prayer (Od. 2.261)"],
  ["ἠεροειδέα πόντον", "the MISTY sea of the same prayer (Od. 2.263), not οἶνοψ"],
  ["μείλανι πόντῳ", "the DARK sea (Il. 24.79)"],
];
for (const [g, label] of GK_CHECKS) {
  const inSrc = GK.includes(g);
  const onPage = pageGK.includes(g);
  (inSrc && onPage) ? ok(`${label}: «${g}» — in source & on page`)
                    : bad(`${label}: «${g}» — source:${inSrc} page:${onPage}`);
}
// the count: οἶνοψ of the sea, recounted from the [SEA ...] lines saved from Perseus
{
  const sea = [...BODY("greek-perseus.txt").matchAll(/^\[SEA (Il|Od)\. [\d.]+\] (.*)$/gm)];
  const allOinop = sea.every((m) => /οἴνοπ/.test(m[2]));
  const il = sea.filter((m) => m[1] === "Il").length;
  const od = sea.filter((m) => m[1] === "Od").length;
  const want = `${il + od}× of the sea (${il} Il., ${od} Od.)`;
  (allOinop && il === 5 && od === 12 && PAGE.includes(want))
    ? ok(`οἶνοψ of the sea: ${il + od} saved lines (${il} Il., ${od} Od.); page says «${want}»`)
    : bad(`οἶνοψ sea count: saved Il ${il}, Od ${od}, all οἴνοπ-: ${allOinop}; page has «${want}»: ${PAGE.includes(want)}`);
}
// the lemma breakdown the banner asserts
(pageEN.includes("oinos") || pageGK.includes("οἶνος")) && pageGK.includes("ὄψ")
  ? ok("banner shows the etymology οἶνος + ὄψ")
  : bad("banner missing the οἶνος + ὄψ etymology");

// ---------- B · English translators (verbatim, colour kept) ----------
console.log("\nB · English quotations that KEEP a sea-colour (verbatim)");
const SRC = {
  butcherlang: normEN(BODY("butcherlang-1879-od.txt")),
  cowper_od:   normEN(BODY("cowper-1791-od.txt")),     // Book I, Od. 1.180-184 only
  cowper_od2:  normEN(BODY("cowper-1791-od-2.txt")),   // Od. 2.260-264, 2.421, 5.132
  chapman:     normEN(BODY("chapman-1615-od.txt")),     // Od. 3.286 and 6.170 only
  chapman_il:  normEN(BODY("chapman-1611-il.txt")),     // Iliads (ed. Hooper), Il. 2.613
  buckley:     normEN(BODY("buckley-1851-il.txt")),
  worsley:     normEN(BODY("worsley-1861-od.txt")),     // Internet Archive OCR, Od. 1.183 (dated note)
};
const KEEP = [
  ["butcherlang", "sailing over the wine-dark sea, unto men of strange speech, even to Temesa", 'Butcher & Lang 1879 "wine-dark sea"'],
  ["cowper_od",   "Athwart the gloomy flood, in quest of brass", 'Cowper 1791 "gloomy flood" (Od. 1.183)'],
  ["cowper_od2",  "the gray Deep", 'Cowper 1791 "gray Deep" (the grey of Od. 2.261)'],
  ["cowper_od2",  "the sable Deep", 'Cowper 1791 "sable Deep" (the misty sea of Od. 2.263; his οἶνοψ at Od. 2.421, 5.132)'],
  ["chapman",     "the wine-hued seas", 'Chapman 1615 "wine-hued seas" (Od. 3.286)'],
  ["chapman",     "the sable seas", 'Chapman 1615 "sable seas" (Od. 6.170: same epithet, opposite colour)'],
  ["chapman_il",  "To pass the gulfy purple sea, that did no sea rites know", 'Chapman c. 1611 Iliads "gulfy purple sea" (Il. 2.613)'],
  ["buckley",     "to pass over the dark sea", 'Buckley 1851 "the dark sea"'],
  ["worsley",     "in sailing o'er the wine-dark sea", 'Worsley 1861 "wine-dark sea" (Od. 1.183, quoted in the dated note)'],
];
for (const [who, q, label] of KEEP) {
  const qn = normEN(q);
  const inSrc  = SRC[who].includes(qn);
  const onPage = pageEN.includes(qn);
  (inSrc && onPage) ? ok(`${label} — in source & on page`)
                    : bad(`${label} — source:${inSrc} page:${onPage}`);
}

// ---------- C · the dropped epithets (verbatim line shown, colour gone) ----------
console.log("\nC · DROPPED epithets (real text, no colour-word)");
const pope_il = normEN(BODY("pope-1715-il.txt"));
const butler_od = normEN(BODY("butler-1900-od.txt"));
const pope_od = normEN(BODY("pope-1725-od.txt"));     // Book I (Fenton), Od. 1.180-184
const DROP = [
  ["Through roaring seas the wondering warriors bear", pope_il, 'Pope 1715: colour → sound ("roaring seas")'],
  ["on a voyage to men of a foreign tongue", butler_od, 'Butler 1900: prose, epithet dissolved'],
  ["I steer my voyage to the Brutian strand", pope_od, 'Pope 1725 (Book I by Fenton): Od. 1.183 as "the Brutian strand", no sea-colour'],
];
for (const [q, src, label] of DROP) {
  const qn = normEN(q);
  const inSrc  = src.includes(qn);
  const onPage = pageEN.includes(qn);
  (inSrc && onPage) ? ok(`${label} — verbatim in source & on page`)
                    : bad(`${label} — source:${inSrc} page:${onPage}`);
}
// page must actually mark these as drops
/dropped/i.test(PAGE) ? ok('page labels the dropped epithets as "dropped"')
                      : bad('page does not mark the drops');

// ---------- D · Gladstone (OCR-normalised) ----------
console.log("\nD · Gladstone 1858 (Internet Archive scan; p. 488 via Gutenberg 53004)");
const dGlad = (s) => normEN(s).toLowerCase();
const glad = dGlad(BODY("gladstone-1858-colour.txt"));
const GLAD = [
  ["now we must at once be struck with the poverty of the list", 'Gladstone "poverty of the list" (block-quote, first half)'],
  ["out of these nine, three at least stand unrepresented", 'Gladstone "three at least stand unrepresented" (block-quote, second half)'],
  ["the organ of colour and its impressions were but partially developed among the greeks of the heroic age", 'Gladstone\'s conclusion on colour (p. 488)'],
];
for (const [q, label] of GLAD) {
  (glad.includes(q) && dGlad(PAGE).includes(q))
    ? ok(`${label}: in excerpt & on page`)
    : bad(`${label}: excerpt:${glad.includes(q)} page:${dGlad(PAGE).includes(q)}`);
}
// "in the bud only" is Gladstone on the picturesque (p. 419), not his verdict on colour
!/in the bud only/i.test(AUTHORED)
  ? ok('page does not give "in the bud only" (the picturesque, p. 419) as the colour verdict')
  : bad('page still quotes "in the bud only" as Gladstone on colour');
// the page must attribute it to the 1858 vol. III
/Studies on Homer/i.test(PAGE) && /1858/.test(PAGE)
  ? ok("page cites Studies on Homer (1858)") : bad("page miscites Gladstone");

// ---------- E · honest-edge disciplines ----------
console.log("\nE · honest-edge disciplines");
const tags = [
  ["names the swatches as readings, not perception data", /readings, not data|not a claim about what|not a reconstruction of ancient/i],
  ["marks reasoning as judgment",                          /class="judge"|judgment</i],
  ["names Berlin & Kay 1969",                              /Berlin\s*&(amp;)?\s*Kay/i],
  ["states the sea is never 'blue'",                       /never[^.]{0,30}blue|never, not once, .?blue/i],
  ["flags that ὄψ's sense is itself debated",              /itself debated|is itself debated/i],
  ["names every translator as public domain",              /public domain/i],
  ["points back to a sibling P6 entry",                    /the-first-word-is-rage|the-way-that-can-be-told/i],
];
for (const [label, re] of tags) {
  re.test(PAGE) ? ok(label) : bad("missing: " + label);
}

// ---------- F · claims corrected 2026-10-11 stay corrected ----------
// Reads AUTHORED (defined at the top): generated blocks and the dated note excluded.
console.log("\nF · corrected claims stay corrected (authored page only)");
const RETIRED = [
  [/\bcoin(s|ed)?\b/i, 'no claim that Butcher & Lang coined "wine-dark sea" (Worsley printed it in 1861)'],
  [/adjacent lines|his <em>wine<\/em> sea/i, 'Cowper\'s "gray Deep" / "sable Deep" not called adjacent, nor the second a wine sea'],
  [/yr:'1877'|\(1870s\)/, "Geiger's colour lecture not dated 1877 or the 1870s (read 24 September 1867)"],
  [/Reithrian port|regretted Sire/, "no line from another passage shown at Od. 1.183 (Pope's Od. 1.315-318, Cowper's Od. 2.263)"],
];
for (const [re, label] of RETIRED) {
  !re.test(AUTHORED) ? ok(label) : bad("reappeared: " + label);
}

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