// verify-you-were-already-answering.mjs — drive the immersive "You Were Already
// Answering" page in a real headless browser and confirm it is honest end to end:
//
//   • the measured payload the page ships is EXACTLY what measure.mjs produced,
//     re-derived here from artifact.json rather than trusted;
//   • if the corpora are present locally, measure.mjs is re-run from the raw
//     annotations and every headline number must come back identical;
//   • every number printed into the page's prose matches the artifact;
//   • the histogram is internally consistent (bins sum to n) and the page's own
//     cumulative function agrees with an independent recomputation at 21 points;
//   • the inference the page makes about the reader (a press that beat their own
//     reaction floor was not a reaction) is exercised directly on the page's own
//     scoring function with constructed cases, including the ones that must NOT
//     count as evidence;
//   • the projection test actually runs: trials advance, presses are recorded,
//     and a full run produces a results table;
//   • no JS errors, canvases paint, and no horizontal overflow at 390/768/1440.
//
//   npm run build && node verify-you-were-already-answering.mjs
import pw from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pw;
import { createServer } from 'http';
import { readFileSync, existsSync } from 'fs';
import { extname, join } from 'path';
import { execFileSync } from 'child_process';
import { payload, readArtifact } from './research/turn-taking-gap/embed.mjs';

const ROOT = '/home/user/Artificial-Wasteland';
const dist = join(ROOT, 'dist');
const types = { '.html':'text/html','.css':'text/css','.js':'text/javascript','.woff2':'font/woff2','.png':'image/png','.svg':'image/svg+xml','.ico':'image/x-icon','.xml':'application/xml','.txt':'text/plain','.json':'application/json','.webp':'image/webp','.jpg':'image/jpeg' };
const server = createServer((req,res)=>{ let p=decodeURIComponent(req.url.split('?')[0]); if(p.endsWith('/'))p+='index.html'; const fp=join(dist,p);
  try{ const buf=readFileSync(fp); res.writeHead(200,{'content-type':types[extname(fp)]||'application/octet-stream'}); res.end(buf); }
  catch{ res.writeHead(404); res.end('404'); } });
await new Promise(r=>server.listen(8194,r));
const URL_='http://localhost:8194/strata/you-were-already-answering/';

let fails=0, checks=0;
const ok=(n,c,x='')=>{ checks++; if(!c)fails++; console.log(`${c?'  ok':'FAIL'}  ${n}${x?'   '+x:''}`); };
const near=(a,b,t)=>Math.abs(a-b)<=t;

// ───────────────────────────────────────────── 1. the artifact is the source ──
console.log('\n— the measured payload —');
const art = readArtifact();
const want = payload(art);

// ─────────────────────────── 2. re-run the measurement from the raw corpus ────
const DATA = join(ROOT, 'research/turn-taking-gap/_data/ami/segments');
if (existsSync(DATA)) {
  console.log('  (corpora present: re-running measure.mjs from the raw annotations)');
  execFileSync('node', [join(ROOT,'research/turn-taking-gap/measure.mjs')], { stdio:'pipe' });
  const again = readArtifact();
  for (const k of ['n','medianMs','modeMs','meanMs','p25Ms','p75Ms']) {
    ok(`measurement reproduces from source: headline.${k}`, again.headline[k]===art.headline[k],
       `${again.headline[k]} vs ${art.headline[k]}`);
  }
  ok('measurement reproduces from source: overlap fraction',
     near(again.headline.overlapFrac, art.headline.overlapFrac, 1e-12));
  ok('measurement reproduces from source: histogram identical',
     JSON.stringify(again.histogram)===JSON.stringify(art.histogram));
} else {
  console.log('  (corpora absent — skipping the from-source rerun; run research/turn-taking-gap/fetch.mjs)');
}

