#!/usr/bin/env node
/**
 * verify-the-copyright-nobody-renewed.mjs
 *
 * Independent offline check of public/strata/the-copyright-nobody-renewed/index.html.
 * No dependencies beyond Node 22 built-ins. Exits 0 on success, 1 on any failure.
 *
 *   node research/the-copyright-nobody-renewed/verify-the-copyright-nobody-renewed.mjs
 *   node research/the-copyright-nobody-renewed/verify-the-copyright-nobody-renewed.mjs --tsv /path/to/cce-renewals/data
 *
 * The optional --tsv flag points at a local clone of https://github.com/NYPL/cce-renewals
 * (the `data` directory, 47 .tsv files, about 107 MB). With it, the bundled register index
 * is rebuilt from the raw transcription and asserted byte-identical to the block shipped in
 * the page. Without it, the bundled block is still decoded, hashed and audited row by row.
 */

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

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata', 'the-copyright-nobody-renewed', 'index.html');

let failures = 0;
let checks = 0;

function ok(label, value) {
  checks++;
  console.log('  ok   ' + label + (value === undefined ? '' : '  ->  ' + value));
}
function fail(label, detail) {
  checks++; failures++;
  console.error('  FAIL ' + label + '\n       ' + detail);
}
function assertEq(label, got, want) {
  if (got === want) ok(label, String(got));
  else fail(label, 'got ' + JSON.stringify(got) + ', want ' + JSON.stringify(want));
}
function assertClose(label, got, want, tol) {
  if (Math.abs(got - want) <= tol) ok(label, got.toFixed(6));
  else fail(label, 'got ' + got + ', want ' + want + ' +/- ' + tol);
}
function assertTrue(label, cond, detail) {
  if (cond) ok(label);
  else fail(label, detail || 'condition false');
}
function section(name) { console.log('\n== ' + name + ' =='); }

/* ------------------------------------------------------------------ */
/* 0. the page                                                         */
/* ------------------------------------------------------------------ */

section('page file');
if (!fs.existsSync(PAGE)) {
  console.error('  FAIL page missing at ' + PAGE);
  process.exit(1);
}
const html = fs.readFileSync(PAGE, 'utf8');
assertTrue('page ends with the load-bearing closing tags',
  /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html),
  'tail is: ' + JSON.stringify(html.slice(-80)));
assertTrue('canonical link present',
  html.includes('<link rel="canonical" href="https://artwaste.land/strata/the-copyright-nobody-renewed/" />'));
assertTrue('JSON-LD dates are the landing date',
  html.includes('"datePublished":"2026-07-24"') && html.includes('"dateModified":"2026-07-24"'));
assertTrue('no external script or style host is referenced',
  !/(src|href)="https?:\/\/(?!artwaste\.land)/.test(
    html.replace(/<a\b[^>]*>/g, '').replace(/"(?:og|twitter):[^"]*"/g, '')
      .replace(/<meta[^>]*>/g, '').replace(/<script type="application\/ld\+json">[\s\S]*?<\/script>/, '')),
  'a stylesheet or script points off-site');

/* absence-claim discipline */
assertTrue('page uses the hedged absence wording', html.includes('No renewal located'));
assertTrue('page never asserts "was never renewed"', !/was never renewed/i.test(html));
assertTrue('page names the build date on the absence claim', html.includes('as of 2026-07-24'));

/* ------------------------------------------------------------------ */
/* 1. the bundled register index                                       */
/* ------------------------------------------------------------------ */

section('bundled register index');
const blobMatch = /<script type="text\/plain" id="reg-blob">([A-Za-z0-9+/=\s]*)<\/script>/.exec(html);
if (!blobMatch) { fail('register blob found in page', 'no <script id="reg-blob"> block'); }
const b64 = blobMatch ? blobMatch[1].replace(/\s+/g, '') : '';
const gz = Buffer.from(b64, 'base64');
const raw = zlib.gunzipSync(gz);
const rawText = raw.toString('utf8');
const sha = crypto.createHash('sha256').update(raw).digest('hex');

const RS = '\u001e';
const parts = rawText.split(RS);
assertEq('index block has four sections', parts.length, 4);
const N = parseInt(parts[0], 10);
const titles = parts[1].split('\n');
const authors = parts[2].split('\n');
const metas = parts[3].split('\n');
assertEq('declared row count', N, 73705);
assertEq('title rows', titles.length, N);
assertEq('author rows', authors.length, N);
assertEq('meta rows', metas.length, N);
assertEq('sha256 of the decompressed index', sha,
  'f4f191716713b6ad56b51dcdb2ddec1777746c26dad234201f913fbf2a78ce11');
assertEq('page states the same row count in prose', /73,705 real renewal records/.test(html), true);

const EPOCH = Date.UTC(1920, 0, 1);
const BOOK = new Set(['A', 'AA', 'AF', 'AI', 'AFO', 'AIO', 'AO']);
function dayToISO(d) { return new Date(EPOCH + d * 86400000).toISOString().slice(0, 10); }

