#!/usr/bin/env node

import fs from "node:fs";
import crypto from "node:crypto";
import path from "node:path";
import process from "node:process";
import zlib from "node:zlib";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, "../..");
const htmlPath = path.join(root, "public/strata/federalist-stylometry/index.html");
const bundledCorpusPath = path.join(here, "pg1404-2009.txt.gz");
const corpusBlobSha = "1b23c1665bbd42c0f7077f4872e3ab81e073d68a";
const html = fs.readFileSync(htmlPath, "utf8");

let checks = 0;
let failures = 0;

function pass(label, detail = "") {
  checks += 1;
  console.log(`PASS ${String(checks).padStart(2, "0")}  ${label}${detail ? `: ${detail}` : ""}`);
}

function fail(label, detail = "") {
  checks += 1;
  failures += 1;
  console.error(`FAIL ${String(checks).padStart(2, "0")}  ${label}${detail ? `: ${detail}` : ""}`);
}

function assert(label, condition, detail = "") {
  if (condition) pass(label, detail);
  else fail(label, detail);
}

function close(a, b, tolerance = 1e-12) {
  return Math.abs(a - b) <= tolerance;
}

function extractJson(name, opener) {
  const start = html.indexOf(`const ${name}=`);
  if (start < 0) throw new Error(`Could not find ${name} in page`);
  const valueStart = html.indexOf(opener, start);
  const end = html.indexOf(";", valueStart);
  if (valueStart < 0 || end < 0) throw new Error(`Could not parse ${name} in page`);
  return JSON.parse(html.slice(valueStart, end));
}

const WORDS = extractJson("WORDS", "[");
const ROWS = extractJson("ROWS", "[");
const FIRST_TOKEN_CORRECTIONS = extractJson("FIRST_TOKEN_CORRECTIONS", "{");
const FUNCTION_WORDS = WORDS.slice(0, 32);
const CONTENT_WORDS = ["war", "executive", "legislature"];
const MARKERS = ["upon", "while", "whilst", "by", "to", "war", "executive", "legislature"];

const MADISON = new Set([10, 14, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48]);
const DISPUTED = new Set([49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 62, 63]);
const JAY = new Set([2, 3, 4, 5, 64]);
const JOINT = new Set([18, 19, 20]);

function authorOf(number) {
  if (MADISON.has(number)) return "M";
  if (DISPUTED.has(number)) return "D";
  if (JAY.has(number)) return "J";
  if (JOINT.has(number)) return "X";
  return "H";
}

function inflate(row) {
  const counts = Object.fromEntries(WORDS.map((word, i) => [word, row[i + 2]]));
  const correction = FIRST_TOKEN_CORRECTIONS[row[0]];
  if (correction) {
    for (const [word, delta] of Object.entries(correction.c)) counts[word] += delta;
  }
  return {
    n: row[0],
    total: row[1] + (correction ? correction.t : 0),
    counts,
    author: authorOf(row[0])
  };
}

const PAPERS = ROWS.map(inflate);
const KNOWN = PAPERS.filter((paper) => paper.author === "H" || paper.author === "M");
const RESERVED = PAPERS.filter((paper) => paper.author === "D");

function aggregatePapers(source, author, excludedNumber = null) {
  const papers = source.filter((paper) => paper.author === author && paper.n !== excludedNumber);
  return {
    papers: papers.length,
    total: papers.reduce((sum, paper) => sum + paper.total, 0),
    counts: Object.fromEntries(
      WORDS.map((word) => [word, papers.reduce((sum, paper) => sum + paper.counts[word], 0)])
    )
  };
}

function aggregate(author, excludedNumber = null) {
  return aggregatePapers(PAPERS, author, excludedNumber);
}

function rate(group, word) {
  return group.counts[word] * 1000 / group.total;
}

