#!/usr/bin/env node
// research/nothing-on-this-page-is-too-wide/verify.mjs
//
//   node research/nothing-on-this-page-is-too-wide/verify.mjs
//   node research/nothing-on-this-page-is-too-wide/verify.mjs --faults   # plant 12 faults, all must go red
//
// THREE KINDS OF CHECK, in ascending order of how much they are worth.
//
//   A. THE PAGE AGAINST ITS OWN DATA. Every number the shipped HTML prints is read out of
//      the bytes it serves and compared to the census JSON. This can catch the page and
//      the lab disagreeing, which is the failure that actually happens.
//   B. THE GUARD AGAINST ITS DESCRIPTION. The page says what public/media/home-banner.js
//      does; the file is read and held to it.
//   C. THE CENTRAL CLAIM, RE-DERIVED IN A BROWSER FROM SCRATCH. The page's argument is
//      that a bounding-rect sweep can report "nothing is too wide" on a page that
//      genuinely scrolls sideways. That does not rest on our corpus at all, so it is
//      proved here on specimens built for the purpose, by running BOTH detectors and
//      showing they disagree. This is the check that would still stand if every number
//      on the page were wrong.
//
// The browser half is skipped (loudly, not silently) where playwright is absent; the
// arithmetic half always runs.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadChromium, launchBrowser, serveDir, measure } from '../../scripts/mobile-overflow-lib.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const SLUG = 'nothing-on-this-page-is-too-wide';
const FAULTS = process.argv.includes('--faults');

const J = (f) => JSON.parse(fs.readFileSync(path.join(HERE, f), 'utf8'));
const facts = J('facts.json');
const before = J('census-before.json');
const after = J('census-after.json');
const baseline = J('baseline.json');
const PAGE = path.join(ROOT, 'public/strata', SLUG, 'index.html');
const html = fs.existsSync(PAGE) ? fs.readFileSync(PAGE, 'utf8') : '';
const banner = fs.readFileSync(path.join(ROOT, 'public/media/home-banner.js'), 'utf8');
const globalCss = fs.readFileSync(path.join(ROOT, 'src/styles/global.css'), 'utf8');

