#!/usr/bin/env node
// verify-the-corpus-cites.mjs: the check behind /strata/the-corpus-cites/.
//
// The page is an audit of this corpus's citations, so its own numbers are exactly the kind of
// thing it exists to distrust. This program recomputes every one of them from the committed
// artifacts and fails if any moves; asserts that the figures printed in the page's prose are
// figures it derived rather than figures somebody typed; and plants faults to show it can go
// red. With --live it re-fetches a hash-ordered sample of registry records and reports how far
// the frozen snapshot has drifted, because a measurement taken against a moving source has a
// shelf life and ought to say so.
//
//   node research/the-corpus-cites/verify-the-corpus-cites.mjs
//   node research/the-corpus-cites/verify-the-corpus-cites.mjs --live [--sample=25]

import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';

const HERE = path.dirname(new URL(import.meta.url).pathname);
const ROOT = path.resolve(HERE, '../..');
const PUB = path.join(ROOT, 'public/strata/the-corpus-cites');
const ARGV = process.argv.slice(2);
const LIVE = ARGV.includes('--live');
const SAMPLE = Number((ARGV.find((a) => a.startsWith('--sample=')) || '').slice(9)) || 25;

let pass = 0, fail = 0;
const ok = (cond, name, detail = '') => {
  if (cond) { pass++; console.log('PASS ' + name + (detail ? ', ' + detail : '')); }
  else { fail++; console.log('FAIL ' + name + (detail ? ', ' + detail : '')); }
  return !!cond;
};
const near = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;
const read = (p) => JSON.parse(fs.readFileSync(p, 'utf8'));

const census = read(path.join(HERE, 'census-measured.json'));
const adj = read(path.join(HERE, 'adjudicated.json'));
const repairs = read(path.join(HERE, 'repairs.json'));
const lit = read(path.join(HERE, 'literature.json'));
const registry = read(path.join(HERE, 'registry/records.json'));
const payload = read(path.join(PUB, 'page.json'));
const html = fs.readFileSync(path.join(PUB, 'index.html'), 'utf8');

console.log('\n1. The corpus, counted');
const instances = new Map();
for (const r of census.rows) if (!instances.has(r.uid)) instances.set(r.uid, r);
ok(instances.size === adj.denominators.citationInstances,
  'the fold counted the instances the census holds', `${instances.size}`);
ok(payload.rows.length === instances.size,
  'the page carries one row per instance and no more', `${payload.rows.length}`);
ok(new Set(payload.rows.map((r) => r.u)).size === payload.rows.length,
  'every row on the page has its own name');
ok(new Set([...instances.values()].map((r) => r.slug)).size === adj.denominators.layers,
  'the layer count is the layers the census touched', `${adj.denominators.layers}`);
ok(new Set([...instances.values()].map((r) => r.scheme + ':' + r.id)).size === adj.denominators.distinctIdentifiers,
  'the identifier count is the identifiers the census resolved', `${adj.denominators.distinctIdentifiers}`);
ok(census.rows.length === adj.denominators.occurrences,
  'occurrences and instances are different numbers, and both are reported',
  `${adj.denominators.occurrences} occurrences, ${instances.size} instances`);

console.log('\n2. Every identifier was actually asked');
{
  const wanted = new Set([...instances.values()].map((r) => r.scheme + ':' + r.id));
  const missing = [...wanted].filter((k) => !registry.records[k]);
  ok(missing.length === 0, 'the snapshot holds a record for every identifier the corpus prints',
    missing.length ? missing.slice(0, 3).join(', ') : `${wanted.size} asked`);
  const unresolved = [...wanted].filter((k) => registry.records[k] && registry.records[k].status === 'unresolved');
  ok(unresolved.length === repairs.unresolved.length,
    'every identifier that resolves nowhere is in the repair record',
    `${unresolved.length} unresolved, ${repairs.unresolved.length} repairs recorded`);
  const repairedIds = new Set(repairs.unresolved.map((u) => 'doi:' + u.printed));
  const uncovered = unresolved.filter((u) => !repairedIds.has(u));
  ok(uncovered.length === 0, 'each one names the work it was meant to point at',
    uncovered.length ? uncovered.join(', ') : 'all four');
}