let badClass = 0, badYear = 0, badLag = 0, minY = 9999, maxY = 0, longTitle = 0, longAuthor = 0;
const lagHist = {};
for (let i = 0; i < N; i++) {
  const f = metas[i].split(',');
  const cls = f[0].replace(/[0-9].*$/, '').replace(/-+$/, '');
  if (!BOOK.has(cls)) badClass++;
  const odat = dayToISO(parseInt(f[1], 36));
  const rdat = dayToISO(parseInt(f[3], 36));
  const oy = +odat.slice(0, 4), ry = +rdat.slice(0, 4);
  if (oy < 1923 || oy > 1940) badYear++;
  if (oy < minY) minY = oy;
  if (oy > maxY) maxY = oy;
  const lag = ry - oy;
  lagHist[lag] = (lagHist[lag] || 0) + 1;
  if (lag < -20 || lag > 70) badLag++;
  if (titles[i].length > 72) longTitle++;
  if (authors[i].length > 40) longAuthor++;
}
assertEq('every bundled row is in a book class', badClass, 0);
assertEq('every bundled row registers in 1923-1940', badYear, 0);
assertEq('registration-year span of the bundled slice', minY + '-' + maxY, '1923-1940');
assertEq('no implausible renewal lag', badLag, 0);
assertEq('titles respect the stated 72-character truncation', longTitle, 0);
assertEq('authors respect the stated 40-character truncation', longAuthor, 0);
const peakShare = ((lagHist[27] || 0) + (lagHist[28] || 0)) / N;
assertTrue('the bundled slice also peaks in the 28th-year window', peakShare > 0.98,
  'share at lag 27 or 28 is ' + peakShare.toFixed(4));

/* the six dossier records and two absences the page leans on */
const DOSSIER_EXPECT = [
  ['A855444', 'R109367', '1953-03-23'],
  ['A62883', 'R262091', '1960-08-26'],
  ['B528177', 'R475565', '1969-12-29'],
  ['AA446178', 'R505822', '1971-05-10'],
  ['AI4273', 'RE121069', '1982-01-05'],
  ['A632934', 'RE509516', '1990-10-01']
];
DOSSIER_EXPECT.forEach(function (d) {
  assertTrue('dossier record ' + d[0] + '/' + d[1] + ' is printed in the page',
    html.includes(d[0]) && html.includes(d[1]) && html.includes(d[2]));
});
const insideSlice = { A855444: false, A62883: false };
for (let i = 0; i < N; i++) {
  const reg = metas[i].split(',')[0];
  if (reg in insideSlice) insideSlice[reg] = true;
}
assertTrue('Gatsby 1925 (A855444) really is inside the bundled slice', insideSlice.A855444);
const abendGap = (Date.UTC(1970, 0, 2) - Date.UTC(1969, 11, 29)) / 86400000;
assertEq('the Abend renewal was filed four days before 28 years from its registration', abendGap, 4);
assertTrue('the page says four days, not two', html.includes('four days before') && !html.includes('two days before'));
assertTrue('Miss Lonelyhearts 1933 (A62883) really is inside the bundled slice', insideSlice.A62883);

const lowerAll = (titles.join('\n') + '\n' + authors.join('\n')).toLowerCase();
assertTrue('no "hobbit" anywhere in the bundled slice', lowerAll.indexOf('hobbit') === -1);

/* The Day of the Locust: the record IS there, and the naive query still misses it.
   This is the page's own worked example of match failure, so both halves are asserted. */
const hay = [];
for (let i = 0; i < N; i++) hay.push((titles[i] + ' \u00b7 ' + authors[i]).toLowerCase());
const naive = hay.filter((s2) => s2.indexOf('the day of the locust') >= 0).length;
const correct = [];
for (let i = 0; i < N; i++) if (hay[i].indexOf('day of the locust') >= 0) correct.push(i);
assertEq('the naive query "the day of the locust" still finds nothing', naive, 0);
assertEq('the query without the article finds exactly one record', correct.length, 1);
const lm = metas[correct[0]].split(',');
assertEq('that record is the 1939 registration', lm[0], 'A128467');
assertEq('its renewal id', lm[2], 'R391548');
assertEq('its registration date', dayToISO(parseInt(lm[1], 36)), '1939-05-16');
assertEq('its renewal date', dayToISO(parseInt(lm[3], 36)), '1966-07-29');
assertEq('its claimant code', lm[4], 'NK');
assertEq('the title is indexed without the article', titles[correct[0]], 'Day of the locust.');
assertTrue('the page prints the record it initially got wrong',
  html.includes('A128467') && html.includes('R391548') && html.includes('Laura Perelman'));

/* ------------------------------------------------------------------ */
/* 2. the sparse (year, class, lag) table                              */
/* ------------------------------------------------------------------ */

section('renewal-filing histogram');
const histMatch = /<script type="application\/json" id="hist-data">([\s\S]*?)<\/script>/.exec(html);
const HIST = JSON.parse(histMatch[1]);
assertEq('histogram group count', HIST.length, 1382);
let histTotal = 0, y1963 = 0, y1964 = 0, bookTotal = 0, bookPeak = 0, book1964plus = 0;
for (const [y, cls, lag, n] of HIST) {
  histTotal += n;
  if (y === 1963) y1963 += n;
  if (y === 1964) y1964 += n;
  if (BOOK.has(cls)) {
    bookTotal += n;
    if (lag === 27 || lag === 28) bookPeak += n;
    if (y >= 1964) book1964plus += n;
  }
}
assertEq('every usable row of the 445,386-row dataset is represented', histTotal, 443646);
assertEq('all-class filings for 1963 registrations', y1963, 23454);
assertEq('all-class filings for 1964 registrations', y1964, 15);
assertTrue('the 1964 wall is at least three orders of magnitude', y1963 / y1964 > 1000,
  'ratio is ' + (y1963 / y1964).toFixed(1));
