#!/usr/bin/env node
// research/held-in-common/verify.mjs — the cutoff gate for "Held in Common"
// (/strata/held-in-common/), the public-domain rights-clearance stratum.
//
// WHY THIS EXISTS. The page is a rights tool: it tells a reader whether a work is
// free to republish. Its load-bearing claim is the US 95-year publication line, and
// that line MOVES: it advances one year at midnight every 1 January. The page used to
// state it in three hardcoded forms ("pre-1929", "1930 or earlier", "pre-1931"), which
// disagreed with each other by two years and would all have been wrong on 1 January
// 2027. A wrong year on this page is not a typo; it is the answer.
//
// WHAT IT CHECKS. It reads the SHIPPED page and runs the page's own derivation. It
// does NOT restate the rule alongside the page and compare two copies of the same
// sentence — a page-blind verifier ("C0" here) proves nothing about what shipped.
// Concretely:
//
//   1. it lifts the page's `pd-rule` block (the single place the cutoff is worked out)
//      straight out of public/strata/held-in-common/index.html and evaluates it;
//   2. it checks that block's answers against an INDEPENDENT restatement of the term
//      (a work published in year P is protected for 95 years and enters the public
//      domain on the following 1 January, so on 1 January of year Y everything
//      published in Y-96 and earlier is free), plus two dated anchors: 1929 works
//      became free on 1 Jan 2025 and 1930 works on 1 Jan 2026;
//   3. it exercises that derivation across stated "as of" years, 2026 and 2027 among
//      them, and rebuilds the exact sentences the page will print in those years;
//   4. it asserts that no publication-cutoff year survives as a literal anywhere in
//      the page's rights logic — every year the reader sees must come from the block.
//
// WHAT IT IS NOT. It does not check that the 95-year term is the law; that is cited on
// the page (US Copyright Office, Hirtle/Cornell term chart). It does not clear any
// work: renewal, restoration, and foreign terms sit outside it, which is why the page
// gives a procedure and not legal advice.
//
//   Run:  node research/held-in-common/verify.mjs      (exit 0 = all checks pass)

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

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const PAGE_REL = 'public/strata/held-in-common/index.html';
const html = fs.readFileSync(path.join(ROOT, PAGE_REL), 'utf8');

let pass = 0, fail = 0;
function check(name, cond, detail = '') {
  cond ? pass++ : fail++;
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  —  ' + detail : ''}`);
}
function die(msg) {
  console.error(`\nFATAL  ${msg}`);
  console.error(`${pass}/${pass + fail} checks pass (aborted).\n`);
  process.exit(2);
}

console.log(`\nHeld in Common — the public-domain cutoff gate`);
console.log(`reading the shipped page: ${PAGE_REL}\n`);

// ─── 1. lift the page's own derivation out of the shipped file ───────────────
console.log('§1  the page\'s single source of the cutoff');

const BLOCK_RE = /\/\* ==== pd-rule[\s\S]*?\*\/\s*([\s\S]*?)\/\* ==== \/pd-rule ==== \*\//;
const blockMatch = html.match(BLOCK_RE);
check('page carries exactly one `pd-rule` block', !!blockMatch &&
  html.split('==== pd-rule').length === 2);
if (!blockMatch) die('no pd-rule block in the shipped page: nothing to verify against.');
const BLOCK = blockMatch[1];

check('the block reads the clock rather than a typed-in year',
  /new Date\(\)\.getFullYear\(\)/.test(BLOCK));

let PD;
try {
  PD = new Function(
    BLOCK + '\nreturn { pdCutoffYear, pdCutoffPhrase, pdAsOfPhrase, pdRuleSentence, AS_OF, PD_CUTOFF };'
  )();
} catch (e) {
  die(`the page's pd-rule block does not evaluate: ${e.message}`);
}
check('the block exports the four derivations the page uses',
  ['pdCutoffYear', 'pdCutoffPhrase', 'pdAsOfPhrase', 'pdRuleSentence']
    .every((k) => typeof PD[k] === 'function'));
check('the page\'s live cutoff is derived from its live "as of" year',
  PD.PD_CUTOFF === PD.pdCutoffYear(PD.AS_OF) && PD.AS_OF === new Date().getFullYear(),
  `as of ${PD.AS_OF} → ${PD.PD_CUTOFF}`);

// ─── 2. the derivation against an independent statement of the term ──────────
console.log('\n§2  the derivation against the term, restated independently');