// ─────────────────────────────────────── 3. internal consistency of the data ──
console.log('\n— the distribution is internally consistent —');
const h = art.histogram;
const binSum = h.counts.reduce((a,b)=>a+b,0) + h.under + h.over;
ok('histogram bins account for every floor transfer', binSum===art.headline.n, `${binSum} vs ${art.headline.n}`);
ok('histogram covers -2s..+3s in 50ms bins', h.counts.length===100 && h.binSec===0.05 && h.loSec===-2 && h.hiSec===3);
const modeBin = h.counts.indexOf(Math.max(...h.counts));
const modeFromHist = Math.round((h.loSec + (modeBin+0.5)*h.binSec)*1000);
ok('reported mode is the peak of the reported histogram', modeFromHist===art.headline.modeMs,
   `${modeFromHist} vs ${art.headline.modeMs}`);
ok('overlap fraction equals the mass left of zero',
   near(art.headline.overlapFrac, art.headline.underMs['0'], 1e-9));
ok('median lies between p25 and p75', art.headline.p25Ms < art.headline.medianMs && art.headline.medianMs < art.headline.p75Ms);
// the sweep is the honesty claim about the one free parameter
const meds = art.sweep.map(s=>s.medianMs);
const spread = Math.max(...meds)-Math.min(...meds);
ok('the free parameter moves the median by under 50 ms across a 20x sweep', spread<50, `${spread} ms`);
ok('the free parameter moves the overlap rate by under 1 point',
   Math.max(...art.sweep.map(s=>s.overlapFrac))-Math.min(...art.sweep.map(s=>s.overlapFrac)) < 0.01);
// the claim that most transfers beat the one-word budget
ok('the load-bearing claim: a large majority finish inside 600 ms',
   art.headline.underMs['600'] > 0.75, (art.headline.underMs['600']*100).toFixed(1)+'%');
ok('underMs is monotone in the threshold',
   Object.entries(art.headline.underMs).sort((a,b)=>a[0]-b[0]).every(([,v],i,arr)=>i===0||v>=arr[i-1][1]));

// ─────────────────────────────────────────────────────── 4. the live page ────
console.log('\n— the live page —');
const browser = await chromium.launch();
const page = await browser.newPage({ viewport:{ width:390, height:900 } });
const errs=[]; page.on('pageerror',e=>errs.push(String(e))); page.on('console',m=>{ if(m.type()==='error') errs.push(m.text()); });
const reqs=[]; page.on('request',r=>{ const u=r.url(); if(!u.startsWith('http://localhost:8194')&&!u.startsWith('data:')) reqs.push(u); });
await page.goto(URL_, { waitUntil:'networkidle' });

ok('no JS errors on load', errs.length===0, errs.join(' | '));
ok('no third-party network requests', reqs.length===0, reqs.join(' | '));

// the page ships exactly the artifact
const shipped = await page.evaluate(()=>window.__turn && window.__turn.data);
ok('page carries a measured payload', !!shipped);
ok('shipped payload is byte-identical to the artifact-derived payload',
   JSON.stringify(shipped)===JSON.stringify(want));

// numbers printed into the prose
const dom = await page.evaluate(()=>{
  const t=id=>{ const e=document.getElementById(id); return e?e.textContent.trim():null; };
  return { hours:t('c-hours'), meetings:t('c-meetings'), chan:t('c-chan'),
           median:t('c-median'), mode:t('c-mode'), mean:t('c-mean'), n:t('c-n'),
           under600:t('c-under600'), overlap:t('c-overlap'), sweep:t('c-sweep'),
           dmed:t('c-ctl-dmed'), dmode:t('c-ctl-dmode'), cap:document.getElementById('lanescap').textContent };
});
const fmt=v=>(v>0?'+':'')+v+' ms';
ok('prose median matches artifact', dom.median===fmt(art.headline.medianMs), dom.median);
ok('prose mode matches artifact', dom.mode===fmt(art.headline.modeMs), dom.mode);
ok('prose mean matches artifact', dom.mean===fmt(art.headline.meanMs), dom.mean);
ok('prose n matches artifact', dom.n===art.headline.n.toLocaleString('en-US'), dom.n);
ok('prose meetings/channels match artifact',
   dom.meetings===String(art.corpus.meetings) && dom.chan===String(art.corpus.speakerChannels));