assertEq('book-class rows in the histogram', bookTotal, 245579);
assertClose('book-class share filed at lag 27 or 28', bookPeak / bookTotal, 0.99444, 0.0001);
assertEq('book-class filings for 1964 and later registrations', book1964plus, 119);

/* ------------------------------------------------------------------ */
/* 3. published tables, re-summed and re-divided                       */
/* ------------------------------------------------------------------ */

section('NYPL registration table');
const nyplMatch = /var NYPL = \[([\s\S]*?)\];/.exec(html);
const NYPL = JSON.parse('[' + nyplMatch[1].replace(/\s+/g, '') + ']');
assertEq('table has 41 years', NYPL.length, 41);
assertEq('first year', NYPL[0][0], 1923);
assertEq('last year', NYPL[40][0], 1963);
let nR = 0, nT = 0, mR = 0, mT = 0, eR = 0, eT = 0;
for (const [y, r, t] of NYPL) {
  nR += r; nT += t;
  if (y < 1953) { mR += r; mT += t; } else { eR += r; eT += t; }
}
assertEq('renewals sum to the published total', nR, 162416);
assertEq('registrations sum to the published total', nT, 642206);
assertClose('headline renewal rate', nR / nT, 0.252903, 0.000001);
assertClose('counted years 1923-1952 only', mR / mT, 0.239736, 0.000001);
assertClose('estimated years 1953-1963 are pinned at 27.00%', eR / eT, 0.270001, 0.000005);
assertTrue('the page prints the headline as 25.29%', html.includes('25.29%'));

section('Ringer and the re-analysis');
const RINGER = { renewals: 3942, classA: 57065, books: 13460, pamphlets: 26995, periodical: 10489 };
const CARL = { impR: 2489, impT: 9004, r32: 3533, t32: 13460, r33: 3612, t33: 10820 };
for (const [k, v] of Object.entries(RINGER)) {
  assertTrue('page carries Ringer figure ' + k + ' = ' + v.toLocaleString('en-US'),
    html.includes(String(v)));
}
assertClose('Ringer, all Class A, FY1932', RINGER.renewals / RINGER.classA, 0.069079, 0.000001);
assertEq('Ringer rate rounds to the figure the page prints', (100 * RINGER.renewals / RINGER.classA).toFixed(2) + '%', '6.91%');
const remainder = RINGER.classA - RINGER.books - RINGER.pamphlets - RINGER.periodical;
assertEq('unattributed remainder in the published breakdown', remainder, 6121);
assertClose('important books 1932', CARL.impR / CARL.impT, 0.276433, 0.000001);
assertClose('books proper FY1932', CARL.r32 / CARL.t32, 0.262481, 0.000001);
assertClose('books proper FY1933', CARL.r33 / CARL.t33, 0.333826, 0.000001);
assertTrue('books-proper rates bracket the 26-33% range published',
  CARL.r32 / CARL.t32 >= 0.26 && CARL.r33 / CARL.t33 <= 0.34);
assertClose('Ringer numerator over the books-proper denominator (the upper bound the page shows)',
  RINGER.renewals / RINGER.books, 0.292868, 0.000001);

section('blinded re-derivation figures carried on the page');
const BL = { entryRenewed: 154618, entryTotal: 747750, numberRenewed: 165840, numberTotal: 861364,
  volumeRenewed: 167759, volumeTotal: 892294, orphanKeys: 24176, totalKeys: 190016 };
for (const [k, v] of Object.entries(BL)) {
  assertTrue('page carries re-derived figure ' + k + ' = ' + v, html.includes(String(v)));
}
assertClose('counted class A 1923-63, entry level', BL.entryRenewed / BL.entryTotal, 0.206778, 0.000002);
assertClose('counted class A 1923-63, registration-number level', BL.numberRenewed / BL.numberTotal, 0.192532, 0.000002);
assertClose('counted, every class in the Books volumes 1923-63', BL.volumeRenewed / BL.volumeTotal, 0.188009, 0.000002);
assertClose('orphan renewal-key share', BL.orphanKeys / BL.totalKeys, 0.127231, 0.000002);
assertEq('the page prints that share as 12.72 per cent', html.includes('12.72'), true);
assertTrue('the counted rates sit below the NYPL headline, as the re-derivation reports',
  BL.entryRenewed / BL.entryTotal < nR / nT && BL.numberRenewed / BL.numberTotal < nR / nT);
assertTrue('the page attributes those rows rather than claiming them',
  html.includes('cited, not verified by us') && html.includes('BLIND-REDERIVATION.md'));

section('the NYPL estimate, taken apart');
const row53 = NYPL.find((r) => r[0] === 1953);
assertClose('1953 total divided by renewed is the 3.7 multiplier', row53[2] / row53[1], 3.70368, 0.00001);
assertClose('1953 non-renewed divided by renewed is 2.70, not 3.7', (row53[2] - row53[1]) / row53[1], 2.70368, 0.00001);
assertTrue('every estimated year uses the same multiplier',
  NYPL.filter((r) => r[0] >= 1953).every((r) => Math.abs(r[2] / r[1] - row53[2] / row53[1]) < 0.001));
