// verify-page.mjs — drive the built /tools/strictcheck/ page in a real browser.
//   npm run build && node research/strictcheck/verify-page.mjs
// Checks the wiring: the default example renders the matrix; the Gemini
// silent-ignore alert fires for a constraints schema; structural warnings
// appear (missing additionalProperties, optionals, root anyOf, $ref); the
// corrected-schema tabs produce a fixed schema; invalid JSON shows an error;
// the schema round-trips through the URL hash; examples load. Screenshots too.
import pw from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pw;
import { createServer } from 'http';
import { readFileSync } from 'fs';
import { extname, join } from 'path';

const root = new globalThis.URL('../../dist/', import.meta.url).pathname;
const types = { '.html':'text/html','.css':'text/css','.js':'text/javascript','.mjs':'text/javascript','.woff2':'font/woff2','.png':'image/png','.svg':'image/svg+xml','.ico':'image/x-icon','.md':'text/markdown' };
const server = createServer((req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]); if (p.endsWith('/')) p += 'index.html';
  try { const b = readFileSync(join(root, p)); res.writeHead(200, { 'content-type': types[extname(p)] || 'application/octet-stream' }); res.end(b); }
  catch { res.writeHead(404); res.end('404'); }
});
await new Promise(r => server.listen(8102, r));

let fails = 0;
const ok = (n, c, extra = '') => { console.log((c ? '  ✓ ' : '  ✗ FAIL ') + n + (extra ? '  ' + extra : '')); if (!c) fails++; };