ok('prose "inside 600 ms" matches artifact',
   dom.under600===(art.headline.underMs['600']*100).toFixed(1)+'%', dom.under600);
ok('prose overlap rate matches artifact',
   dom.overlap===(art.headline.overlapFrac*100).toFixed(1)+'%', dom.overlap);
ok('prose sweep spread matches artifact', dom.sweep===spread+' ms', dom.sweep);
ok('control delta matches artifact',
   dom.dmed===Math.abs(art.wordTimingsControl.medianMs-art.headline.medianMs)+' ms', dom.dmed);
ok('figure caption states the real modal offset',
   dom.cap.includes(String(Math.abs(art.headline.modeMs))) &&
   dom.cap.includes(art.headline.modeMs<0?'before':'after'), dom.cap.slice(0,90));

// the cumulative function the reader drags, checked against an independent recompute
const pts = Array.from({length:21},(_,i)=>-2000+i*250);
const pageF = await page.evaluate(ts=>ts.map(t=>window.__turn.fractionUnder(t)), pts);
function refFraction(ms){
  const s=ms/1000; let n=h.under;
  for(let i=0;i<h.counts.length;i++){
    const lo=h.loSec+i*h.binSec, hi=lo+h.binSec;
    if(hi<=s) n+=h.counts[i];
    else if(lo<s) n+=h.counts[i]*(s-lo)/h.binSec;
  }
  return Math.min(1,n/art.headline.n);
}
let cumOk=true, worst=0;
pts.forEach((t,i)=>{ const d=Math.abs(pageF[i]-refFraction(t)); worst=Math.max(worst,d); if(d>1e-9) cumOk=false; });
ok('the draggable cumulative agrees with an independent recompute at 21 points', cumOk, 'max diff '+worst.toExponential(2));
ok('cumulative is monotone non-decreasing', pageF.every((v,i)=>i===0||v>=pageF[i-1]-1e-12));
ok('cumulative at +3s accounts for all but the far tail',
   near(pageF[pts.length-1], 1-h.over/art.headline.n, 1e-9));

// ───────────────────────────── 5. the inference the page makes about YOU ─────
console.log('\n— the reader-facing inference —');
// Construct runs by hand and check the page's own scorer draws the right conclusion.
const scored = await page.evaluate(()=>{
  const S = window.__turn.scoreRun;
  return {
    // floor 300ms; two word-presses launched 120ms after the last word (impossible
    // as a reaction) AND landing on target, two launched 500ms after (consistent
    // with reacting), plus one wild early mash that is fast but nowhere near the end
    clear: S([
      {kind:'react',rt:290},{kind:'react',rt:300},{kind:'react',rt:310},
      {kind:'words',off:10,sinceLast:120},{kind:'words',off:-30,sinceLast:150},
      {kind:'words',off:60,sinceLast:500},{kind:'words',off:80,sinceLast:520},
      {kind:'words',off:-1400,sinceLast:-1100},
      {kind:'blocks',off:400,sinceLast:900},{kind:'blocks',off:-350,sinceLast:800},
    ]),
    // every press slower than the floor: nothing is proven
    none: S([
      {kind:'react',rt:200},{kind:'react',rt:200},{kind:'react',rt:200},
      {kind:'words',off:10,sinceLast:400},{kind:'words',off:20,sinceLast:450},
    ]),
    // no usable reaction trials: the floor is unknown, so nothing may be claimed
    nofloor: S([
      {kind:'react',missed:true},{kind:'react',missed:true},{kind:'react',missed:true},
      {kind:'words',off:0,sinceLast:10},{kind:'words',off:0,sinceLast:10},
    ]),
    // missed trials must not be counted as data
    missed: S([
      {kind:'react',rt:300},
      {kind:'words',off:0,sinceLast:100},{kind:'words',missed:true},
    ]),
  };
});
ok('floor is the median of the reaction trials', scored.clear.floor===300, String(scored.clear.floor));
ok('counts exactly the presses that beat the reader\'s own floor', scored.clear.rows[0].early===2,
   String(scored.clear.rows[0].early));
