#!/usr/bin/env node
// verify-nothing-funny-happened.mjs
//
//   node verify-nothing-funny-happened.mjs            (offline: artifacts vs page)
//   node verify-nothing-funny-happened.mjs --rerun    (also re-derive from the corpora)
//
// Two jobs.
//
//   1. RE-DERIVE. With --rerun, run the measurement scripts again from the
//      downloaded corpora and check that they produce the committed artifacts.
//      This is what makes the numbers reproducible rather than asserted.
//   2. AGREE. Always: check that every number the page prints comes from those
//      artifacts, that the arithmetic the prose performs on them is right, and
//      that the page's own internal consistency holds.
//
// Plus a set of standing invariants that would each catch a specific way this
// page could quietly become false.

import { readFileSync, existsSync, writeFileSync, mkdtempSync, rmSync } from 'fs';
import { execFileSync } from 'child_process';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { tmpdir } from 'os';

const HERE = dirname(fileURLToPath(import.meta.url));
const LAB = join(HERE, 'research', 'laughter-punctuation');
const PAGE = join(HERE, 'public', 'strata', 'nothing-funny-happened', 'index.html');
const RERUN = process.argv.includes('--rerun');

let pass = 0, fail = 0;
const bad = [];
function ok(name, cond, detail) {
  if (cond) { pass++; return true; }
  fail++; bad.push(`${name}${detail ? `  (${detail})` : ''}`);
  return false;
}
const near = (a, b, eps) => Math.abs(a - b) <= (eps === undefined ? 1e-9 : eps);

// ---------------------------------------------------------------------------
// Load
// ---------------------------------------------------------------------------
const read = (f) => JSON.parse(readFileSync(join(LAB, f), 'utf8'));
for (const f of ['artifact.json', 'parse-artifact.json', 'sbc-artifact.json',
                 'blindspot-artifact.json', 'acoustics-artifact.json', 'channel-artifact.json']) {
  ok(`artifact present: ${f}`, existsSync(join(LAB, f)));
}
const ami = read('artifact.json');
const parse = read('parse-artifact.json');
const sbc = read('sbc-artifact.json');
const blind = read('blindspot-artifact.json');
const ac = read('acoustics-artifact.json');
const chan = read('channel-artifact.json');

const html = readFileSync(PAGE, 'utf8');
const m = html.match(/<script type="application\/json" id="payload">([\s\S]*?)<\/script>/);
ok('page carries an embedded payload', !!m);
const P = m ? JSON.parse(m[1]) : {};

// ---------------------------------------------------------------------------
// 1. The page's payload matches the artifacts, field by field
// ---------------------------------------------------------------------------
ok('page laugh count = AMI artifact', P.ami.laughs === ami.corpus.laughs, `${P.ami?.laughs} vs ${ami.corpus.laughs}`);
ok('page interior count = artifact', P.ami.position.interior === ami.position.interior);
ok('page boundary count = artifact', P.ami.position.boundary === ami.position.interiorBoundary);
ok('page mid count = artifact', P.ami.position.mid === ami.position.interiorMid);
ok('page null rate = artifact', near(P.ami.position.nullRate, ami.position.null.exactExpectation));
ok('page speaker share = artifact', near(P.ami.who.share, ami.who.speakerShare));
ok('page rotation null = artifact', near(P.ami.who.rotMean, ami.who.rotationNull.rotatedMean));
ok('page parse ratio = artifact', near(P.parse.atLaugh, parse.crossingArcs.atTheLaugh));
ok('page SBC runs = artifact', P.sbc.runs === sbc.laughs.runs);
ok('page SBC pulses = artifact', P.sbc.pulses === sbc.laughs.pulses);
ok('page overlap count = artifact', P.blind.overlap === blind.overlapWithOwnSpeech.laughsOverlappingOwnWords);
ok('page AUC = artifact', near(P.acoustics.auc, ac.separability.auc));
ok('page channel margin = artifact', near(P.acoustics.channelMargin, chan.verdict.minPermutationMarginDb));

// ---------------------------------------------------------------------------
// 2. The arithmetic the page performs in prose
// ---------------------------------------------------------------------------
ok('interior = boundary + mid',
  ami.position.interior === ami.position.interiorBoundary + ami.position.interiorMid,
  `${ami.position.interior} vs ${ami.position.interiorBoundary}+${ami.position.interiorMid}`);
