// verify-immersive.mjs — the check behind the immersive form of
// "A Minor Leonardo, Until It Was Gone" (public/strata/a-minor-leonardo/index.html).
//
// It guarantees three things, so the immersive page cannot drift from the truth:
//
//   1. DATA FIDELITY. The JSON embedded in the page is byte-identical to the
//      committed research artifact coverage.json (which coverage-data.mjs pulls
//      from the Library of Congress; --check also reuses cached years).
//   2. THE SHAPE THE PAGE CLAIMS IS THE SHAPE THE DATA HAS. Every factual claim
//      the page makes ABOUT the chart — "the Venus outranks the Mona Lisa before
//      1911", "the Winged Victory keeps pace in 1905", "the Mona Lisa peaks in the
//      theft window", "its line never starts at the floor" — is recomputed from
//      the data and asserted true. The prose can't say something the numbers deny.
//   3. PROSE FIDELITY. Every verified paragraph of the canonical prose stratum
//      (src/content/strata/a-minor-leonardo.md) appears, word for word, in the
//      immersive page. The immersive form may ADD framing for the instrument, but
//      it may not drop or alter a single sentence of the checked record-correction.
//
// Run:  node research/a-minor-leonardo/verify-immersive.mjs

import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { runInNewContext } from "node:vm";

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, "..", "..");
const HTML = readFileSync(join(ROOT, "public/strata/a-minor-leonardo/index.html"), "utf8");
const MD = readFileSync(join(ROOT, "src/content/strata/a-minor-leonardo.md"), "utf8");
const JSON_ARTIFACT = readFileSync(join(HERE, "coverage.json"), "utf8");

let pass = 0, fail = 0;
function ok(name, cond, detail) {
  cond ? pass++ : fail++;
  console.log(`${cond ? "PASS" : "FAIL"}  ${name}${detail ? "  — " + detail : ""}`);
}

// ── 1. DATA FIDELITY ────────────────────────────────────────────────────────
const blobMatch = HTML.match(/<script id="coverage-data" type="application\/json">\s*([\s\S]*?)\s*<\/script>/);
ok("the page embeds a coverage-data JSON block", !!blobMatch);
const embedded = blobMatch ? blobMatch[1].trim() : "";
const artifact = JSON_ARTIFACT.trim();
ok("embedded JSON is byte-identical to committed coverage.json",
   embedded === artifact,
   embedded === artifact ? "identical" : `embedded ${embedded.length} chars vs artifact ${artifact.length}`);

const data = JSON.parse(artifact);

// Exercise the page's actual hover function in both modes for every saved year.
const showYearSource = HTML.match(/    function showYear\(yr\) \{[\s\S]*?(?=    function move\(ev\))/)?.[0];
const readoutErrors = [];
if (!showYearSource) readoutErrors.push("showYear function missing");
else for (const raw of [false, true]) {
  for (const row of data.series) {
    const readout = {};
    const context = {
      series: data.series, terms: data.terms, raw, readout, year: row.year,
      on: Object.fromEntries(data.terms.map((t) => [t.key, true])),
      COLOR: {}, hline: { setAttribute() {} }, xScale: (year) => year,
    };
    runInNewContext(showYearSource + "\nshowYear(year);", context, { timeout: 1000 });
    const unit = raw ? "matching pages:" : "per million pages:";
    const values = [...readout.innerHTML.matchAll(/<b>([^<]+)<\/b>/g)].map((m) => m[1]);
    const expected = [String(row.year), ...data.terms.map((t) => raw
      ? String(row.counts[t.key])
      : (row.counts[t.key] / row.corpusPages * 1e6).toFixed(1))];
    if (!readout.innerHTML.includes(unit) || JSON.stringify(values) !== JSON.stringify(expected)) {
      readoutErrors.push(`${row.year} ${raw ? "raw" : "normalized"}`);
    }
  }
}
ok("hover values and units agree for every year in raw and normalized modes",
   readoutErrors.length === 0,
   readoutErrors.length ? readoutErrors.join(", ") : `${data.series.length * 2} readouts checked`);

const S = {};
for (const s of data.series) S[s.year] = s;
const ml = (y) => S[y].perMillion.mona_lisa;
const ve = (y) => S[y].perMillion.venus_de_milo;
const wv = (y) => S[y].perMillion.winged_victory;

// ── 2. THE SHAPE THE PAGE CLAIMS ─────────────────────────────────────────────
const preYears = data.series.filter((s) => s.year < 1911).map((s) => s.year);

ok("before 1911, the Venus de Milo outranks the Mona Lisa every measured year (the page's control)",
   preYears.every((y) => ve(y) > ml(y)),
   preYears.map((y) => `${y}:V${ve(y).toFixed(0)}>M${ml(y).toFixed(0)}`).join(" "));

ok("in 1905 the Winged Victory keeps pace with the Mona Lisa (within 2x), as the intro says",
   wv(1905) > 0 && ml(1905) > 0 && Math.max(wv(1905), ml(1905)) / Math.min(wv(1905), ml(1905)) < 2,
   `1905: WV ${wv(1905).toFixed(0)} vs ML ${ml(1905).toFixed(0)} per 10⁶`);

const peak = data.series.reduce((a, b) => (b.perMillion.mona_lisa > a.perMillion.mona_lisa ? b : a));
ok("the Mona Lisa's coverage peaks inside the theft window (1911–1914)",
   peak.year >= 1911 && peak.year <= 1914,
   `peak year ${peak.year} at ${peak.perMillion.mona_lisa.toFixed(0)} per 10⁶`);

const preMax = Math.max(...preYears.map(ml));
ok("the peak is a genuine SPIKE: at least 4x the highest pre-theft year",
   peak.perMillion.mona_lisa >= 4 * preMax,
   `peak ${peak.perMillion.mona_lisa.toFixed(0)} vs pre-1911 max ${preMax.toFixed(0)} (${(peak.perMillion.mona_lisa/preMax).toFixed(1)}x)`);

ok("in the theft years the Mona Lisa clears BOTH rivals (it 'cleared the sky')",
   [1911, 1912, 1913].every((y) => ml(y) > ve(y) && ml(y) > wv(y)),
   [1911, 1912, 1913].map((y) => `${y}:M${ml(y).toFixed(0)}`).join(" "));

ok("the Mona Lisa line never starts at the floor (fame was a shift in degree, not from zero)",
   ml(data.window.from) > 0,
   `${data.window.from}: ${ml(data.window.from).toFixed(1)} per 10⁶ (> 0)`);

// ── 3. PROSE FIDELITY ────────────────────────────────────────────────────────
// Strip HTML to plain text and markdown to plain text, normalize whitespace, then
// assert every verified prose sentence survives verbatim onto the immersive page.
function plain(s) {
  return s
    .replace(/<sup>[\s\S]*?<\/sup>/g, "")     // drop footnote markers
    .replace(/<[^>]+>/g, "")                    // drop tags
    .replace(/\[\^[^\]]+\]/g, "")               // drop md footnote refs
    .replace(/\*\*(.*?)\*\*/g, "$1")            // md bold
    .replace(/\*(.*?)\*/g, "$1")                // md italic
    .replace(/&amp;/g, "&").replace(/&nbsp;/g, " ")
    .replace(/&mdash;/g, "—").replace(/&times;/g, "×")
    .replace(/[""]/g, '"').replace(/['']/g, "'")
    .replace(/\s+/g, " ")
    .trim();
}
const htmlText = plain(HTML).replace(/[""]/g, '"').replace(/['']/g, "'");