ok('does not count presses slower than the floor as evidence', scored.none.rows[0].early===0,
   String(scored.none.rows[0].early));
ok('claims nothing when the floor could not be measured',
   !Number.isFinite(scored.nofloor.floor) && scored.nofloor.rows[0].early===0);
ok('missed trials are excluded from n', scored.missed.rows[0].n===1, String(scored.missed.rows[0].n));
ok('a fast press nowhere near the ending is not counted as evidence',
   scored.clear.rows[0].n===5 && scored.clear.rows[0].early===2,
   `n=${scored.clear.rows[0].n} early=${scored.clear.rows[0].early}`);
// an impossibly fast "reaction" must be discarded rather than believed
const guard = await page.evaluate(()=>window.__turn.scoreRun([
  {kind:'react',rt:80},{kind:'react',rt:290},{kind:'react',rt:300},
  {kind:'words',off:0,sinceLast:150},
]));
const rtGuard = await page.evaluate(()=>({
  min: window.__turn.MIN_RT,
  onTarget: window.__turn.ON_TARGET,
  verdicts: [-50, 0, 40, 99, 100, 250, 900].map(window.__turn.acceptRT),
}));
ok('an impossibly fast reaction is rejected at capture, not believed',
   rtGuard.min===100 && JSON.stringify(rtGuard.verdicts)===JSON.stringify([false,false,false,false,true,true,true]),
   JSON.stringify(rtGuard.verdicts));
ok('the on-target window is stated and finite', rtGuard.onTarget===400, String(rtGuard.onTarget));
ok('floor is unaffected by the trials that were discarded at capture',
   guard.floor===290, String(guard.floor));

// the test's own timing must make the inference possible at all: the final word
// has to be short enough that a typical reaction floor cannot cover it
const wordTiming = await page.evaluate(()=>{
  const w=window.__turn;
  return w.sentences.map(s=>{ const p=s.split(' '); return { last:p[p.length-1], ms:w.wordMs(p[p.length-1]),
    total:p.reduce((a,x)=>a+w.wordMs(x),0), n:p.length }; });
});
ok('every test sentence ends on a word shorter than a typical 300 ms reaction floor',
   wordTiming.every(w=>w.ms<300), wordTiming.map(w=>`${w.last}:${w.ms}`).join(' '));
const rates = wordTiming.map(w=>w.n/(w.total/1000)*60);
ok('sentences run at a brisk conversational rate (150-260 wpm)',
   rates.every(r=>r>150&&r<260), rates.map(r=>r.toFixed(0)).join(' '));

// ──────────────────────────────────────────── 6. the instrument really runs ──
console.log('\n— the instrument runs —');
ok('projection test present', await page.$('#stage')!==null && await page.$('#go')!==null);
ok('distribution canvas present', await page.$('#dist')!==null);
ok('pause instrument present', await page.$('#pause')!==null);

await page.click('#go');
await page.waitForTimeout(300);
const started = await page.evaluate(()=>document.getElementById('progress').textContent);
ok('trials begin and are numbered', /Trial 1 of \d+/.test(started), started);

// run the whole thing by pressing space on a loop until it finishes
for (let i=0;i<400;i++){
  const done = await page.evaluate(()=>document.getElementById('progress').textContent==='Done');
  if (done) break;
  await page.keyboard.press('Space');
  await page.waitForTimeout(120);
}
const finished = await page.evaluate(()=>({
  prog: document.getElementById('progress').textContent,
  shown: !document.getElementById('results').hidden,
  rows: document.querySelectorAll('#restable tbody tr').length,
  verdict: document.getElementById('verdict').textContent.trim().length,
}));
ok('a full run completes', finished.prog==='Done', finished.prog);
ok('results table is revealed with three rows', finished.shown && finished.rows===3, String(finished.rows));
ok('a verdict is written', finished.verdict>80, String(finished.verdict));