// Independent restatement, deliberately not written as "asOf - 96": a work published
// in year P holds copyright for 95 years and falls into the public domain on the
// 1 January that follows the end of that term, i.e. on 1 January of P + 96. So walk
// back from the "as of" year to the newest publication year that has already crossed.
function newestFreeYear(asOfYear) {
  let p = asOfYear;
  while (p + 95 + 1 > asOfYear) p--;
  return p;
}

const AS_OF_YEARS = [2024, 2025, 2026, 2027, 2028, 2030, 2040, 2100];
for (const y of AS_OF_YEARS) {
  const got = PD.pdCutoffYear(y);
  const want = newestFreeYear(y);
  check(`as of ${y}: the page derives ${got}`, got === want, `term says ${want}`);
}

// Dated anchors, from the published record of Public Domain Day.
check('1929 US publications became free on 1 January 2025', PD.pdCutoffYear(2025) === 1929);
check('1930 US publications became free on 1 January 2026', PD.pdCutoffYear(2026) === 1930);
check('the line moves exactly one year per year',
  AS_OF_YEARS.every((y) => PD.pdCutoffYear(y + 1) === PD.pdCutoffYear(y) + 1));

// ─── 3. the sentences the page will actually print ───────────────────────────
console.log('\n§3  the sentences the page builds, per "as of" year');

for (const y of [2026, 2027, 2028]) {
  const cut = PD.pdCutoffYear(y);
  const built = [PD.pdCutoffPhrase(y), PD.pdAsOfPhrase(y), PD.pdRuleSentence(y)];
  const stale = [cut - 3, cut - 2, cut - 1, cut + 1, cut + 2].map(String);
  check(`as of ${y}: every phrasing names ${cut} and no other cutoff year`,
    built.every((s) => s.includes(String(cut)) && !stale.some((z) => s.includes(z))));
  built.forEach((s) => console.log(`        · ${s}`));
}
check('the "as of" year is stated alongside the cutoff, so a reader can date the claim',
  PD.pdAsOfPhrase(2027).includes('2027') && PD.pdRuleSentence(2027).includes('2027'));
check('the page still tells the reader the line advances every 1 January',
  /1 January/.test(PD.pdRuleSentence(PD.AS_OF)));

// ─── 4. no hardcoded cutoff year survives in the rights logic ────────────────
console.log('\n§4  no stale hardcoded cutoff anywhere in the rights logic');

// 4a. the exact forms the page used to carry, and the family they belong to.
const STALE_FORMS = [
  [/pre-\d{4}\s+publication/i, '"pre-YYYY publication" cutoff'],
  [/\bUS\s+pre-\d{4}\b/i, '"US pre-YYYY" cutoff'],
  [/pre-\d{4}\s+film/i, '"pre-YYYY film" cutoff'],
  [/published\s+in\s+\d{4}\s+or\s+earlier/i, 'literal-year "published in YYYY or earlier"'],
  [/\bin\s+\d{4}\s+or\s+earlier\b/i, 'literal-year "in YYYY or earlier"'],
  [/published\s+after\s+\d{4}/i, 'literal-year "published after YYYY"'],
  [/public domain as of\s+\d{4}/i, 'literal-year "public domain as of YYYY"'],
  [/\bPD as of\s+\d{4}/i, 'literal-year "PD as of YYYY"'],
  [/pub\s*≤\s*\d{4}/i, 'literal-year "pub ≤YYYY" trail label'],
];
// The claims record folded into the page (<!--aw-assay:...-->, since 2026-10-07) quotes the old forms as history;
// it is a record of what was checked, not rights logic, so it is left out here as the other verifiers leave it out.
const rights = html.replace(/<!--aw-assay:start-->[\s\S]*?<!--aw-assay:end-->/g, ' ');
for (const [re, what] of STALE_FORMS) {
  const hit = rights.match(re);
  check(`no ${what} in the shipped page`, !hit, hit ? `found: "${hit[0]}"` : '');
}

// 4b. the decision table itself: every four-digit year in it must be a documented
// non-cutoff fact. Anything else is a cutoff someone typed in by hand.
const tStart = html.indexOf('var T = {');
const tEnd = html.indexOf('\n    };', tStart);
check('the checker\'s decision table is locatable', tStart > -1 && tEnd > tStart);
if (tStart < 0 || tEnd < 0) die('cannot locate the checker decision table.');
const TABLE = html.slice(tStart, tEnd);