// Canonical sentences — the load-bearing prose that MUST survive verbatim.
const CANON = [
  "The thief went for it partly",
  "before 1911 it was one prized Leonardo among the Louvre's many treasures, not the singular icon it has since become",
  "On the morning of Monday, 21 August 1911, the Louvre was closed",
  "He was Vincenzo Peruggia",
  "The absence went unnoticed for about a day",
  "It was a guard who finally raised the alarm on Tuesday, 22 August",
  "decided to steal the Mona Lisa not because it was then the most famous painting, but because it was small",
  "From the theft to the day it hung again in the Louvre",
  "arrested in Florence on 12 December 1913",
  "the theft occurred in 1911, Mona Lisa was recovered in late 1913, and Vincenzo Perugia was on trial in 1914",
  "Crowds filed into the Salon Carré to stare at the empty space and its four lonely pegs",
  "It was an unknown painting until a thief made it famous",
  "is as false as",
  "a shift in degree and reach, not a rise from zero",
  "so pleasing that it seemed more divine than human",
  "she is older than the rocks among which she sits",
  "It was a star in a sky full of stars",
  "The theft did not invent its brightness; it cleared the rest of the sky",
  "the theft was a major, documented catalyst, but",
  "it was not the sole cause",
  "made it the most famous painting on Earth",
];
let missing = [];
for (const c of CANON) {
  const needle = plain(c);
  if (!htmlText.includes(needle)) missing.push(c);
}
ok("every canonical prose sentence survives verbatim onto the immersive page",
   missing.length === 0,
   missing.length ? `MISSING: ${missing.map((m) => JSON.stringify(m.slice(0, 40))).join(", ")}` : `${CANON.length}/${CANON.length} present`);

// The stratum's markdown must now point AT the immersive page.
ok("the markdown stratum declares href to the immersive page",
   /href:\s*["']\/strata\/a-minor-leonardo\/["']/.test(MD));
ok("the markdown stratum keeps the full prose below (verified source of truth)",
   MD.includes("decided to steal the Mona Lisa not because it was then the most famous painting, but because it was small"));

// Every source URL in the prose must also be present on the immersive page.
const urls = [...MD.matchAll(/https?:\/\/[^\s)\]]+/g)].map((m) => m[0].replace(/[.,]$/, ""));
const uniqUrls = [...new Set(urls)];
let urlMissing = uniqUrls.filter((u) => !HTML.includes(u.replace(/^https?:\/\/(www\.)?/, "").split("/")[0]));
ok("every source domain cited in the prose is present on the immersive page",
   urlMissing.length === 0,
   urlMissing.length ? `MISSING domains for: ${urlMissing.join(", ")}` : `${uniqUrls.length} source URLs, all domains present`);

console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