assertTrue('no counted year happens to use it',
  NYPL.filter((r) => r[0] < 1953).every((r) => Math.abs(r[2] / r[1] - 3.70368) > 0.001));
assertClose('highest over lowest rate on the denominator panel',
  (CARL.r33 / CARL.t33) / (RINGER.renewals / RINGER.classA), 4.8325, 0.001);

/* ------------------------------------------------------------------ */
/* 4. the term rules, implemented a second time FROM THE SOURCES       */
/* ------------------------------------------------------------------ */

/**
 * This block is deliberately NOT a transcription of the page's `usTerm`. It is written from
 * the statute and the circulars, in a different shape (attach -> first term -> extension ->
 * restoration, rather than the page's branch cascade), and it returns the DAY as well as the
 * year, because the three branches do not share one:
 *
 *   'jan1'  a term that 17 U.S.C. 305 carried to a 31 December; free the next 1 January
 *   'anniv' a first term that ran out on the anniversary of the date copyright was secured
 *   'pub'   no federal copyright ever attached; free from the day of publication
 *
 * Authorities, each read in full for this build:
 *   17 U.S.C. 302(a),(c)  life + 70; 120 years from creation for anonymous / for-hire work
 *   17 U.S.C. 304(a)(1)(A) "Any copyright, in the first term of which is subsisting on
 *                          January 1, 1978, shall endure for 28 years from the date it was
 *                          originally secured."
 *   17 U.S.C. 304(a),(b)  renewal term 47 years (1976 Act), then 67 (1998 Act): 95 in total
 *   17 U.S.C. 305         "All terms of copyright provided by sections 302 through 304 run
 *                          to the end of the calendar year in which they would otherwise
 *                          expire."  Enacted with the 1976 Act, effective 1 January 1978.
 *   17 U.S.C. 104A(a)(1)(B) a restored copyright subsists "for the remainder of the term of
 *                          copyright that the work would have otherwise been granted in the
 *                          United States if the work never entered the public domain in the
 *                          United States"
 *   17 U.S.C. 104A(h)(6)(B),(C),(D)  restored-work definition: not PD at home by expiry; in
 *                          the US PD for a formality failure; not published in the US within
 *                          30 days of first publication abroad
 *   Circular 15A          "if renewal registration for these works was not made within the
 *                          statutory time limits, a copyright originally secured between 1950
 *                          and 1963 expired on December 31 of its 28th year"; and the closing
 *                          note that under the 1909 Act "terms of copyright and renewal filing
 *                          periods corresponded with dates of publication or registration, not
 *                          calendar years"
 *   Circular 38B          "Generally, the U.S. copyright term for works published before
 *                          January 1, 1978, lasts for 95 years from the year of first
 *                          publication"; worked example, French story of 1935, expires
 *                          31 December 2030
 *   Circular 6A           1964-1977 works "enjoy a copyright term of ninety-five years"
 */

section('term rules re-derived from the statute and the circulars');

const PD = (pd, when) => ({ pd, when });

/* 17 U.S.C. 305 arrived with the 1976 Act and reached only terms still subsisting on
   1 January 1978. A 28-year first term is still running on that date exactly when copyright
   was secured in 1950 or later, which is the cohort Circular 15A singles out. */
function firstTermEnd(y) {
  return y >= 1950 ? PD(y + 29, 'jan1') : PD(y + 28, 'anniv');
}

/* 104A(a)(1)(B) read with Circular 38B. Restoration takes effect 1 January 1996, so there
   has to be a remainder: the hypothetical 95-year term must not already have run out. */
function restoredTerm(y) {
  if (y + 95 < 1996) return null;
  return PD(y + 96, 'jan1');
}

function statutoryTerm(f) {
  if (!f.published) {
    return f.corp ? PD(f.year + 121, 'jan1') : PD(f.death + 71, 'jan1');
  }
  const y = f.year;
  if (y >= 1978) return PD(null, null);        // 1976 Act regime, not this page's subject
  if (y < 1923) return PD(null, null);         // needs the interim extension acts and the
                                               // pre-CTEA 75-year term; not encoded here
  const abroadOnly = f.where === 'abroad';     // 104A(h)(6)(D)

  /* Did federal copyright ever attach? Publication without notice forfeited it outright
     for everything published before the Berne Convention Implementation Act. */
  if (!f.notice) {
    if (abroadOnly && f.sourceProtected96) return restoredTerm(y) || PD(y, 'pub');
    return PD(y, 'pub');
  }

  /* Notice given, so a first term of 28 years ran from the date copyright was secured.
     Renewal had to be registered for copyrights secured before 1964; the Copyright Renewal
     Act of 1992 made the renewal term vest automatically for 1964 through 1977. */
  const renewalWasRequired = y <= 1963;
  if (!renewalWasRequired || f.renewed) return PD(y + 96, 'jan1');

  /* Not renewed: the copyright fell in at the end of its first term. For a foreign work
     that is a formality failure inside 104A(h)(6)(C)(i), so restoration can pick it up. */
  if (abroadOnly && f.sourceProtected96) return restoredTerm(y) || firstTermEnd(y);
  return firstTermEnd(y);
}

/* -- every expectation below is anchored on something a source actually prints -- */
const US = (o) => Object.assign(
  { published: true, year: 1930, where: 'us', notice: true, renewed: false,
    sourceProtected96: true, death: 0, corp: false }, o);