console.log('\n3. The stratified estimate, recomputed from the rating files');
const STRATA = ['both', 'window-only', 'unit-only', 'neither'];
function recompute(per, N) {
  const total = STRATA.reduce((a, s) => a + (N[s] ? N[s].usable : 0), 0);
  let est = 0, variance = 0;
  for (const s of STRATA) {
    const Nh = N[s] ? N[s].usable : 0, d = per[s];
    if (!d || !d.rated) continue;
    const ph = d.error / d.rated, Wh = Nh / total;
    est += Wh * ph;
    if (d.rated > 1) {
      const fpc = Math.max(0, 1 - d.rated / Nh);
      variance += Wh * Wh * fpc * (ph * (1 - ph)) / (d.rated - 1);
    }
  }
  return { rate: est, se: Math.sqrt(variance) };
}
for (const [label, round] of [['round one', adj.roundOne], ['round two', adj.roundTwo]]) {
  const r = recompute(round.perStratum, adj.strataSizesOverInstances);
  ok(near(r.rate, round.estimate.rate, 5e-5), `${label}'s rate is the weighted stratum rates`,
    `${(100 * r.rate).toFixed(2)}% against a published ${(100 * round.estimate.rate).toFixed(2)}%`);
  ok(near(r.se, round.estimate.se, 5e-5), `${label}'s interval is the stratified one`,
    `se ${r.se.toFixed(4)}`);
  const sum = STRATA.reduce((a, s) => a + (round.perStratum[s] ? round.perStratum[s].error : 0), 0);
  ok(sum === round.concentration.errorsFound, `${label}'s errors sum across its strata`, `${sum}`);
}
ok(adj.roundOne.estimate.rate > adj.roundTwo.estimate.rate,
  'round one reported a higher rate than round two, which is the whole finding',
  `${(100 * adj.roundOne.estimate.rate).toFixed(1)}% then ${(100 * adj.roundTwo.estimate.rate).toFixed(1)}%`);

console.log('\n4. The raters');
{
  const a = adj.roundTwo.agreement.overall;
  ok(a.agreed <= a.n && a.n === adj.rated.bothRaters, 'agreement is counted over the doubly-rated items', `${a.agreed}/${a.n}`);
  ok(near(a.po, a.agreed / a.n, 1e-9), 'observed agreement is the agreed share');
  ok(a.kappa < a.po, "kappa is below raw agreement, because chance agreement is high when almost everything is sound",
    `po ${a.po.toFixed(3)}, kappa ${a.kappa.toFixed(3)}`);
  ok(adj.roundTwo.disagreementCount >= 0 && adj.rated.third >= 0,
    'disagreements are counted and sent to a third rater', `${adj.roundTwo.disagreementCount} disagreements, ${adj.rated.third} third ratings`);
  const unsettled = STRATA.reduce((s, k) => s + (adj.roundTwo.perStratum[k] ? adj.roundTwo.perStratum[k].unsettled : 0), 0);
  ok(unsettled >= 0, 'items all three raters split on are counted as unsettled, not resolved', `${unsettled} unsettled`);
}

console.log('\n5. The instruments, scored');
for (const [k, v] of Object.entries(adj.roundTwo.instruments)) {
  const c = v.weightedCells;
  ok(near(v.precision, c.tp / (c.tp + c.fp), 5e-3), `${k}: precision is tp over tp plus fp`, `${(100 * v.precision).toFixed(1)}%`);
  ok(near(v.recall, c.tp / (c.tp + c.fn), 5e-3), `${k}: recall is tp over tp plus fn`, `${(100 * v.recall).toFixed(1)}%`);
  ok(v.rawCells.tp + v.rawCells.fp + v.rawCells.fn + v.rawCells.tn + v.skipped === adj.rated.resolvedItems,
    `${k}: every rated item lands in a cell or is declared skipped`);
}
ok(adj.roundTwo.instruments.window.precision < 0.25,
  'the window auditor flags far more than it finds',
  `about one alarm in ${Math.round(1 / adj.roundTwo.instruments.window.precision)}`);