ok('positions sum to the laughs in a word-bearing utterance',
  ami.position.utteranceInitial + ami.position.utteranceFinal + ami.position.interior ===
  ami.position.inWordBearingUtterance);
ok('solo + in-utterance <= total laughs',
  ami.position.soloUtterance + ami.position.inWordBearingUtterance <= ami.position.laughsTotal);
ok('boundary rate = boundary / interior',
  near(ami.position.interiorBoundaryRate, ami.position.interiorBoundary / ami.position.interior, 5e-5));
ok('AMI interruption share = mid / all laughs',
  near(P.ami.position.interruptShare, ami.position.interiorMid / ami.position.laughsTotal, 5e-5));
ok('SBC interruption share = medial / runs',
  near(sbc.interruption.share, sbc.interruption.wordMedial / sbc.laughs.runs, 5e-5));
ok('speaker + listener = classified',
  ami.who.bySpeaker + ami.who.byListener === ami.who.classified);
ok('speaker share = speaker / classified',
  near(ami.who.speakerShare, ami.who.bySpeaker / ami.who.classified, 5e-5));

// The two-corpus convergence is the page's headline. Guard the claim itself:
// if a future rerun pulls them apart, the sentence "to within a fifth of a
// percentage point" must stop being printed.
const amiShare = ami.position.interiorMid / ami.position.laughsTotal;
const sbcShare = sbc.interruption.share;
ok('the two corpora still agree to within 0.5 percentage points',
  Math.abs(amiShare - sbcShare) < 0.005,
  `${(100 * amiShare).toFixed(2)}% vs ${(100 * sbcShare).toFixed(2)}%`);
ok('both are still far above the published 8/1200',
  amiShare > 5 * (8 / 1200) && sbcShare > 5 * (8 / 1200));
ok('the page says "a fifth of a percentage point" only while that is true',
  !/fifth of a percentage point/.test(html) || Math.abs(amiShare - sbcShare) <= 0.002,
  `gap is ${(100 * Math.abs(amiShare - sbcShare)).toFixed(3)} points`);

// ---------------------------------------------------------------------------
// 3. The results the page's argument rests on
// ---------------------------------------------------------------------------
ok('placement beats its own null',
  ami.position.interiorBoundaryRate > 2 * ami.position.null.exactExpectation);
ok('no null run reached the observed placement rate',
  ami.position.null.runsAtOrAboveObserved === 0);
ok('the parser, blind to punctuation, still finds a cleaner break at the laugh',
  parse.crossingArcs.atTheLaugh < parse.crossingArcs.meanOverAllInteriorPositions);
ok('the parser never saw the punctuation or the laugh',
  parse.parser.sawPunctuation === false && parse.parser.sawLaughter === false);
ok('no permutation of the parse test reached the observed mean',
  parse.null.runsAtOrBelowObserved === 0);
ok('even the phrase-splitting laughs sit at softer-than-average seams',
  parse.byTranscriberPunctuation.midPhraseByPunctuation.atTheLaugh <
  parse.byTranscriberPunctuation.midPhraseByPunctuation.utteranceMean);
ok('the floor-holder laughs more than the rotated null allows',
  ami.who.speakerShare > ami.who.rotationNull.rotatedMax);
ok('no rotation reached the observed speaker share',
  ami.who.rotationNull.runsAtOrAboveObserved === 0);
ok('the commonest word before a laugh is "yeah"',
  ami.lastWordBeforeALaugh.top[0].word === 'yeah',
  ami.lastWordBeforeALaugh.top[0].word);

// The blind spot. These are the numbers that make the page's central caveat
// true; if AMI is ever re-annotated they will move, and the caveat must move.
ok('almost no laugh overlaps its own speaker\'s words',
  blind.overlapWithOwnSpeech.laughsOverlappingOwnWords < 0.001 * blind.counts.usablyTimed,
  `${blind.overlapWithOwnSpeech.laughsOverlappingOwnWords} of ${blind.counts.usablyTimed}`);