// canvases actually painted
const painted = await page.evaluate(()=>{
  const out={};
  for (const id of ['lanes','dist','pausebar']){
    const c=document.getElementById(id); const g=c.getContext('2d');
    const d=g.getImageData(0,0,c.width,c.height).data; let lit=0;
    for(let i=0;i<d.length;i+=4){ if(d[i+3]>8 && d[i]+d[i+1]+d[i+2]>30){ lit++; if(lit>60) break; } }
    out[id]=lit>60;
  }
  return out;
});
ok('lanes figure paints', painted.lanes);
ok('distribution paints', painted.dist);
ok('pause figure paints', painted.pausebar);

// dragging the threshold changes the readout
await page.evaluate(()=>{ const c=document.getElementById('cut'); c.value='-1000'; c.dispatchEvent(new Event('input')); });
const lo = await page.evaluate(()=>document.getElementById('distout').textContent);
await page.evaluate(()=>{ const c=document.getElementById('cut'); c.value='2000'; c.dispatchEvent(new Event('input')); });
const hi = await page.evaluate(()=>document.getElementById('distout').textContent);
ok('the threshold readout responds and increases with the threshold',
   lo!==hi && parseFloat(lo)<parseFloat(hi), `${parseFloat(lo)}% -> ${parseFloat(hi)}%`);

// the pause instrument names its source at every stop
const pauseTexts = await page.evaluate(()=>{
  const s=document.getElementById('pause'), out=[];
  for (const v of [0,200,500,800,1400]){ s.value=String(v); s.dispatchEvent(new Event('input'));
    out.push(document.getElementById('pauseout').textContent); }
  return out;
});
ok('the pause readout changes across its range', new Set(pauseTexts).size===5);
// the 0 ms stop makes no published claim, so it is exempt; every other one must cite
const cited = pauseTexts.slice(1);
ok('every published claim in the pause readout names its source',
   cited.every(t=>/\(20\d\d\)|et al\./.test(t)),
   cited.filter(t=>!/\(20\d\d\)|et al\./.test(t)).length+' unattributed of '+cited.length);

// ─────────────────────────────────────────────── 7. honesty of the apparatus ─
console.log('\n— the apparatus —');
const body = await page.evaluate(()=>document.body.innerText);
ok('names the corpus and its licence', /AMI Meeting Corpus/.test(body) && /CC BY 4\.0/.test(body));
ok('states the meetings-not-dyads caveat', /four-person meetings/.test(body) && /dyadic/.test(body));
ok('reports the corpus it had to discard', /Santa Barbara/.test(body) && /0\.000 seconds/.test(body));
ok('separates measured-here from cited', /Measured here/i.test(body) && /Taken from published work/i.test(body));
ok('says the reader\'s own data is not transmitted', /never sent anywhere|Nothing was sent anywhere/.test(body));
ok('does not overclaim from the reader\'s tiny sample',
   /a demonstration, not an experiment/.test(body));
// scoped to <main>: the shared site banner carries one in an aria-label and is
// not this page's prose (nor this claim's to change)
const emdash = await page.evaluate(()=>(document.querySelector('main').innerHTML.match(/—/g)||[]).length);
ok('no em dashes in this page\'s own prose', emdash===0, String(emdash));

// ───────────────────────────────────────────────────────── 8. no overflow ────
console.log('\n— layout —');
for (const w of [390,768,1440]){
  await page.setViewportSize({ width:w, height:900 });
  await page.waitForTimeout(220);
  const over = await page.evaluate(()=>document.documentElement.scrollWidth-document.documentElement.clientWidth);
  ok(`no horizontal overflow at ${w}px`, over<=0, `overflow ${over}px`);
}

await browser.close(); server.close();
console.log(`\n${fails? 'FAILED' : 'ALL GREEN'} — ${checks-fails}/${checks} checks passed`);
process.exit(fails?1:0);
