// research/church-axes/verify-page.mjs — drive the built page in a real browser and check
// what a reader actually sees, not what the source says.
//
//   node research/church-axes/verify-page.mjs
//   node research/church-axes/verify-page.mjs --doctor    # plant a fault, require a red result
//
// ⚠ The reason this is separate from the data verifier. A page can pass every assertion
// about its files and still show a reader nothing: the corpus has shipped pages whose
// controls were dead, whose canvases rendered pure black while every returned number was
// correct, and whose headline figure was filled in live and therefore invisible to any
// check that read the HTML source. Whether a reader can see a number is a question for the
// browser, so it is asked here, against the rendered DOM.

import http from 'node:http'
import fs from 'node:fs'
import path from 'node:path'

const ROOT = '/home/liam/aw-claude-quenching-fermi-2b8e'
const DIR = path.join(ROOT, 'public/strata/half-the-grid-is-missing')
const DOCTOR = process.argv.includes('--doctor')

let chromium
try { ({ chromium } = await import('playwright')) } catch {
  ({ chromium } = (await import('/opt/node22/lib/node_modules/playwright/index.js')).default)
}
const CHROME = process.env.AW_CHROMIUM || (fs.existsSync('/opt/pw-browsers/chromium') ? '/opt/pw-browsers/chromium' : null)

const MIME = { '.html': 'text/html', '.json': 'application/json', '.bin': 'application/octet-stream', '.css': 'text/css', '.js': 'text/javascript' }
// Serve the page directory, falling back to public/ for the site's shared assets. Without
// the fallback the stylesheet 404s and the run reports a console error that is an artifact
// of the harness rather than a fault in the page: a check whose own scaffolding generates
// the failure it reports is worse than no check.
const PUBLIC = path.join(ROOT, 'public')
const server = http.createServer((req, res) => {
  const rel = req.url === '/' ? 'index.html' : decodeURIComponent(req.url.split('?')[0]).replace(/^\/+/, '')
  let p = path.join(DIR, rel)
  if (!fs.existsSync(p)) p = path.join(PUBLIC, rel)
  if (!fs.existsSync(p) || fs.statSync(p).isDirectory()) { res.writeHead(404); return res.end() }
  res.writeHead(200, { 'Content-Type': MIME[path.extname(p)] || 'application/octet-stream' })
  fs.createReadStream(p).pipe(res)
})
await new Promise(r => server.listen(0, '127.0.0.1', r))
const base = `http://127.0.0.1:${server.address().port}/`

const payload = JSON.parse(fs.readFileSync(path.join(DIR, 'payload.json'), 'utf8'))
let pass = 0, fail = 0
const fails = []
const ok = (c, m, d) => { if (c) pass++; else { fail++; fails.push(m + (d ? `  [${d}]` : '')) } }

const browser = await chromium.launch(CHROME ? { executablePath: CHROME } : {})
const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } })
const page = await ctx.newPage()
const errors = []
page.on('pageerror', e => errors.push(String(e)))
page.on('console', m => { if (m.type() === 'error') errors.push(m.text()) })

await page.goto(base, { waitUntil: 'networkidle' })
await page.waitForFunction(() => document.getElementById('k-raw').textContent !== '…', { timeout: 30000 })

if (DOCTOR) {
  // Plant a fault the way a reader would see one: rewrite the rendered headline ratio.
  await page.evaluate(() => { document.getElementById('k-ratio').textContent = '9.99' })
}

console.log('=== what the page displays ===')
const txt = async id => (await page.textContent('#' + id)).trim()
const raw = await txt('k-raw'), adm = await txt('k-adm'), ratio = await txt('k-ratio')
console.log(`    footprints ${raw}   admitted ${adm}   ratio ${ratio}`)

ok(raw === payload.frame.raw.toLocaleString('en-US'), 'displayed footprint count matches payload', raw)
ok(adm === payload.admitted.n.toLocaleString('en-US'), 'displayed admitted count matches payload', adm)
ok(ratio === payload.admitted.ratio.toFixed(2), 'displayed east/north ratio matches payload', `${ratio} vs ${payload.admitted.ratio.toFixed(2)}`)