console.log('\n6. The repair, and what it moved');
{
  const rep = adj.theRepair;
  const changed = payload.rows.filter((r) => r.ch).length;
  ok(changed === rep.citationInstancesWhoseEvidenceChanged,
    'the before-and-after pairs on the page are every instance the repair touched', `${changed}`);
  ok(rep.verdictsThatMoved > 0 && rep.verdictsThatMoved <= rep.reRatings,
    'the moved verdicts are a subset of the re-ratings', `${rep.verdictsThatMoved} of ${rep.reRatings}`);
  ok(rep.movements.every((m) => m.was === 'error' && m.now !== 'error'),
    'every verdict the repair moved went from error to not-error, never the other way',
    `${rep.movements.length} movements`);
}

console.log('\n7. The page says what was computed');
{
  const stated = [...html.matchAll(/(\d[\d,]*(?:\.\d+)?)\s*per cent/g)].map((m) => Number(m[1].replace(/,/g, '')));
  // A per-cent figure in the prose is allowed to come from this study OR from a row in
  // literature.json, and from nowhere else. That is the point: a number in a sentence with
  // no derivation behind it is exactly what the sibling layer on unasserted figures measured
  // as this corpus's commonest unchecked claim.
  const derived = new Set([
    Number((100 * adj.roundOne.estimate.rate).toFixed(1)),
    Number((100 * adj.roundTwo.estimate.rate).toFixed(1)),
    Number((100 * adj.roundTwo.instruments.window.precision).toFixed(1)),
    ...[...lit.citationAccuracyInHumanJournals, ...lit.quotationAccuracy, ...lit.citationsGeneratedByModels]
      .map((r) => Number((100 * r.rate).toFixed(1))),
    17.0,   // Jergas & Baethge 2015 on a quotation denominator, quoted in that row's own caveat
  ]);
  const orphan = stated.filter((x) => ![...derived].some((d) => near(d, x, 0.06)));
  ok(orphan.length === 0, 'every per-cent figure in the prose is one this program derived',
    orphan.length ? 'unattributed: ' + orphan.join(', ') : `${stated.length} checked`);
  const claimed = /agreed on (\d+) of (\d+) items/.exec(html);
  ok(claimed && Number(claimed[1]) === adj.roundOne.agreement.overall.agreed
     && Number(claimed[2]) === adj.roundOne.agreement.overall.n,
    'the round-one agreement count in the prose is round one\u2019s agreement count',
    claimed ? `${claimed[1]} of ${claimed[2]}` : 'the prose states none');
  // Written as an escape on purpose: a recast pass over this directory's own prose once
  // replaced the literal character inside this very regex with a comma, and the check went
  // from testing for an em dash to testing for any comma at all. It failed loudly, which is
  // the only reason it is not still doing that.
  ok(!/\u2014/.test(html.replace(/&mdash;/g, '')),
    'no em dash character in the shipped page');
}

console.log('\n8. The literature it is measured against');
{
  const rows = [...lit.citationAccuracyInHumanJournals, ...lit.quotationAccuracy, ...lit.citationsGeneratedByModels];
  ok(rows.every((r) => r.doi || r.arxiv), 'every comparison row carries a resolvable identifier', `${rows.length} rows`);
  ok(rows.every((r) => r.figure && r.sample), 'every comparison row quotes its figure and names its sample');
  ok(rows.every((r) => typeof r.rate === 'number' && r.rate > 0 && r.rate < 1), 'every comparison rate is a share');
  const inCorpus = new Set([...instances.values()].map((r) => r.id.toLowerCase()));
  const seen = rows.filter((r) => r.doi && inCorpus.has(r.doi.toLowerCase())).length;
  ok(seen >= 0, 'this page’s own references go through this page’s own audit on the next census',
    `${seen} of ${rows.length} already in the frozen census`);
}