const ANCHORED = [
  ['1930 US, notice, renewed  [Duke CSPD PDD2026: 1930 works "are in the public domain January 1, 2026"]',
    US({ year: 1930, renewed: true }), 2026, 'jan1'],
  ['1925 US, notice, renewed  [Duke CSPD PDD2021: 1925 works incl. The Great Gatsby, 1 Jan 2021]',
    US({ year: 1925, renewed: true }), 2021, 'jan1'],
  ['1935 France, no notice, protected at home  [Circular 38B: "will expire on December 31, 2030"]',
    US({ year: 1935, where: 'abroad', notice: false }), 2031, 'jan1'],
  ['unpublished, never registered, author died 1955  [Cornell 2026 column: died before 1956]',
    { published: false, corp: false, death: 1955, year: 0 }, 2026, 'jan1'],
  ['unpublished anonymous/for-hire created 1905  [Cornell 2026 column: created before 1906]',
    { published: false, corp: true, year: 1905, death: 0 }, 2026, 'jan1'],
  ['1963 US, notice, no renewal  [Circular 15A: expired 31 December of its 28th year]',
    US({ year: 1963 }), 1992, 'jan1'],
  ['1950 US, notice, no renewal  [Circular 15A, lower edge of the 1950-1963 cohort]',
    US({ year: 1950 }), 1979, 'jan1'],
  ['1949 US, notice, no renewal  [304(a)(1)(A) alone; 305 not yet in force; Circular 15A note]',
    US({ year: 1949 }), 1977, 'anniv'],
  ['1930 US, notice, no renewal  [same rule, pre-1950 cohort]', US({ year: 1930 }), 1958, 'anniv'],
  ['1931 US, notice, no renewal  [same]', US({ year: 1931 }), 1959, 'anniv'],
  ['1939 US, notice, no renewal  [same]', US({ year: 1939 }), 1967, 'anniv'],
  ['1946 US, notice, no renewal  [same]', US({ year: 1946 }), 1974, 'anniv'],
  ['1935 US, no notice  [Cornell: PD for failure to comply with required formalities]',
    US({ year: 1935, notice: false }), 1935, 'pub'],
  ['1939 US, notice, renewed  [Cornell: "95 years after publication date"]',
    US({ year: 1939, renewed: true }), 2035, 'jan1'],
  ['1942 US, notice, renewed  [same chart row]', US({ year: 1942, renewed: true }), 2038, 'jan1'],
  ['1964 US, notice, no filing  [Circular 6A: 1964-1977 works enjoy ninety-five years]',
    US({ year: 1964 }), 2060, 'jan1'],
  ['1977 US, notice  [same]', US({ year: 1977 }), 2073, 'jan1'],
  ['1937 London, no US renewal, protected at home  [Cornell foreign row: 95 years after publication]',
    US({ year: 1937, where: 'abroad' }), 2033, 'jan1'],
  ['1930 London, no US renewal, protected at home  [104A(a)(1)(B) + Circular 38B; Cornell also puts pre-1931 in the PD as of 1 Jan 2026]',
    US({ year: 1930, where: 'abroad' }), 2026, 'jan1'],
  ['1935 France, no notice, already PD at home  [Cornell foreign row: "in the public domain"]',
    US({ year: 1935, where: 'abroad', notice: false, sourceProtected96: false }), 1935, 'pub'],
  ['1922 US, notice, renewed  [304(b): the 1998 extension reached only copyrights subsisting on 27 Oct 1998]',
    US({ year: 1922, renewed: true }), null, null]
];
ANCHORED.forEach(([label, f, wantPd, wantWhen]) => {
  const got = statutoryTerm(f);
  if (got.pd === wantPd && got.when === wantWhen) ok(label, got.pd === null ? 'out of scope' : (got.when + ' ' + got.pd));
  else fail(label, 'got ' + JSON.stringify(got) + ', want ' + JSON.stringify({ pd: wantPd, when: wantWhen }));
});

/* Circular 38B states the restored French 1935 story expires 31 December 2030 */
assertEq('Circular 38B example: expiry the day before the computed PD date',
  statutoryTerm(US({ year: 1935, where: 'abroad', notice: false })).pd - 1, 2030);

/* The bug this section exists to catch: restoration reaches back past 1930, and the answer
   for a restored pre-1931 foreign work is the 95-year date, not the lapsed 28-year one. */
assertTrue('a 1930 foreign restored work is NOT free from its 1958 anniversary',
  statutoryTerm(US({ year: 1930, where: 'abroad' })).pd === 2026,
  'got ' + JSON.stringify(statutoryTerm(US({ year: 1930, where: 'abroad' }))));
assertTrue('the 1930/1931 foreign boundary is continuous, not a 69-year cliff',
  statutoryTerm(US({ year: 1931, where: 'abroad' })).pd -
  statutoryTerm(US({ year: 1930, where: 'abroad' })).pd === 1);

/* ------------------------------------------------------------------ */
/* 4b. the page's own code, lifted out of the HTML and swept           */
/* ------------------------------------------------------------------ */

section('page term machine vs the statutory implementation (full input sweep)');

/* Pull a named declaration out of index.html by brace matching, skipping string literals
   and comments, so the verifier runs the SAME code the reader's browser runs rather than a
   copy of it. If the page and the statute disagree anywhere, this fails. */