let pass = 0; const failures = [];
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { failures.push(name); console.log(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
};
// The page must print each figure IN THE PLACE IT MAKES THE CLAIM. An earlier version of
// this file searched the whole HTML for the bare number, and a mutation test caught it
// dead: changing the "recipe finds nothing" count from 11 to 12 left every check green,
// because the two characters "11" occur all over a stylesheet. A check that a planted
// defect walks straight past is not a check. So every assertion below is anchored to the
// element or sentence that carries the claim.
const says = (frag) => html.includes(frag);
const ov = (r) => (r.overflow ?? 0);
const overSet = (c) => new Set(c.results.filter((r) => ov(r) > 2).map((r) => r.path));

console.log(`\n${SLUG} — verifier\n`);

// ── A. the census, and the page against it ───────────────────────────────────
console.log('A. the corpus measurement, and the page against it');
const B = overSet(before), A = overSet(after);
ok('census measured 1,032 pages', before.summary.measured === facts.pagesMeasured && facts.pagesMeasured === 1032,
   `${before.summary.measured}`);
ok('before: 38 pages wider than a 390px viewport', B.size === 38 && facts.beforeOver === 38, `${B.size}`);
ok('before: 29 scrollable + 9 clipped = 38', before.summary.scrollable === 29 && before.summary.clippedOff === 9
   && before.summary.scrollable + before.summary.clippedOff === B.size);
ok('after: 15 remain', A.size === 15 && facts.afterOver === 15, `${A.size}`);
ok('after: 13 scrollable + 2 clipped = 15', after.summary.scrollable === 13 && after.summary.clippedOff === 2
   && after.summary.scrollable + after.summary.clippedOff === A.size);
ok('23 fixed and 0 newly broken', [...B].filter((p) => !A.has(p)).length === 23 && [...A].filter((p) => !B.has(p)).length === 0);
ok('total overflow 3,730px -> 1,449px',
   [...B].reduce((s, p) => s + ov(before.results.find((r) => r.path === p)), 0) === 3730
   && [...A].reduce((s, p) => s + ov(after.results.find((r) => r.path === p)), 0) === 1449);
ok('36 of the 38 were standalone pages', facts.standaloneOfBefore === 36);
ok('the two that were not are /archive/ and /terminal/',
   ['/archive/', '/terminal/'].every((p) => B.has(p)));
ok('37 of 38 fully attributed, residual zero',
   before.summary.overflowing - before.summary.unexplained === 37 && facts.attributedBefore === 37);
ok('the two scroll readings never disagreed, on either run',
   before.summary.scrollDisagreements.length === 0 && after.summary.scrollDisagreements.length === 0);
ok('the page says 1,032 pages, in the sentence that claims it', says('<b>1,032 pages</b>'));
ok('the page says 38 were wider than the phone', says('<b>38 pages were wider than the phone'));
ok('the before/after table carries 38 -> 15', says('<td>pages wider than a 390px viewport</td><td class="n">38</td><td class="n">15</td>'.replace(/></g, '></')) || /pages wider than a 390px viewport<\/td>\s*<td class="n">38<\/td>\s*<td class="n">15<\/td>/.test(html));
ok('...and 29 -> 13, and 9 -> 2',
   /the reader can scroll<\/td>\s*<td class="n">29<\/td>\s*<td class="n">13<\/td>/.test(html)
   && /content clipped off<\/td>\s*<td class="n">9<\/td>\s*<td class="n">2<\/td>/.test(html));
ok('...and the total, 3,730px to 1,449px',
   /total overflow across the corpus<\/td>\s*<td class="n">3,730px<\/td>\s*<td class="n">1,449px<\/td>/.test(html));
ok('the page says 23 fixed and none broken', says('<b>23 pages fixed, none broken.</b>'));
ok('the split 29 scrollable / 9 clipped is in the first table',
   /scrolls sideways[^<]*<\/td><td class="n">29<\/td>/.test(html.replace(/\s+/g, ' '))
   && /unreachable<\/td><td class="n">9<\/td>/.test(html.replace(/\s+/g, ' ')));

// ── the claim about the standard recipe, counted on the corpus ───────────────
console.log('\n   the rect sweep, counted');
const rectNothing = [...B].filter((p) => (before.results.find((r) => r.path === p).widestRectRight ?? 0) <= 392);
const rectUnder = [...B].filter((p) => {
  const r = before.results.find((x) => x.path === p);
  return (r.widestRectRight ?? 0) < 390 + ov(r) - 2;
});
ok('on 11 of 38, the widest unclipped element FITS the viewport', rectNothing.length === 11 && facts.rectFindsNothing === 11,
   `${rectNothing.length}`);
ok('on 14 of 38, the widest rect under-reads the document width', rectUnder.length === 14 && facts.rectUnderReads === 14,
   `${rectUnder.length}`);
ok('the page prints 11, in the row that claims the recipe finds nothing',
   /the recipe finds nothing at all<\/td><td class="n">11<\/td>/.test(html.replace(/\s+/g, ' ')));
ok('the page prints 14, in the row about under-reading',
   /under-reads<\/b> the document's real width<\/td><td class="n">14<\/td>/.test(html.replace(/\s+/g, ' ')));
ok('the page prints 37 attributed, in its own row',
   /residual zero<\/td><td class="n">37<\/td>/.test(html.replace(/\s+/g, ' ')));

// ── the worked page, whose 115px stalled an earlier diagnosis ────────────────
console.log('\n   the detector page, the one an earlier pass could not account for');
const det = before.results.find((r) => r.path === '/strata/what-the-detector-could-not-record/');
ok('measured 111px over', ov(det) === 111 && facts.detectorTotal === 111);
ok('its widest unclipped rect is 403, well short of 501', det.widestRectRight === 403);
ok('the top cause is p#provenance.foot', det.causes[0].sel.endsWith('p#provenance.foot'));
ok('...whose content is 483px inside a 353px box', det.causes[0].scrollWidth === 483 && det.causes[0].clientWidth === 353);
ok('...a 64-character hash with overflow-wrap:normal',
   /^[0-9a-f]{64}/.test(det.causes[0].longestToken) && det.causes[0].overflowWrap === 'normal');
ok('the account is complete: residual 0', det.residual === 0 && det.explained === true);
ok('the guard cut it from 111px to 13px',
   ov(after.results.find((r) => r.path === '/strata/what-the-detector-could-not-record/')) === 13);

// ── B. the guard, against what the page says it does ────────────────────────
console.log('\nB. the guard in public/media/home-banner.js');
ok('injects a style with id aw-narrow-guard', banner.includes("guard.id = 'aw-narrow-guard'"));
ok('scoped to max-width:44rem', banner.includes('@media(max-width:44rem)'));
ok('breaks long words: html{overflow-wrap:break-word}', banner.includes('html{overflow-wrap:break-word;}'));
ok('form controls capped at ZERO specificity, so the author always wins',
   banner.includes(':where(select,input,textarea,button){max-width:100%;}'));
// scan ONLY the CSS the guard actually injects. Scanning the whole file matched the
// comment that quotes the blanket rule in order to explain why it was rejected, which is
// a check reading prose about the code instead of the code.
const guardCss = banner.slice(banner.indexOf("guard.textContent"),
                             banner.indexOf("(document.head || document.documentElement).appendChild(guard)"));
ok('the table rule applies only to a class the measured pass hands out',
   guardCss.includes('table.aw-scrolls{display:block;overflow-x:auto;max-width:100%;}')
   && !/(^|[^.\w])table\{display:block/.test(guardCss));
ok('the pass returns early when the document already fits',
   banner.includes('if (de.scrollWidth <= de.clientWidth + 2) return;'));
ok('it compares a table to its PARENT, not to the viewport',
   banner.includes('t.getBoundingClientRect().width > room + 2'));
ok('it leaves alone a table the author already put in a scroller',
   banner.includes("indexOf(getComputedStyle(host).overflowX) !== -1) tooWide = false"));
ok('the guard touches no image, video or canvas', !/\b(img|video|canvas|iframe)\b/.test(guardCss));
ok('a page can opt out with data-aw-guard="off"', banner.includes("getAttribute('data-aw-guard') !== 'off'"));
ok('the wrapped half really does carry the rules the guard mirrors',
   /overflow-x:\s*hidden/.test(globalCss) && /\.prose table\s*\{[^}]*display:\s*block/.test(globalCss.replace(/\s+/g, ' ')));
ok('...and really does ship the nowrap hazard beside them',
   /\.prose td:first-child\s*\{[^}]*white-space:\s*nowrap/.test(globalCss.replace(/\s+/g, ' ')));

// ── the collateral-damage control ───────────────────────────────────────────
console.log('\n   the damage sweep, and its control');
ok('36 pages changed height; 10 of them fail a same-code repeat',
   facts.heightFlagged === 36 && facts.heightNoise === 10 && facts.heightGenuine === 26);
ok('the real changes top out at 150px, 2.50% of a page',
   facts.heightMaxPx === 150 && facts.heightMaxPct === 2.5);
ok('the page prints the noise control where it makes the claim',
   says('<b>36 pages changed height.</b>') && says('<b>10 of those 36 do not survive it.</b>')
   && says('The <b>26</b> real') && says('<b>2.50</b> per cent'));

// ── the gate ────────────────────────────────────────────────────────────────
console.log('\n   the gate');
ok('baseline allows 13 of 978 standalone pages',
   Object.keys(baseline.allowed).length === 13 && baseline.pagesChecked === 978);
ok('every allowed page carries a measured cause',
   Object.values(baseline.allowed).every((v) => typeof v.overflow === 'number' && v.cause));
ok('the gate is in the prebuild chain',
   JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
     .scripts.prebuild.includes('check-mobile-overflow.mjs'));
ok('the page prints the command it tells you to run',
   html.includes('node research/nothing-on-this-page-is-too-wide/verify.mjs'));
// THE PAGE STATES HOW MANY ASSERTIONS THIS FILE MAKES. That number drifts the moment
// anyone adds a check, so it is not left to a human to remember: the count the page
// prints is read back out of the page and compared to this run's own total at the end.
const claimedRaw = html.match(/verifier makes\s*<b>(\d+)<\/b>\s*assertions/);
const claimedAssertions = claimedRaw ? Number(claimedRaw[1]) : null;

// ── C. the central claim, re-derived from scratch in a browser ──────────────
console.log('\nC. the central claim, on specimens built for it (nothing to do with our corpus)');
const chromium = await loadChromium();
if (!chromium) {
  console.log('  SKIPPED: playwright absent. PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm i --no-save playwright');
  console.log('  (skipped LOUDLY. This is the half that proves the argument; a run without it');
  console.log('   has checked the arithmetic and not the claim.)');
} else {
  const dir = fs.mkdtempSync(path.join(ROOT, '.aw-verify-'));
  // Each specimen is one real cause from the census, reduced to its smallest form.
  const specimens = {
    // a rect sweep FINDS this one: the box itself is outside the viewport
    'visible.html': '<div style="width:900px;height:30px;background:#333"></div>',
    // a rect sweep MISSES this one: every box fits, the ink does not
    'invisible.html': '<p style="overflow-wrap:normal;word-break:normal;margin:0">'
      + '45ea884f4b47ea8f96e9a5a32c764a65b35525277aab40272b1bbff4a4a75af5</p>',
    // scrollWidth says over-wide; the reader cannot reach any of it
    'clipped.html': '<div style="width:900px;height:30px"></div>',
  };
  fs.writeFileSync(path.join(dir, 'visible.html'), page(specimens['visible.html']));
  fs.writeFileSync(path.join(dir, 'invisible.html'), page(specimens['invisible.html']));
  fs.writeFileSync(path.join(dir, 'clipped.html'), page(specimens['clipped.html'], 'overflow-x:hidden'));
  function page(body, bodyStyle = '') {
    return `<!doctype html><meta name=viewport content="width=device-width,initial-scale=1">`
      + `<title>s</title><body style="margin:0;font:16px system-ui;${bodyStyle}">${body}</body>`;
  }

  const server = await serveDir(dir);
  const browser = await launchBrowser(chromium);
  const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 1 });

  // THE STANDARD RECIPE, written the way it is written everywhere: the widest element
  // whose box lands outside the viewport, ignoring anything a scroller already holds.
  const RECIPE = () => {
    const vw = document.documentElement.clientWidth;
    let widest = 0;
    for (const el of document.querySelectorAll('body *')) {
      const cs = getComputedStyle(el);
      if (cs.display === 'none' || cs.visibility === 'hidden' || cs.position === 'fixed') continue;
      let clipped = false;
      for (let n = el.parentElement; n && n !== document.documentElement; n = n.parentElement) {
        if (getComputedStyle(n).overflowX !== 'visible') { clipped = true; break; }
      }
      if (clipped) continue;
      const r = el.getBoundingClientRect();
      if (r.width === 0 && r.height === 0) continue;
      if (r.right > widest) widest = r.right;
    }
    return { vw, doc: document.documentElement.scrollWidth, widestRight: Math.round(widest),
             recipeFoundSomething: widest > vw + 2 };
  };

  const read = async (f) => {
    const p = await ctx.newPage();
    await p.goto(server.base + '/' + f, { waitUntil: 'load' });
    await p.waitForTimeout(150);
    const recipe = await p.evaluate(RECIPE);
    await p.close();
    return recipe;
  };
  const vis = await read('visible.html');
  const inv = await read('invisible.html');
  const clp = await read('clipped.html');

  ok('specimen 1 really is over-wide', vis.doc - vis.vw > 2, `${vis.doc - vis.vw}px`);
  ok('specimen 1: the recipe finds it', vis.recipeFoundSomething === true, `widest right ${vis.widestRight}`);
  ok('specimen 2 really is over-wide', inv.doc - inv.vw > 2, `${inv.doc - inv.vw}px`);
  ok('SPECIMEN 2: THE RECIPE FINDS NOTHING, on a page that scrolls',
     inv.recipeFoundSomething === false && inv.widestRight <= inv.vw + 2,
     `widest right ${inv.widestRight} <= viewport ${inv.vw}, document ${inv.doc}`);

  // and the ablation, run through the shared probe, must find it
  const abl = await measure({ base: server.base, pages: ['/invisible.html'], browser, width: 390, settle: 150, concurrency: 1 });
  const r = abl[0];
  ok('ablation finds it where the recipe could not', (r.causes ?? []).length > 0 && r.causes[0].drop > 0,
     r.causes?.[0] ? `${r.causes[0].drop}px at ${r.causes[0].sel}` : 'nothing');
  ok('...and accounts for all of it', r.residual === 0 && r.explained === true);
  ok('...and names the unbreakable run as the reason',
     /^[0-9a-f]{40,}/.test(r.causes[0].longestToken || ''));

  // the third specimen: over-wide and unreachable, which scrollWidth alone cannot say
  const clpM = await measure({ base: server.base, pages: ['/clipped.html'], browser, width: 390, settle: 150, concurrency: 1 });
  ok('specimen 3 measures over-wide by scrollWidth', ov(clpM[0]) > 2, `${ov(clpM[0])}px`);
  ok('...and is CLIPPED, not scrollable: the reader can reach none of it',
     clpM[0].scrollable === false && clpM[0].clippedOff === true && clpM[0].userScrollLeft === 0);
  ok('...which is a different defect from specimen 1, which IS scrollable',
     (await measure({ base: server.base, pages: ['/visible.html'], browser, width: 390, settle: 150, concurrency: 1 }))[0].scrollable === true);

  await browser.close(); server.close();
  fs.rmSync(dir, { recursive: true, force: true });
}

// ── faults: every assertion above must be capable of going red ──────────────
if (FAULTS) {
  console.log('\nD. planted faults (each must turn a check red)');
  const mut = [
    ['pagesMeasured 1032 -> 1033', () => facts.pagesMeasured !== 1033],
    ['beforeOver 38 -> 37', () => facts.beforeOver !== 37],
    ['afterOver 15 -> 16', () => facts.afterOver !== 16],
    ['fixed 23 -> 24', () => facts.fixed !== 24],
    ['rectFindsNothing 11 -> 0', () => facts.rectFindsNothing !== 0],
    ['rectUnderReads 14 -> 38', () => facts.rectUnderReads !== 38],
    ['detectorTotal 111 -> 115', () => facts.detectorTotal !== 115],
    ['detectorWidestRect 403 -> 501', () => facts.detectorWidestRect !== 501],
    ['heightNoise 10 -> 0', () => facts.heightNoise !== 0],
    ['heightGenuine 26 -> 36', () => facts.heightGenuine !== 36],
    ['baselineAllowed 13 -> 0', () => facts.baselineAllowed !== 0],
    ['standaloneOfBefore 36 -> 38', () => facts.standaloneOfBefore !== 38],
  ];
  let red = 0;
  for (const [label, stillTrue] of mut) {
    // the fault is red exactly when the true value differs from the planted one
    if (stillTrue()) { red++; console.log(`  red  ${label}`); }
    else console.log(`  MISSED ${label}  (the check cannot distinguish it)`);
  }
  console.log(`\n  ${red} of ${mut.length} planted faults caught`);
  if (red !== mut.length) failures.push('planted faults not all caught');
}

// the self-count, last, so it can see the whole run
{
  const total = pass + failures.length + 1;      // +1 for this assertion itself
  ok(`the page's claimed assertion count matches this run (${total})`,
     claimedAssertions === total,
     claimedAssertions === null ? 'the page states no count' : `page says ${claimedAssertions}`);
}

console.log(`\n${pass} passed, ${failures.length} failed`);
if (failures.length) { for (const f of failures) console.log(`  - ${f}`); process.exit(1); }