const browser = await chromium.launch();
for (const vp of [{ w: 1280, h: 1100, name: 'desktop' }, { w: 390, h: 820, name: 'mobile' }]) {
  const page = await browser.newPage({ viewport: { width: vp.w, height: vp.h }, deviceScaleFactor: 1 });
  const errs = [];
  page.on('pageerror', e => errs.push(e.message));
  page.on('console', m => { if (m.type() === 'error') errs.push('console: ' + m.text()); });
  console.log(`\n[${vp.name} ${vp.w}x${vp.h}]`);

  await page.goto('http://localhost:8102/tools/strictcheck/', { waitUntil: 'networkidle' });
  await page.waitForTimeout(250);
  ok('no JS / console errors on load', errs.length === 0);
  if (errs.length) console.log('     ' + errs.join('\n     '));

  // default example (value constraints) auto-loads and renders the matrix
  ok('default example loads and output is visible', !(await page.$eval('#out', el => el.classList.contains('hidden'))));
  const rows = await page.$$eval('#matrix tbody tr', els => els.map(r => r.querySelector('th').textContent));
  ok('matrix lists the keywords in the schema', rows.includes('minLength') && rows.includes('pattern') && rows.includes('uniqueItems'), rows.join(','));
  const cols = await page.$$eval('#matrix thead th', els => els.length);
  ok('matrix has keyword + 4 provider-surface columns', cols === 5, 'cols=' + cols);

  // the headline: Gemini silent-ignore alert names minLength
  const alerts = await page.textContent('#alerts');
  ok('Gemini silent-ignore alert names the dropped keywords', /silently ignore/i.test(alerts) && /minLength/.test(alerts), alerts.slice(0, 80).replace(/\s+/g, ' '));
  ok('OpenAI rejection alert fires for uniqueItems', /OpenAI strict will reject/i.test(alerts) && /uniqueItems/.test(alerts));

  // a silently-ignored chip actually renders in the matrix (the I class)
  const ichips = await page.$$eval('#matrix .chip.I', els => els.length);
  ok('at least one "silently ignored" chip in the matrix', ichips >= 1, 'count=' + ichips);
  const xchips = await page.$$eval('#matrix .chip.X', els => els.length);
  ok('at least one "rejected" chip in the matrix', xchips >= 1, 'count=' + xchips);

  // corrected schema: open, expect it to differ from input for OpenAI (strips uniqueItems etc.)
  await page.click('#corr summary');
  await page.waitForTimeout(120);
  const corrected = await page.textContent('#corrPre');
  ok('corrected (OpenAI) schema drops rejected keywords', !/uniqueItems/.test(corrected) && corrected.length > 20);
  const changes = await page.textContent('#corrChanges');
  ok('corrected schema lists what it changed', /removed|made|set|required/i.test(changes));

  // structural: load the "optional fields" example → OpenAI optional warning
  await page.click('[data-ex="optional"]');
  await page.waitForTimeout(150);
  ok('optional-fields example flags OpenAI optionals', /forbids optionals/i.test(await page.textContent('#struct')));

  // composition example → $ref + oneOf structural note
  await page.click('[data-ex="composition"]');
  await page.waitForTimeout(150);
  const struct3 = await page.textContent('#struct');
  ok('composition example flags $ref handling', /\$ref/.test(struct3));

  // invalid JSON shows a parse error and hides output
  await page.fill('#schema', '{ not valid json');
  await page.waitForTimeout(150);
  ok('invalid JSON shows a parse error', /not valid json/i.test(await page.textContent('#err')));
  ok('output hidden on invalid JSON', await page.$eval('#out', el => el.classList.contains('hidden')));

  // URL round-trip: type a schema, share, reload from hash
  await page.fill('#schema', '{"type":"object","additionalProperties":false,"properties":{"x":{"type":"string","minLength":2}},"required":["x"]}');
  await page.waitForTimeout(150);
  const url = await page.evaluate(() => location.href);
  ok('schema round-trips through the URL hash (never sent)', /#s=/.test(url));

  const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok('no horizontal page overflow (matrix scrolls in its own box)', overflow <= 1, 'overflow=' + overflow + 'px');

  // ── the depth regression, reported by Marco (marcologs.com) 2026-09-04 ─────
  //
  // The analyzer used to descend into ten subschema keywords, and
  // patternProperties, if/then/else, contains, propertyNames, dependentSchemas
  // and the unevaluated* pair were not among them. A keyword under one of those
  // never reached the verdict, so the banner printed "No silent drops or
  // rejections detected" over a schema carrying a keyword the ruleset grades X.
  //
  // Each case below is a PAIR: the same schema with and without one graded
  // keyword. If the verdict does not move between them, the analyzer is not
  // looking. A check that only ever ran the positive half would pass on the
  // broken tool, which is exactly how this survived: the offline verifier
  // re-implemented the same ten-key walk and reported 42 of 42.
  const banner = async (schema) => {
    await page.fill('#schema', JSON.stringify(schema));
    await page.waitForTimeout(160);
    return (await page.textContent('#alerts')) || '';
  };
  const GREEN = /No silent drops or rejections detected/;
  const DEPTH_PAIRS = [
    ['patternProperties', { type:'object', additionalProperties:false, properties:{ id:{type:'string'} }, required:['id'],
                            patternProperties:{ '^x-':{ type:'string', minLength:3 } } }, 'minLength'],
    ['if / then',         { type:'object', additionalProperties:false, properties:{ n:{type:'integer'} }, required:['n'],
                            if:{ properties:{ n:{type:'integer'} } }, then:{ properties:{ n:{ type:'integer', maximum:10 } } } }, 'maximum'],
    ['contains',          { type:'object', additionalProperties:false, properties:{ a:{ type:'array', contains:{ type:'string', maxLength:5 } } }, required:['a'] }, 'maxLength'],
    ['propertyNames',     { type:'object', additionalProperties:false, properties:{ a:{type:'string'} }, required:['a'],
                            propertyNames:{ pattern:'^[a-z]+$' } }, 'pattern'],
    ['dependentSchemas',  { type:'object', additionalProperties:false, properties:{ a:{type:'string'} }, required:['a'],
                            dependentSchemas:{ a:{ properties:{ b:{ type:'string', minLength:2 } } } } }, 'minLength'],
  ];
  for (const [where, schema, kw] of DEPTH_PAIRS) {
    const withIt = await banner(schema);
    ok('a graded keyword under ' + where + ' reaches the verdict', !GREEN.test(withIt), kw + ' -> ' + withIt.replace(/\s+/g,' ').trim().slice(0, 70));
  }
  // The negative half of each pair: with nothing graded in it, the same shape
  // MUST still come back clean, or the check above passes for the wrong reason.
  const cleanShape = await banner({ type:'object', additionalProperties:false, properties:{ id:{type:'string'} }, required:['id'],
                                    patternProperties:{ '^x-':{ type:'string' } } });
  ok('and the same shape with no graded keyword still reads clean', GREEN.test(cleanShape),
     cleanShape.replace(/\s+/g,' ').trim().slice(0, 70));

  // The census: a graded keyword under a container the analyzer CANNOT know
  // about must refuse the clean banner rather than ignore it. This is the half
  // that survives the specification growing, and a longer key list cannot
  // provide it.
  const vendor = await banner({ type:'object', additionalProperties:false, properties:{ a:{type:'string'} }, required:['a'],
                                'x-vendor':{ minLength:4 } });
  ok('an unreachable graded keyword blocks the clean banner', !GREEN.test(vendor) && /incomplete/i.test(vendor),
     vendor.replace(/\s+/g,' ').trim().slice(0, 80));

  // And the artifact, which is the half that matters most: a schema handed to
  // the user as corrected-for-Anthropic must not still carry a keyword the
  // ruleset says Anthropic rejects.
  await page.fill('#schema', JSON.stringify({ type:'object', additionalProperties:false, properties:{ id:{type:'string'} },
    required:['id'], patternProperties:{ '^x-':{ type:'string', minLength:3 } } }));
  await page.waitForTimeout(160);
  await page.evaluate(() => { const d = document.getElementById('corr'); if (d) d.open = true; });
  for (const t of await page.$$('#corrTabs button')) { if ((await t.innerText()).trim() === 'Anthropic') { await t.click(); break; } }
  await page.waitForTimeout(160);
  const corrDeep = await page.textContent('#corrPre');
  // Structurally, not by substring: the Anthropic fix MOVES the keyword into a
  // description, so the word legitimately still appears in the text. What must
  // not survive is minLength as a KEY. (The first version of this assertion
  // used a bare /minLength/ and failed on the tool's own correct output.)
  const hasKeyDeep = (function find(n){
    if (!n || typeof n !== 'object') return false;
    if (Array.isArray(n)) return n.some(find);
    if (Object.prototype.hasOwnProperty.call(n, 'minLength')) return true;
    return Object.values(n).some(find);
  })(JSON.parse(corrDeep));
  ok('the corrected-for-Anthropic artifact strips a nested rejected keyword', !hasKeyDeep,
     hasKeyDeep ? 'minLength still present as a key' : 'moved into description');

  await page.click('[data-ex="constraints"]');
  await page.waitForTimeout(150);
  // Resolve the screenshot beside THIS file rather than from the working directory.
  // A root-relative path only lands correctly when the verifier is run from the repo
  // root; run it from its own directory, as the corpus sweep does, and it silently
  // creates research/<name>/research/<name>/page-*.png instead. Three verifiers did
  // that on 2026-08-21 and left 3.8 MB of duplicate screenshots behind.
  await page.screenshot({ path: new globalThis.URL(`./page-${vp.name}.png`, import.meta.url).pathname, fullPage: true });
  await page.close();
}
await browser.close();
server.close();
console.log('\n' + (fails === 0 ? 'ALL BROWSER CHECKS PASS' : `${fails} BROWSER CHECK(S) FAILED`));
process.exit(fails === 0 ? 0 : 1);