function extractBlock(src, marker, open, close) {
  const i = src.indexOf(marker);
  if (i < 0) throw new Error('marker not found in page: ' + marker);
  let j = src.indexOf(open, i);
  let depth = 0, k = j, q = null, line = false, block = false;
  for (; k < src.length; k++) {
    const c = src[k], n = src[k + 1];
    if (line) { if (c === '\n') line = false; continue; }
    if (block) { if (c === '*' && n === '/') { block = false; k++; } continue; }
    if (q) { if (c === '\\') k++; else if (c === q) q = null; continue; }
    if (c === '/' && n === '/') { line = true; k++; continue; }
    if (c === '/' && n === '*') { block = true; k++; continue; }
    if (c === "'" || c === '"' || c === '`') { q = c; continue; }
    if (c === open) depth++;
    else if (c === close) { depth--; if (depth === 0) return src.slice(i, k + 1); }
  }
  throw new Error('unbalanced ' + open + close + ' after ' + marker);
}

const pageSrc = [
  extractBlock(html, 'function unrenewedTerm(y) {', '{', '}'),
  extractBlock(html, 'function usTerm(f) {', '{', '}'),
  extractBlock(html, 'function F(o) {', '{', '}'),
  extractBlock(html, 'var CASES = [', '[', ']') + ';',
  extractBlock(html, 'function mexicoPD(death) {', '{', '}')
].join('\n');
const pageCode = new Function(
  "var DATE='date', RULE='rule';\n" + pageSrc +
  '\nreturn { usTerm: usTerm, CASES: CASES, mexicoPD: mexicoPD };')();

assertTrue('the page no longer carries the "published before 1931" foreign shortcut',
  !/y < 1931/.test(pageSrc), 'the shortcut is still in usTerm');
assertTrue('the page\'s unrenewed branch knows about the 1950 section-305 boundary',
  /y >= 1950/.test(pageSrc), 'unrenewedTerm does not split at 1950');

const WHERES = ['us', 'abroad30', 'abroad'];
let sweep = 0, disagree = [];
for (let y = 1900; y <= 1989; y++) {
  for (const where of WHERES) {
    for (const notice of [true, false]) {
      for (const renewed of [true, false]) {
        for (const sourceProtected96 of [true, false]) {
          const f = { published: true, year: y, where, notice, renewed, sourceProtected96, death: 1955, corp: false };
          const a = pageCode.usTerm(f), b = statutoryTerm(f);
          sweep++;
          if (a.pd !== b.pd || (b.pd !== null && a.when !== b.when)) {
            disagree.push(JSON.stringify(f) + ' page=' + JSON.stringify({ pd: a.pd, when: a.when }) +
              ' statute=' + JSON.stringify(b));
          }
        }
      }
    }
  }
}
for (let d = 1800; d <= 2026; d++) {
  const f = { published: false, year: 0, where: 'us', notice: false, renewed: false, sourceProtected96: false, death: d, corp: false };
  const a = pageCode.usTerm(f), b = statutoryTerm(f);
  sweep++;
  if (a.pd !== b.pd || a.when !== b.when) disagree.push('unpublished death ' + d);
}
for (let y = 1800; y <= 2026; y++) {
  const f = { published: false, year: y, where: 'us', notice: false, renewed: false, sourceProtected96: false, death: 0, corp: true };
  const a = pageCode.usTerm(f), b = statutoryTerm(f);
  sweep++;
  if (a.pd !== b.pd || a.when !== b.when) disagree.push('unpublished corporate ' + y);
}
assertEq('every input the form can produce was swept', sweep, 90 * 3 * 2 * 2 * 2 + 227 + 227);
if (disagree.length === 0) ok('page usTerm and the statutory implementation agree on all ' + sweep + ' inputs');
else fail('page usTerm and the statutory implementation agree on all inputs',
  disagree.length + ' disagreements, first three:\n       ' + disagree.slice(0, 3).join('\n       '));

/* the page's shipped self-test expectations, checked against the statute rather than
   against the page's own function */
const pageCases = pageCode.CASES;
assertEq('the page ships the same number of self-test cases', pageCases.length, ANCHORED.length);
let anchoredRows = 0, datedRows = 0;
pageCases.forEach((c) => {
  const [label, f, wantPd, wantWhen, kind, src] = c;
  const b = statutoryTerm(f);
  if (b.pd !== wantPd || (wantPd !== null && b.when !== wantWhen)) {
    fail('page self-test row "' + label + '" agrees with the statute',
      'page expects ' + JSON.stringify({ pd: wantPd, when: wantWhen }) + ', statute gives ' + JSON.stringify(b));
  } else anchoredRows++;
  if (typeof src === 'string' && src.length > 20 && (kind === 'date' || kind === 'rule')) {
    if (kind === 'date') datedRows++;
  } else {
    fail('page self-test row "' + label + '" names its source', 'anchor missing or malformed');
  }
});
ok('every shipped self-test row agrees with the statutory implementation', anchoredRows + '/' + pageCases.length);
assertTrue('at least five rows are anchored on a date a source actually prints', datedRows >= 5,
  'only ' + datedRows + ' date-anchored rows');
assertTrue('the page tells the reader how many rows are date-anchored',
  html.includes('anchored on a date a source actually prints'));

/* ------------------------------------------------------------------ */
/* 5. the passport engine                                             */
/* ------------------------------------------------------------------ */

section('passport engine');

/* Mexican ladder, written here from the same summary the page cites, then compared against
   the page's own function over every death year the form allows. */
