#!/usr/bin/env node
// Offline verifier — "How Many Words Did Shakespeare Know?" (Verification Venue).
//
// WHAT THIS CHECKS
//
//  (A) OUR OWN frequency spectrum, recomputed from a freely-downloadable canon
//      (Project Gutenberg #100, committed under ./data/pg100.txt) with a simple,
//      stated tokenizer. The reader can reproduce every number here from that file.
//
//  (B) The Efron-Thisted UNSEEN-SPECIES estimator (Biometrika 1976), run live:
//        Delta_hat(t) = n_1 t - n_2 t^2 + n_3 t^3 - ...   (Good & Toulmin 1956)
//      the expected number of NEW word-types in a fresh corpus of relative size t.
//      - our doubling estimate varies little over the tested cutoffs K=20..50;
//      - our 30-term sum grows sharply at t=2. This finite calculation does not
//        establish an extrapolation limit for all accelerated estimators. E&T
//        estimate beyond a doubling with growing uncertainty and use linear
//        programming for a nonparametric lower bound on unused vocabulary,
//        conditional on sampling assumptions and an uncertainty tolerance.
//
//  (C) REPRODUCTION of the historical headline on E&T's OWN published spectrum
//      (Spevack's concordance: N=884,647 tokens, V=31,534 types, n_1=14,376).
//      Running the same estimator on their published n_x recovers their
//      famous ~11,430 "new words if the canon were doubled."
//
//  (D) Sanity self-tests of the estimator (Euler sum of (-1)^k/(k+1) = ln 2).
//
// Sources (full citations on the page): Efron & Thisted (1976) Biometrika
// 63(3):435-447; Thisted & Efron (1987) Biometrika 74(3):445-455; Good & Toulmin
// (1956) Biometrika 43:45; Fisher, Corbet & Williams (1943) J. Anim. Ecol. 12:42;
// Spevack (1968-80) A Complete and Systematic Concordance to the Works of Shakespeare.
//
// Run:   node research/shakespeare-vocabulary/verify.mjs
// Emits: ./data.json  (embedded by the page)

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { eulerAlternatingSum, deltaHat, partialSums } from './estimator.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
let PASS = 0, FAIL = 0;
const checks = [];
function ok(name, cond, detail = '') {
  (cond ? PASS++ : FAIL++);
  checks.push({ name, pass: !!cond, detail });
  console.log(`${cond ? 'ok  ' : 'FAIL'}  ${name}${detail ? '  — ' + detail : ''}`);
}

// ---------- (A) our own spectrum, from the committed corpus ----------
const raw = fs.readFileSync(path.join(HERE, 'data', 'pg100.txt'), 'utf8');
const A = raw.indexOf('*** START OF THE PROJECT GUTENBERG');
const B = raw.indexOf('*** END OF THE PROJECT GUTENBERG');
ok('corpus boundaries found', A >= 0 && B > A);
let body = raw.slice(raw.indexOf('\n', A) + 1, B)
  .replace(/[‘’ʼ]/g, "'").replace(/[“”]/g, '"').replace(/[–—]/g, ' ').toLowerCase();