function parseGutenberg(raw) {
  const text = raw.replace(/\r/g, "");
  const starts = [];
  const heading = /\nFEDERALIST No\. (\d+)\n/g;
  let match;
  while ((match = heading.exec(text))) starts.push({ n:Number(match[1]), index:match.index });
  if (starts.length !== 85) throw new Error(`Expected 85 headings in corpus, found ${starts.length}`);
  return starts.map((start, i) => {
    const terminal = text.indexOf("End of the Project Gutenberg", start.index);
    const end = i + 1 < starts.length
      ? starts[i + 1].index
      : terminal >= 0 ? terminal : text.length;
    const section = text.slice(start.index, end);
    const salutation = /To the People of the State of New York[.:]/.exec(section);
    let bodyEnd = section.lastIndexOf("\nPUBLIUS");
    if (bodyEnd < 0) bodyEnd = section.length;
    if (!salutation) throw new Error(`Could not isolate body of No. ${start.n}`);
    const tokens = section
      .slice(salutation.index + salutation[0].length, bodyEnd)
      .toLowerCase()
      .match(/[a-z]+(?:'[a-z]+)?/g) ?? [];
    const counts = Object.fromEntries(WORDS.map((word) => [word, 0]));
    for (const token of tokens) if (token in counts) counts[token] += 1;
    return { n:start.n, total:tokens.length, counts, author:authorOf(start.n) };
  });
}

function gitBlobSha(bytes) {
  return crypto.createHash("sha1")
    .update(`blob ${bytes.length}\0`)
    .update(bytes)
    .digest("hex");
}

const corpusArg = process.argv.indexOf("--corpus");
const supplied = corpusArg >= 0 ? process.argv[corpusArg + 1] : null;
if (corpusArg >= 0 && !supplied) {
  throw new Error("--corpus requires a path to Project Gutenberg #1404 plain text");
}
const corpusBytes = supplied
  ? fs.readFileSync(path.resolve(supplied))
  : zlib.gunzipSync(fs.readFileSync(bundledCorpusPath));
const sourcePapers = parseGutenberg(corpusBytes.toString("utf8"));

function classify(paper, features, exclude) {
  const scores = {};
  for (const author of ["H", "M"]) {
    const group = aggregate(author, exclude ? paper.n : null);
    let score = 0;
    for (const word of features) {
      const lambda = (group.counts[word] + 0.5) / group.total;
      score += paper.counts[word] * Math.log(lambda) - paper.total * lambda;
    }
    scores[author] = score;
  }
  return { prediction: scores.M > scores.H ? "M" : "H", margin: scores.M - scores.H };
}

function validate(features) {
  const results = KNOWN.map((paper) => {
    const result = classify(paper, features, true);
    return { paper, ...result, correct: result.prediction === paper.author };
  });
  const h = results.filter((result) => result.paper.author === "H");
  const m = results.filter((result) => result.paper.author === "M");
  const hCorrect = h.filter((result) => result.correct).length;
  const mCorrect = m.filter((result) => result.correct).length;
  return {
    results,
    correct: hCorrect + mCorrect,
    hCorrect,
    mCorrect,
    balanced: 0.5 * (hCorrect / h.length + mCorrect / m.length)
  };
}

const groupH = aggregate("H");
const groupM = aggregate("M");
const groupD = aggregate("D");
const sourceH = aggregatePapers(sourcePapers, "H");
const sourceM = aggregatePapers(sourcePapers, "M");
const sourceD = aggregatePapers(sourcePapers, "D");

assert("pinned Gutenberg blob",
  gitBlobSha(corpusBytes) === corpusBlobSha,
  `${supplied ? "supplied" : "bundled"} source ${gitBlobSha(corpusBytes)}`);
assert("embedded corpus shape", WORDS.length === 35 && ROWS.length === 85,
  `${ROWS.length} papers x ${WORDS.length} measured words`);
assert("paper numbering", PAPERS.every((paper, i) => paper.n === i + 1), "1 through 85");
assert("authorship partitions",
  groupH.papers === 51 && groupM.papers === 14 && groupD.papers === 12 &&
  JAY.size === 5 && JOINT.size === 3,
  `Hamilton 51, Madison 14, disputed 12, Jay 5, joint 3`);
assert("token totals",
  groupH.total === sourceH.total && groupM.total === sourceM.total && groupD.total === sourceD.total,
  `Hamilton ${groupH.total}, Madison ${groupM.total}, disputed ${groupD.total}`);

for (const [author, group, sourceGroup] of [
  ["H", groupH, sourceH],
  ["M", groupM, sourceM],
  ["D", groupD, sourceD]
]) {
  for (const word of MARKERS) {
    const actualRate = rate(group, word);
    const sourceRate = rate(sourceGroup, word);
    assert(`${author} ${word}`,
      group.counts[word] === sourceGroup.counts[word] && close(actualRate, sourceRate),
      `${sourceGroup.counts[word]} occurrences, ${actualRate.toFixed(6)} per 1,000`);
  }
}

const uponRatio = rate(groupH, "upon") / rate(groupM, "upon");
const sourceUponRatio = rate(sourceH, "upon") / rate(sourceM, "upon");
assert("source-derived upon rates and ratio",
  close(rate(groupH, "upon"), rate(sourceH, "upon")) &&
  close(rate(groupM, "upon"), rate(sourceM, "upon")) &&
  close(uponRatio, sourceUponRatio),
  `${uponRatio.toFixed(6)} x Hamilton/Madison`);

for (const paper of RESERVED) {
  const sourcePaper = sourcePapers.find((candidate) => candidate.n === paper.n);
  const actualRate = paper.counts.upon * 1000 / paper.total;
  const sourceRate = sourcePaper.counts.upon * 1000 / sourcePaper.total;
  assert(`No. ${paper.n} upon`,
    paper.total === sourcePaper.total &&
    paper.counts.upon === sourcePaper.counts.upon &&
    close(actualRate, sourceRate),
    `${sourcePaper.counts.upon}/${sourcePaper.total}, ${actualRate.toFixed(6)} per 1,000`);
}

const functionValidation = validate(FUNCTION_WORDS);
assert("function-word held-out total",
  functionValidation.correct === 65,
  `${functionValidation.correct}/65`);
assert("function-word author split",
  functionValidation.hCorrect === 51 && functionValidation.mCorrect === 14,
  `Hamilton ${functionValidation.hCorrect}/51, Madison ${functionValidation.mCorrect}/14`);
assert("function-word balanced accuracy",
  close(functionValidation.balanced, 1),
  `${(functionValidation.balanced * 100).toFixed(1)}%`);

const contentValidation = validate(CONTENT_WORDS);
assert("content-word held-out total",
  contentValidation.correct === 43,
  `${contentValidation.correct}/65`);
assert("content-word author split",
  contentValidation.hCorrect === 41 && contentValidation.mCorrect === 2,
  `Hamilton ${contentValidation.hCorrect}/51, Madison ${contentValidation.mCorrect}/14`);
assert("content-word balanced accuracy",
  close(contentValidation.balanced, 0.4733893557422969),
  `${(contentValidation.balanced * 100).toFixed(6)}%`);

const disputedPredictions = RESERVED.map((paper) => ({
  n: paper.n,
  ...classify(paper, FUNCTION_WORDS, false)
}));
const towardMadison = disputedPredictions.filter((result) => result.prediction === "M").length;
const towardHamilton = disputedPredictions.filter((result) => result.prediction === "H").map((result) => result.n);
assert("reserved-set diagnostic",
  towardMadison === 11 && towardHamilton.length === 1 && towardHamilton[0] === 55,
  `${towardMadison}/12 toward Madison; No. ${towardHamilton.join(",")} toward Hamilton`);

assert("visible headline totals",
  html.includes(`${sourceH.total.toLocaleString("en-US")} tokens`) &&
  html.includes(`${sourceM.total.toLocaleString("en-US")} tokens`) &&
  html.includes('id="card-disputed"') && html.includes('id="card-content"') &&
  html.includes('dMadison + " / " + RESERVED.length') &&
  html.includes('(cv.balanced * 100).toFixed(1) + "%"'),
  `${sourceH.total.toLocaleString("en-US")}; ${sourceM.total.toLocaleString("en-US")}; dynamic reserved and control results`);

const exact = sourcePapers.every((paper, i) => {
    const stored = PAPERS[i];
    return paper.n === stored.n && paper.total === stored.total &&
      WORDS.every((word) => paper.counts[word] === stored.counts[word]);
});
assert("raw Gutenberg reparse", exact,
  `85 token totals and ${85 * WORDS.length} word counts match the embedded observations`);

if (failures > 0) {
  console.error(`\n${failures} of ${checks} checks failed.`);
  process.exit(1);
}

console.log(`\nAll ${checks} checks passed.`);
process.exit(0);