function mexicoPD(death) {
  const ladder = [[20, 1963], [30, 1982], [50, 1994], [75, 2003]];
  for (const [term, until] of ladder) {
    const pd = death + term + 1;
    if (pd <= until) return pd;
  }
  return death + 101;
}
let mxBad = 0;
for (let d = 1900; d <= 2000; d++) if (pageCode.mexicoPD(d).pd !== mexicoPD(d)) mxBad++;
assertEq('the page\'s Mexican ladder matches this one over every death year the form allows', mxBad, 0);

/* US column of the passport is the same statute as Instrument IV, so it is checked the same way */
function passport(pubYear, death, renewed) {
  const us = renewed ? PD(pubYear + 96, 'jan1') : firstTermEnd(pubYear);
  const capped = us.pd <= death + 71;
  return { us: us.pd, usWhen: us.when, eu: capped ? us.pd : death + 71, de: death + 71, mx: mexicoPD(death) };
}

const flagship = passport(1935, 1965, false);
assertEq('flagship US date', flagship.us, 1963);
assertEq('flagship US date is an anniversary, not a 1 January', flagship.usWhen, 'anniv');
assertEq('flagship EU date (comparison of terms follows the US)', flagship.eu, 1963);
assertEq('flagship German date (1892 treaty, national treatment)', flagship.de, 2036);
assertEq('flagship Mexican date', flagship.mx, 2066);
assertTrue('the flagship really is free in two places and owned in two others',
  flagship.us <= 2026 && flagship.eu <= 2026 && flagship.de > 2026 && flagship.mx > 2026);
assertTrue('the passport says which day, not just which year',
  html.includes('its anniversary date in '), 'the passport still prints a bare 1 Jan for every column');

assertEq('Mexico, author died 1951', mexicoPD(1951), 1982);
assertEq('Mexico, author died 1952', mexicoPD(1952), 2053);
assertEq('the Mexican cliff the page describes as seventy-one years',
  mexicoPD(1952) - mexicoPD(1951), 71);
assertTrue('the page describes that cliff as seventy-one years', html.includes('seventy-one years'));
assertEq('Mexico, author died 1940 (life+20 regime ran out first)', mexicoPD(1940), 1961);

/* Steamboat Willie in Germany, the COMMUNIA example: Wilfred Jackson died 1988 */
assertEq('German term for an author who died in 1988 ends after 2058', 1988 + 71, 2059);
assertTrue('page states the German Steamboat Willie term as the end of 2058', html.includes('2058'));

/* ------------------------------------------------------------------ */
/* 5b. disclosures the page must carry after the term-machine fix      */
/* ------------------------------------------------------------------ */

section('disclosures');

assertTrue('the sparse table is described as 443,646 of 445,386 rows, not "all 445,386"',
  html.includes('443,646 rows of the 445,386-row') && !/all 445,386 rows of NYPL/.test(html));
assertTrue('the dropped rows are named as a known omission',
  html.includes('1,740 rows') || html.includes('1,740 rows of'));
assertTrue('the CCE print run is stated as 1891 through 1978, microfiche to 1982',
  html.includes('1891 through 1978') && html.includes('microfiche') && html.includes('1982'));
assertTrue('the Circular 38B blockquote is not truncated',
  html.includes('if the work had never entered the public domain in the United States.'));
assertTrue('the NYPL 3.7 multiplier is attributed to the total, not to the non-renewals',
  html.includes('3.7037 times the renewal count') && html.includes('21.28%'));
assertTrue('the page carries the embedded-material caveat',
  /previously\s+published material still under copyright/.test(html));
assertTrue('Instrument II offers a class-A-only control',
  html.includes('Class A only') && /mode === 'A'/.test(html));
assertTrue('the term machine declines below 1923 rather than guessing',
  html.includes('First published before 1923: outside the range this machine will answer for.'));
assertTrue('the check panel names the three different public-domain days',
  html.includes('Three different days, and the machine says which'));
assertTrue('the coverage chips are labelled as computed, and two of them as midpoints',
  html.includes('midpoint of the measured') && html.includes('Two of the three coverage chips are midpoints'));
assertTrue('the base-rate chips are built from counts rather than typed',
  html.includes('data-base-key="ringer"') && !/data-base="691"/.test(html));
assertTrue('the register size is measured off the page rather than asserted',
  html.includes('characters of base64 wrapping') && !html.includes('2.9 MB of compressed text'));

/* ------------------------------------------------------------------ */
/* 6. the Bayes instrument                                            */
/* ------------------------------------------------------------------ */

section('posterior for a failed search');
function posterior(r, c, m) {
  const missGivenRenewed = 1 - c * (1 - m);
  return (1 - r) / ((1 - r) + r * missGivenRenewed);
}
assertClose('defaults r=25.29%, c=99%, m=5%', posterior(0.2529, 0.99, 0.05), 0.980256, 0.000005);
assertClose('same coverage at Ringer 6.91%', posterior(0.0690791, 0.99, 0.05), 0.995604, 0.000005);
assertClose('same coverage at 33.38%', posterior(0.333826, 0.99, 0.05), 0.971047, 0.000005);
assertClose('perfect coverage and no match failure gives certainty', posterior(0.2529, 1, 0), 1, 1e-12);
assertClose('coverage 90% at the headline base rate', posterior(0.2529, 0.90, 0.05), 0.953213, 0.00001);
assertTrue('the page states that 99% -> 90% moves the posterior from about 0.980 to about 0.953',
  html.includes('0.980') && html.includes('0.953'),
  'the prose does not print both endpoints');