ok('interior laughs are the untimed ones',
  blind.whichLaughsWentUntimed.interior.zeroDurationShare > 0.95,
  String(blind.whichLaughsWentUntimed.interior.zeroDurationShare));
ok('laughs in clear air are mostly timed',
  blind.whichLaughsWentUntimed.aloneInItsUtterance.zeroDurationShare < 0.2);
ok('the interior/alone contrast is the point',
  blind.whichLaughsWentUntimed.interior.zeroDurationShare >
  4 * blind.whichLaughsWentUntimed.aloneInItsUtterance.zeroDurationShare);

// Acoustics: the three claims, one confirmed and two not.
const REF = String(ac.method.referenceSmoothingMs);
const L = ac.bySmoothingMs[REF].laughter, S = ac.bySmoothingMs[REF].speech;
ok('laughter pulses roughly twice as fast as matched speech',
  L.periodMedianMs < 0.7 * S.periodMedianMs, `${L.periodMedianMs} vs ${S.periodMedianMs}`);
ok('that holds at every smoothing width tried',
  Object.values(ac.bySmoothingMs).every((v) => v.laughter.periodMedianMs < 0.7 * v.speech.periodMedianMs));
ok('periodicity barely separates laughter from speech',
  ac.separability.auc < 0.65, String(ac.separability.auc));
ok('speech falls in amplitude at least as often as laughter',
  S.fractionFalling >= L.fractionFalling, `${S.fractionFalling} vs ${L.fractionFalling}`);
ok('the acoustic run had a speech control of comparable size',
  ac.analysed.speech >= 0.8 * ac.analysed.laughter);
ok('the headset-to-speaker mapping was confirmed, not assumed',
  chan.verdict.allMeetingsMatchAlphabeticalOrder === true &&
  chan.verdict.minPermutationMarginDb > 3);

// SBC parse completeness.
ok('the SBC parse is reconciled against the raw files',
  sbc.reconciliation.pulsesRecoveredByTheParser >= 0.999 * sbc.reconciliation.rawPulseSymbolsInFiles,
  `${sbc.reconciliation.pulsesRecoveredByTheParser}/${sbc.reconciliation.rawPulseSymbolsInFiles}`);
ok('no SBC line went unparsed', sbc.reconciliation.unparsedLines === 0);
ok('laughter takes a prosodic unit to itself far more often than a word does',
  sbc.ownIntonationUnit.laughShare > 2 * sbc.ownIntonationUnit.wordShare);