console.log('\n=== the rose actually drew something ===')
const ink = await page.evaluate(() => {
  const c = document.getElementById('rose')
  const g = c.getContext('2d')
  const d = g.getImageData(0, 0, c.width, c.height).data
  let n = 0
  for (let i = 3; i < d.length; i += 4) if (d[i] > 8) n++
  return n
})
ok(ink > 20000, 'the rose canvas has ink on it', `${ink} non-transparent pixels`)
console.log(`    ${ink} non-transparent pixels`)

// The rose must be visibly asymmetric: more ink to the east than to the north. This is the
// page's entire claim, drawn rather than stated, so it is checked as pixels.
const lobes = await page.evaluate(() => {
  const c = document.getElementById('rose'), g = c.getContext('2d')
  const cx = c.width / 2, cy = c.height / 2, R = Math.min(c.width, c.height) * 0.43
  const d = g.getImageData(0, 0, c.width, c.height).data
  let east = 0, north = 0
  for (let y = 0; y < c.height; y++) for (let x = 0; x < c.width; x++) {
    const a = d[(y * c.width + x) * 4 + 3]; if (a <= 8) continue
    const dx = x - cx, dy = cy - y
    const r = Math.hypot(dx, dy); if (r > R * 1.02) continue
    const ang = Math.abs(Math.atan2(dx, dy) * 180 / Math.PI)   // 0 = north, 90 = east
    if (ang > 75 && ang < 105) east++
    else if (ang < 15 || ang > 165) north++
  }
  return { east, north }
})
ok(lobes.east > lobes.north * 1.5, 'the drawn rose is visibly longer to the east than to the north',
  `east ${lobes.east}, north ${lobes.north}`)
console.log(`    east lobe ${lobes.east} px, north lobe ${lobes.north} px`)

console.log('\n=== the page\'s own check ran and passed ===')
const check = await page.textContent('#checkout')
ok(/passed/.test(check), 'the recompute panel reported a result')
ok(!/FAIL/.test(check), 'the recompute panel found no failures', check.split('\n').filter(l => l.includes('FAIL')).slice(0, 2).join(' | '))
const m = check.match(/(\d+) passed, (\d+) failed/)
console.log(`    ${m ? m[0] : '(no summary)'}`)

console.log('\n=== the mutation button turns it red ===')
await page.click('#mutate')
await page.waitForFunction(() => /records corrupted/.test(document.getElementById('checkout').textContent), { timeout: 60000 })
const mut = await page.textContent('#checkout')
ok(/records corrupted/.test(mut), 'the corruption sweep ran')
ok(/\bRED\b/.test(mut), 'the sweep drives the comparison red at some corruption level',
  'no level of corruption moved a displayed figure, so the check sees nothing')
ok(!/NOTHING WENT RED at any level/.test(mut), 'the sweep found a level where the check notices')
for (const l of mut.split('\n').filter(l => /records corrupted/.test(l))) console.log('    ' + l.trim())
console.log('    ' + (mut.match(/The comparison goes red[^\n]*/) || ['(no verdict)'])[0].slice(0, 150))

console.log('\n=== the degenerate-shape demonstration is on screen ===')
const shapeRows = await page.$$eval('#shapetable tbody tr', rs => rs.map(r => r.textContent.replace(/\s+/g, ' ').trim()))
ok(shapeRows.length >= 5, 'the shape table rendered its rows', String(shapeRows.length))
ok(shapeRows.every(r => /refused/.test(r)), 'every regular shape is shown as refused')
for (const r of shapeRows) console.log('    ' + r)

console.log('\n=== controls do something ===')
const before = await txt('rosedesc')
await page.evaluate(() => { const s = document.getElementById('s-ref'); s.click() })
await page.waitForTimeout(400)
const after = await txt('rosedesc')
ok(before !== after, 'switching to the axis-less set changes the readout')

ok(errors.length === 0, 'no console or page errors', errors.slice(0, 2).join(' | '))

console.log('\n' + '='.repeat(56))
console.log(`${pass} passed, ${fail} failed`)
if (fails.length) { console.log('\nFAILURES:'); for (const f of fails) console.log('  - ' + f) }

await browser.close(); server.close()

if (DOCTOR) {
  if (fail > 0) { console.log('\nDOCTORED VALUE CAUGHT: the check reads the rendered page, not the payload.'); process.exit(0) }
  console.log('\nDOCTORED VALUE NOT CAUGHT: this suite is not reading what the reader sees.')
  process.exit(1)
}
process.exit(fail ? 1 : 0)