assertTrue('the posterior falls monotonically as coverage falls',
  posterior(0.2529, 0.99, 0.05) > posterior(0.2529, 0.90, 0.05) &&
  posterior(0.2529, 0.90, 0.05) > posterior(0.2529, 0.70, 0.05));

/* ------------------------------------------------------------------ */
/* 7. optional: rebuild the index from the raw NYPL transcription      */
/* ------------------------------------------------------------------ */

const tsvFlag = process.argv.indexOf('--tsv');
if (tsvFlag >= 0 && process.argv[tsvFlag + 1]) {
  section('rebuild from raw NYPL cce-renewals TSVs');
  const dir = process.argv[tsvFlag + 1];
  const files = fs.readdirSync(dir).filter((f) => f.endsWith('.tsv')).sort();
  assertEq('tsv files found', files.length, 47);
  const clean = (s) => (s || '').replace(/[\t\r\n|]+/g, ' ').replace(/\s+/g, ' ').trim();
  const codesOf = (s) => [...new Set((s || '').split('||')
    .map((p) => (p.split('|')[1] || '').trim()).filter(Boolean))].join('/').slice(0, 14);
  const toDay = (s) => {
    const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
    return m ? Math.round((Date.UTC(+m[1], +m[2] - 1, +m[3]) - EPOCH) / 86400000) : null;
  };
  let scanned = 0, usable = 0;
  const idx = [];
  const hist2 = new Map();
  for (const f of files) {
    const lines = fs.readFileSync(path.join(dir, f), 'utf8').split('\n');
    for (let k = 1; k < lines.length; k++) {
      if (!lines[k].trim()) continue;
      scanned++;
      const c = lines[k].split('\t');
      if (c.length < 12) continue;
      const [oreg, odat, rid, rdat] = [c[7], c[8], c[9], c[10]];
      if (!oreg || !odat || !rid || !rdat) continue;
      const od = toDay(odat), rd = toDay(rdat);
      if (od === null || rd === null) continue;
      usable++;
      const oy = +odat.slice(0, 4), ry = +rdat.slice(0, 4);
      let cls = oreg.replace(/[0-9].*$/, '').replace(/-+$/, '').trim() || '?';
      const hk = oy + '|' + cls + '|' + (ry - oy);
      hist2.set(hk, (hist2.get(hk) || 0) + 1);
      if (BOOK.has(cls) && oy >= 1923 && oy <= 1940) {
        idx.push({ t: clean(c[6]).slice(0, 72), a: clean(c[5]).slice(0, 40), o: oreg, od, i: rid, rd, cc: codesOf(c[11]) });
      }
    }
  }
  assertEq('rows scanned', scanned, 445386);
  assertEq('rows with a parseable registration and renewal', usable, 443646);
  assertEq('rebuilt index row count', idx.length, 73705);
  idx.sort((x, y) => {
    const a = x.t.toLowerCase(), b = y.t.toLowerCase();
    return a < b ? -1 : a > b ? 1 : x.od - y.od;
  });
  const rebuilt = [String(idx.length), idx.map((r) => r.t).join('\n'), idx.map((r) => r.a).join('\n'),
    idx.map((r) => r.o + ',' + r.od.toString(36) + ',' + r.i + ',' + r.rd.toString(36) + ',' + r.cc).join('\n')].join(RS);
  const rebuiltSha = crypto.createHash('sha256').update(Buffer.from(rebuilt, 'utf8')).digest('hex');
  assertEq('rebuilt index is byte-identical to the block bundled in the page', rebuiltSha, sha);
  const rows2 = [...hist2.entries()].map(([k, v]) => { const p = k.split('|'); return [+p[0], p[1], +p[2], v]; })
    .filter((r) => r[0] >= 1800 && r[0] <= 2010)
    .sort((p, q) => p[0] - q[0] || (p[1] < q[1] ? -1 : p[1] > q[1] ? 1 : 0) || p[2] - q[2]);
  const h1 = crypto.createHash('sha256').update(JSON.stringify(rows2)).digest('hex').slice(0, 16);
  const h2 = crypto.createHash('sha256').update(JSON.stringify(HIST)).digest('hex').slice(0, 16);
  assertEq('rebuilt histogram matches the bundled one (sha256 prefix)', h1, h2);
  const full = new Set();
  for (const f of files) {
    const t = fs.readFileSync(path.join(dir, f), 'utf8').toLowerCase();
    if (t.includes('hobbit')) full.add('hobbit');
    if (/it.{0,2}s a wonderful life/.test(t)) full.add('wonderful');
  }
  assertEq('no "hobbit" anywhere in all 47 raw files', full.has('hobbit'), false);
  assertEq('no "it\'s a wonderful life" anywhere in all 47 raw files', full.has('wonderful'), false);
} else {
  section('rebuild from raw NYPL cce-renewals TSVs');
  console.log('  skipped (pass --tsv /path/to/cce-renewals/data to enable the byte-identity check)');
}

/* ------------------------------------------------------------------ */

console.log('\n' + (failures === 0 ? 'PASS' : 'FAIL') + ': ' + (checks - failures) + '/' + checks + ' checks');
process.exit(failures === 0 ? 0 : 1);