// ---------------------------------------------------------------------------
// 4. The page's own honesty machinery
// ---------------------------------------------------------------------------
// No MEASURED quantity may appear in the prose as a literal. Published figures,
// dates, citations and spelled-out asides are fine and are meant to be there;
// what must never happen is a number that comes out of the corpora being typed
// by hand, because then a rerun moves the artifact and leaves the sentence
// behind. So: take the values the measurements produced, render them the way
// the page would, and insist none of them appear in the body text.
ok('no measured quantity is hard-coded in the prose', (function () {
  const body = html.replace(/<script[\s\S]*?<\/script>/g, ' ')
                   .replace(/<style[\s\S]*?<\/style>/g, ' ')
                   .replace(/<head[\s\S]*?<\/head>/g, ' ')
                   .replace(/<[^>]+>/g, ' ');
  const measured = [
    ami.corpus.laughs, ami.corpus.words, ami.corpus.hours,
    ami.position.laughsTotal, ami.position.soloUtterance, ami.position.inWordBearingUtterance,
    ami.position.interior, ami.position.interiorBoundary, ami.position.interiorMid,
    ami.who.bySpeaker, ami.who.byListener, ami.who.classified,
    parse.cases.scored, sbc.laughs.runs, sbc.laughs.pulses,
    blind.counts.usablyTimed, blind.counts.zeroDuration,
    ac.analysed.laughter, ac.analysed.speech,
    Number((100 * ami.position.interiorBoundaryRate).toFixed(1)),
    Number((100 * ami.position.null.exactExpectation).toFixed(1)),
    Number((100 * ami.who.speakerShare).toFixed(1)),
    ac.bySmoothingMs[REF].laughter.periodMedianMs,
    ac.bySmoothingMs[REF].speech.periodMedianMs,
  ];
  const hits = [];
  for (const v of measured) {
    if (v == null || Math.abs(v) < 10) continue;          // too small to be distinctive
    for (const form of [String(v), Number(v).toLocaleString('en-US')]) {
      const re = new RegExp('(^|[^\\d.,])' + form.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\d])');
      if (re.test(body)) hits.push(form);
    }
  }
  const uniq = [...new Set(hits)];
  if (uniq.length) bad.push(`  measured values typed into the prose: ${uniq.join(' ')}`);
  return uniq.length === 0;
})());
// The dek is the meta description and the homepage blurb, so it is the most
// widely read prose here, and it is the one place numbers are typed by hand
// (frontmatter cannot run the embed step). So check them against the artifacts.
ok('the dek\'s numbers match the artifacts', (function () {
  const md = join(HERE, 'src', 'content', 'strata', 'nothing-funny-happened.md');
  if (!existsSync(md)) return false;
  const dek = (readFileSync(md, 'utf8').match(/^dek:\s*"([\s\S]*?)"\s*$/m) || [])[1] || '';
  if (!dek) { bad.push('  no dek found'); return false; }
  // Every value the dek is allowed to state: whatever the measurements
  // currently say, plus the published figures it compares them against. The
  // dek need not mention all of them; it may not state one that is not here.
  const A = ac.bySmoothingMs[REF];
  const legal = new Set([
    ami.corpus.laughs, sbc.laughs.runs, ami.corpus.laughs + sbc.laughs.runs,
    ami.position.interior, ami.position.interiorMid, ami.position.laughsTotal,
    blind.counts.usablyTimed, blind.overlapWithOwnSpeech.laughsOverlappingOwnWords,
    blind.whichLaughsWentUntimed.interior.n, blind.whichLaughsWentUntimed.interior.zeroDuration,
    ami.corpus.hours, sbc.corpus.hours, ami.who.classified,
    Number((100 * (ami.position.interiorMid / ami.position.laughsTotal)).toFixed(2)),
    Number((100 * sbc.interruption.share).toFixed(2)),
    Number((100 * ami.position.interiorBoundaryRate).toFixed(1)),
    Number((100 * ami.position.null.exactExpectation).toFixed(1)),
    Number((100 * ami.who.speakerShare).toFixed(1)),
    A.laughter.periodMedianMs, A.speech.periodMedianMs,
    Number((100 * A.laughter.fractionFalling).toFixed(1)),
    Number((100 * A.speech.fractionFalling).toFixed(1)),
    ac.separability.auc, parse.crossingArcs.atTheLaugh, parse.crossingArcs.meanOverAllInteriorPositions,
    ami.who.perPersonRateRatio,
    // published figures the dek is comparing against
    1200, 8, 0.67, 46, 210, 218, 120, 75, 1024, 97, 2.7,
  ].map(Number));
  const stated = [...dek.matchAll(/\d[\d,]*(?:\.\d+)?/g)].map((x) => Number(x[0].replace(/,/g, '')));
  const wrong = stated.filter((v) => !legal.has(v));
  if (wrong.length) bad.push(`  dek states values no measurement produces: ${[...new Set(wrong)].join(' ')}`);
  return wrong.length === 0;
})());

ok('the page carries a caveat section', /What this does not show/.test(html));
ok('the page names the corpora and their licences',
  /CC BY 4\.0/.test(html) && /CC BY-ND 3\.0 US/.test(html));
ok('the page names the paywalled source it could not read',
  /Bachorowski[\s\S]{0,400}paywalled/.test(html) || /paywalled[\s\S]{0,400}Bachorowski/.test(html));
ok('the page states the interruption figure is a floor',
  /floor, not an estimate/.test(html));
ok('audio clips referenced by the page exist on disk',
  P.clips.every((c) => existsSync(join(dirname(PAGE), c.file))),
  P.clips.filter((c) => !existsSync(join(dirname(PAGE), c.file))).map((c) => c.file).join(' '));
ok('the closing tags are present',
  /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html.trimEnd() + '\n'));