const TOKENIZER = "lowercased; maximal [a-z]+ runs with internal apostrophes (don't, o'er); curly punct normalised; Gutenberg apparatus/speech-prefixes NOT stripped";
const tokens = body.match(/[a-z]+(?:'[a-z]+)*/g) || [];
const counts = new Map();
for (const t of tokens) counts.set(t, (counts.get(t) || 0) + 1);
const spec = new Map();
for (const v of counts.values()) spec.set(v, (spec.get(v) || 0) + 1);
const maxc = Math.max(...counts.values());
const SPEC = [];
for (let x = 1; x <= maxc; x++) SPEC.push(spec.get(x) || 0);

const N = tokens.length, V = counts.size, n1 = SPEC[0];
ok('token count plausible (0.9-1.0M)', N > 900000 && N < 1000000, `N=${N}`);
ok('distinct types plausible', V > 24000 && V < 30000, `V=${V}`);
ok('spectrum sums to V', SPEC.reduce((a, b) => a + b, 0) === V);
ok('weighted spectrum sums to N', SPEC.reduce((a, nx, i) => a + nx * (i + 1), 0) === N);
ok('hapax are a large minority (~38%)', n1 / V > 0.35 && n1 / V < 0.40, `${(100 * n1 / V).toFixed(1)}%`);

// ---------- (B) the estimator on our spectrum ----------
const d1_ours = deltaHat(SPEC, 1, 30);
ok('Delta_hat(1) on our corpus ~7600', d1_ours > 7400 && d1_ours < 7900, `Delta_hat(1)=${d1_ours.toFixed(0)}`);
// stability in K: a true plateau, not a tuned cutoff
const kvals = [20, 25, 30, 35, 40, 50].map(K => deltaHat(SPEC, 1, K));
const spread = Math.max(...kvals) - Math.min(...kvals);
ok('Delta_hat(1) flat across cutoff K (spread<30)', spread < 30, `spread=${spread.toFixed(1)} over K∈[20,50]`);
// monotone increasing & convex-ish up to t=1
const curve = [0.25, 0.5, 0.75, 1].map(t => deltaHat(SPEC, t, 30));
ok('Delta_hat(t) increasing on (0,1]', curve.every((v, i) => i === 0 || v > curve[i - 1]));
// A finite 30-term calculation at t=2; this is not a general divergence test.
const d2 = deltaHat(SPEC, 2, 30);
ok('our 30-term sum at t=2 exceeds 10x its t=1 value', d2 > 10 * d1_ours, `Delta_hat(2)=${d2.toFixed(0)} at K=30`);

// ---------- (C) reproduce E&T's published headline ----------
// Efron & Thisted (1976), Table 1: the published frequency spectrum n_x of the
// Shakespeare canon per Spevack's concordance, x = 1..100. (Filled from the
// research pass; see ./data/efron-thisted-spectrum.json for provenance.)
const etPath = path.join(HERE, 'data', 'efron-thisted-spectrum.json');
let ET = null;
if (fs.existsSync(etPath)) {
  ET = JSON.parse(fs.readFileSync(etPath, 'utf8'));
  const etSpec = ET.spectrum; // verified n_1..n_12 (Efron 2021 Table 3)
  ok('E&T n_1=14376 (hapax), n_2=4343 (per OUP abstract)', etSpec[0] === 14376 && etSpec[1] === 4343);
  const etD1 = deltaHat(etSpec, 1, etSpec.length);
  ok('E&T headline reproduced: Delta_hat(1) ~ 11,430', etD1 > 11300 && etD1 < 11550, `Delta_hat(1)=${etD1.toFixed(1)} vs published 11,430`);
  // Published terms beyond the page's 12-term input change the estimate.
  const etExtended = etSpec.concat(ET.spectrum_13_to_20);
  const etD20 = deltaHat(etExtended, 1, 20);
  ok('E&T published terms 13..20 change the 12-term estimate',
    etExtended.length === 20 && Math.abs(etD20 - 11421.282053) < 1e-6 && Math.abs(etD20 - etD1) > 10,
    `K12=${etD1.toFixed(4)}, K20=${etD20.toFixed(4)}; no convergence guarantee`);
  ET._reproduced = { delta1: etD1 };
} else {
  console.log('note: ./data/efron-thisted-spectrum.json absent — (C) skipped until research provenance lands');
}

// ---------- (D) estimator self-tests ----------
const ln2 = eulerAlternatingSum(Array.from({ length: 60 }, (_, k) => 1 / (k + 1)));
ok('Euler sum of (-1)^k/(k+1) = ln 2 (1e-12)', Math.abs(ln2 - Math.LN2) < 1e-12, `err=${Math.abs(ln2 - Math.LN2).toExponential(1)}`);

// ---------- emit data.json for the page ----------
const top = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 15);
const data = {
  generated: 'run node research/shakespeare-vocabulary/verify.mjs to regenerate',
  ours: {
    source: 'Project Gutenberg eBook #100 (Complete Works of William Shakespeare)',
    tokenizer: TOKENIZER,
    N, V, n1,
    hapax_fraction: n1 / V,
    spectrum: SPEC.slice(0, 100),         // n_1..n_100 for the bar chart
    spectrum_full_len: SPEC.length,
    top15: top,
    delta1: d1_ours,
    delta_curve: Array.from({ length: 53 }, (_, i) => {
      const t = i * 0.025; // 0 .. 1.3
      return { t: +t.toFixed(3), d: deltaHat(SPEC, t, 30) };
    }),
  },
  efronThisted: ET ? {
    N: 884647, V: 31534, n1: 14376,
    published_delta1: 11430,
    reproduced_delta1: ET._reproduced.delta1,
    spectrum: ET.spectrum.slice(0, 100),
    source: ET.source,
  } : null,
  checks: { pass: PASS, fail: FAIL, list: checks },
};
fs.writeFileSync(path.join(HERE, 'data.json'), JSON.stringify(data, null, 2));

console.log(`\n${PASS}/${PASS + FAIL} checks passed.`);
if (FAIL) process.exit(1);