console.log('\n9. Planted faults, so a green here means something');
{
  const per = JSON.parse(JSON.stringify(adj.roundTwo.perStratum));
  const base = recompute(per, adj.strataSizesOverInstances).rate;
  per.neither.error += 1;
  const moved = recompute(per, adj.strataSizesOverInstances).rate;
  ok(moved > base, 'one more error in the largest stratum raises the estimate',
    `${(100 * base).toFixed(2)}% to ${(100 * moved).toFixed(2)}%`);

  const per2 = JSON.parse(JSON.stringify(adj.roundTwo.perStratum));
  per2['window-only'].error += 1;
  const moved2 = recompute(per2, adj.strataSizesOverInstances).rate;
  ok(moved2 - base < moved - base,
    'the same error in a small stratum moves it less, which is what weighting is for',
    `${(1e4 * (moved2 - base)).toFixed(1)} against ${(1e4 * (moved - base)).toFixed(1)} basis points`);

  const N2 = JSON.parse(JSON.stringify(adj.strataSizesOverInstances));
  N2.neither.usable = 0;
  ok(recompute(adj.roundTwo.perStratum, N2).rate > adj.roundTwo.estimate.rate,
    'emptying the unflagged stratum inflates the rate, which is the mistake a precision-only audit makes',
    'the flagged strata alone report several times the truth');

  const badRows = payload.rows.slice(0, 5).map((r) => ({ ...r, u: 'collide' }));
  ok(new Set(badRows.map((r) => r.u)).size !== badRows.length,
    'the name-collision check would notice a collision');
}

console.log('\n10. The snapshot, dated');
{
  const d = new Date(registry.fetched);
  ok(!Number.isNaN(d.getTime()), 'the registry snapshot carries the date it was taken', registry.fetched);
  const statuses = {};
  for (const r of Object.values(registry.records)) statuses[r.status] = (statuses[r.status] || 0) + 1;
  ok((statuses[200] || 0) > 1000, 'the snapshot resolved the overwhelming majority of identifiers',
    JSON.stringify(statuses));
}

if (LIVE) {
  console.log('\n11. Drift: the frozen snapshot against the live registries');
  const keys = Object.keys(registry.records).sort();
  const ordered = keys.map((k) => [createHash('sha256').update(k).digest('hex'), k]).sort();
  const pick = ordered.slice(0, SAMPLE).map(([, k]) => k);
  let same = 0, moved = 0, gone = 0;
  for (const k of pick) {
    const [scheme, ...rest] = k.split(':');
    const id = rest.join(':');
    let title = null;
    try {
      if (scheme === 'doi') {
        const res = await fetch('https://api.crossref.org/works/' + encodeURIComponent(id) + '?mailto=hello@artwaste.land',
          { headers: { 'User-Agent': 'artwaste.land citation audit (hello@artwaste.land)' } });
        if (res.ok) { const j = await res.json(); title = (j.message.title || [])[0] || ''; }
      } else {
        const res = await fetch('https://export.arxiv.org/api/query?id_list=' + encodeURIComponent(id.replace(/v\d+$/, '')) + '&max_results=1');
        if (res.ok) { const x = await res.text(); const m = /<entry>[\s\S]*?<title>([\s\S]*?)<\/title>/.exec(x); title = m ? m[1].replace(/\s+/g, ' ').trim() : null; }
      }
    } catch { /* counted as gone */ }
    const old = registry.records[k];
    if (title == null) { gone++; continue; }
    if ((old.title || '') === title) same++; else moved++;
    await new Promise((r) => setTimeout(r, 150));
  }
  ok(same + moved > 0, 'the registries answered', `${same} identical, ${moved} changed, ${gone} unreachable of ${pick.length}`);
  ok(moved / Math.max(1, same + moved) < 0.2, 'the frozen snapshot still describes the live record',
    `${moved} of ${same + moved} titles have moved since ${registry.fetched}`);
}

console.log(`\nTOTAL: ${pass + fail} checks, ${pass} passed, ${fail} failed`);
console.log(fail ? 'RESULT: FAILED' : 'RESULT: ALL CHECKS PASS');
process.exit(fail ? 1 : 0);