// The inline script must actually parse; a syntax error there silently
// disables the whole page and the build will not catch it.
ok('the page\'s inline script parses', (function () {
  const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((x) => x[1]);
  if (!scripts.length) return false;
  const dir = mkdtempSync(join(tmpdir(), 'nfh-'));
  try {
    for (let i = 0; i < scripts.length; i++) {
      const f = join(dir, `s${i}.js`);
      writeFileSync(f, scripts[i]);
      execFileSync(process.execPath, ['--check', f], { stdio: 'pipe' });
    }
    return true;
  } catch (e) {
    bad.push(`  node --check: ${String(e.stderr || e).slice(0, 300)}`);
    return false;
  } finally {
    rmSync(dir, { recursive: true, force: true });
  }
})());

// Every data-k the prose asks for must be one the script can answer.
ok('every data-k in the page is served by the script', (function () {
  const keys = [...html.matchAll(/data-k="([^"]+)"/g)].map((x) => x[1]);
  const script = html.match(/var V = \{([\s\S]*?)\n  \};/);
  if (!script) return false;
  const served = new Set([...script[1].matchAll(/'([^']+)':/g)].map((x) => x[1]));
  const missing = [...new Set(keys)].filter((k) => !served.has(k));
  if (missing.length) bad.push(`  unserved data-k: ${missing.join(' ')}`);
  return missing.length === 0;
})());

// ---------------------------------------------------------------------------
// 5. Optional: re-derive everything from the corpora
// ---------------------------------------------------------------------------
if (RERUN) {
  const amiDir = join(HERE, 'research', 'turn-taking-gap', '_data', 'ami', 'words');
  if (!existsSync(amiDir)) {
    console.log('\n--rerun: corpora not downloaded. node research/turn-taking-gap/fetch.mjs');
  } else {
    const before = {
      ami: readFileSync(join(LAB, 'artifact.json'), 'utf8'),
      sbc: readFileSync(join(LAB, 'sbc-artifact.json'), 'utf8'),
      blind: readFileSync(join(LAB, 'blindspot-artifact.json'), 'utf8'),
    };
    for (const s of ['measure.mjs', 'sbc.mjs', 'blindspot.mjs']) {
      execFileSync(process.execPath, [join(LAB, s)], { stdio: 'pipe' });
    }
    ok('measure.mjs reproduces its committed artifact',
      readFileSync(join(LAB, 'artifact.json'), 'utf8') === before.ami);
    ok('sbc.mjs reproduces its committed artifact',
      readFileSync(join(LAB, 'sbc-artifact.json'), 'utf8') === before.sbc);
    ok('blindspot.mjs reproduces its committed artifact',
      readFileSync(join(LAB, 'blindspot-artifact.json'), 'utf8') === before.blind);
  }
}

// ---------------------------------------------------------------------------
console.log(`\nnothing-funny-happened: ${pass} passed, ${fail} failed` +
            (RERUN ? '' : '   (add --rerun to re-derive from the corpora)'));
if (fail) {
  console.log('\nfailures:');
  for (const b of bad) console.log(`  ${b}`);
  process.exit(1);
}
console.log('\nheadline numbers, recomputed from the artifacts:');
console.log(`  laughs that split a phrase:  AMI ${(100 * amiShare).toFixed(2)}%  ` +
            `SBC ${(100 * sbcShare).toFixed(2)}%  published 0.67%`);
console.log(`  placement at a boundary:     ${(100 * ami.position.interiorBoundaryRate).toFixed(1)}% ` +
            `against a null of ${(100 * ami.position.null.exactExpectation).toFixed(1)}%`);
console.log(`  arcs crossing the laugh:     ${parse.crossingArcs.atTheLaugh} against ` +
            `${parse.crossingArcs.meanOverAllInteriorPositions} elsewhere in the same sentence`);
console.log(`  the floor-holder's share:    ${(100 * ami.who.speakerShare).toFixed(1)}% ` +
            `against a rotated null of ${(100 * ami.who.rotationNull.rotatedMean).toFixed(1)}%`);
console.log(`  laugh vs speech period:      ${L.periodMedianMs} ms against ${S.periodMedianMs} ms`);
console.log(`  laughs overlapping own words: ${blind.overlapWithOwnSpeech.laughsOverlappingOwnWords} ` +
            `of ${blind.counts.usablyTimed}`);