// Years that legitimately appear in the table, each for a reason that is NOT the
// 95-year publication line. Every one of these is a fixed historical fact.
const ALLOWED_YEARS = {
  1923: 'Music Modernization Act: US sound recordings published before 1923 (a separate statute)',
  1999: 'Bridgeman v. Corel, the 2-D reproduction case',
  2010: 'an illustrative "a 2010 Beethoven performance"',
  2022: 'the MMA date those pre-1923 recordings actually entered the public domain',
};
const tableYears = [...new Set((TABLE.match(/\b(1[5-9]\d{2}|20\d{2})\b/g) || []).map(Number))].sort();
const unexplained = tableYears.filter((y) => !(y in ALLOWED_YEARS));
check('every literal year in the decision table is a documented non-cutoff fact',
  unexplained.length === 0,
  unexplained.length ? `unexplained: ${unexplained.join(', ')}` : tableYears.join(', '));

// And belt-and-braces: nothing anywhere near the live cutoff or the live year may be
// sitting in the table as a literal, whatever phrasing it hides behind.
const forbidden = [];
for (let y = PD.PD_CUTOFF - 5; y <= PD.PD_CUTOFF + 5; y++) forbidden.push(y);
for (let y = PD.AS_OF - 2; y <= PD.AS_OF + 2; y++) forbidden.push(y);
const planted = forbidden.filter((y) => new RegExp(`\\b${y}\\b`).test(TABLE));
check(`no literal year near the live line (${PD.PD_CUTOFF}±5) or the live year (${PD.AS_OF}±2) in the table`,
  planted.length === 0, planted.length ? `found: ${planted.join(', ')}` : '');

// 4c. the specimen labels: the three that rest on the US line must take their year
// from the block too, and must still read true with JavaScript off.
const parenSpans = html.match(/<span data-pd="paren"><\/span>/g) || [];
check('the three US-line specimen labels carry the interpolation hook',
  parenSpans.length === 3, `${parenSpans.length} found`);
check('the block fills those hooks from the same derivation',
  /data-pd="paren"[\s\S]{0,240}pdAsOfPhrase\(AS_OF\)/.test(html));
const rightsCells = (html.match(/<dd class="rights">[\s\S]*?<\/dd>/g) || [])
  .filter((c) => c.includes('data-pd="paren"'));
check('with JavaScript off each of those labels still states a true rule, and no year',
  rightsCells.length === 3 &&
  rightsCells.every((c) => /95-year term/.test(c) &&
    !/\b(1[5-9]\d{2}|20\d{2})\b/.test(c.replace(/d\.\s*\d{4}|1 Jan \d{4}|published 1923/g, ''))),
  rightsCells.length ? '' : 'no rights cells found');

// 4d. one rule, one phrasing: every statement of the line runs through the block.
const uses = (html.match(/pdCutoffPhrase\(AS_OF\)|pdRuleSentence\(AS_OF\)|pdAsOfPhrase\(AS_OF\)|PD_CUTOFF/g) || []).length;
check('every stated form of the line is interpolated from the block', uses >= 8, `${uses} call sites`);
check('the page says one thing: all cutoff prose is built from pdCutoffPhrase',
  PD.pdAsOfPhrase(2026).startsWith(PD.pdCutoffPhrase(2026)) &&
  PD.pdRuleSentence(2026).includes(PD.pdCutoffPhrase(2026)));

// ─── 5. the caveats a rights tool must keep ─────────────────────────────────
console.log('\n§5  the page is still a guide and not a clearance');
check('the checker is still labelled "a guide, not legal advice"', /a guide, not legal advice/.test(html));
check('the "verify at the source" rule still shows under every verdict',
  /verify at the source, record the provenance exactly/.test(html));
check('the jurisdiction caveat survives', /Verify your own jurisdiction/.test(html));

// ─── tally ───────────────────────────────────────────────────────────────────
const total = pass + fail;
console.log(`\n${pass}/${total} checks pass.`);
if (fail) {
  console.error(`${fail} FAILED — the page's public-domain line is not trustworthy as shipped.\n`);
  process.exit(1);
}
console.log(`The US line is derived, not typed: as of ${PD.AS_OF} the page says "${PD.pdCutoffPhrase(PD.AS_OF)}", and on 1 January ${PD.AS_OF + 1} it will say "${PD.pdCutoffPhrase(PD.AS_OF + 1)}" with nobody touching it.\n`);
process.exit(0);
