#!/usr/bin/env node
// The two front doors, driven in a real browser.
//
// These pages are the only part of the catalogue that computes anything in front of a
// reader, so nothing here reads the payload and calls it a pass: every assertion drives the
// page the way a person would and reads the answer back out of the rendered DOM.
import http from 'node:http'
import { readFile } from 'node:fs/promises'
import { existsSync, readFileSync } from 'node:fs'
import { extname } from 'node:path'
import { chromium } from 'playwright'

let pass = 0, fail = 0
const ok = (c, m) => { if (c) { pass++; console.log(`  ok   ${m}`) } else { fail++; console.log(`  FAIL ${m}`) } }
const TYPES = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2' }

const srv = http.createServer(async (q, s) => {
  let p = 'public' + decodeURIComponent(q.url.split('?')[0].split('#')[0])
  if (p.endsWith('/')) p += 'index.html'
  try { const b = await readFile(p); s.writeHead(200, { 'Content-Type': TYPES[extname(p)] ?? 'application/octet-stream' }); s.end(b) }
  catch { s.writeHead(404); s.end('x') }
})
await new Promise(r => srv.listen(0, r))
const base = `http://127.0.0.1:${srv.address().port}/tools/australian-coins`
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } })
const errors = []
page.on('pageerror', e => errors.push(e.message))

// ---- the collection view is now the only browsing interface: the guided lookup and the
// table of every issue were both absorbed into it and retired to stubs. These checks drive
// what a reader actually does, and the stubs are checked for pointing somewhere real rather
// than for their content.
// Read from disk, not through the browser: the stub carries a meta refresh, so Playwright
// navigates away mid-read and page.content() throws. The claim being checked is about the
// FILE, so the file is the right thing to look at.
for (const [slug, name] of [['what-have-you-got', 'the guided lookup'], ['all-issues', 'the issue table']]) {
  let html = null
  try { html = await readFile(`public/tools/australian-coins/${slug}/index.html`, 'utf8') } catch {}
  ok(html !== null, `${name} stub is still served rather than gone`)
  ok(/rel="canonical"[^>]*collection/.test(html ?? ''), `${name} stub names the collection view as canonical`)
  ok(/noindex/.test(html ?? ''), `${name} stub asks not to be indexed`)
  ok(/collection\//.test(html ?? ''), `${name} stub gives a reader somewhere to click`)
}

// ---- the printable scale guide: the circles must be TRUE SIZE or the page is worse than
// useless, so this measures the rendered geometry rather than trusting the markup.
await page.goto(`${base}/actual-size/`)
await page.waitForTimeout(300)
const geo = await page.evaluate(() => {
  const px = mm => mm * 96 / 25.4
  const out = { ruler: document.querySelector('.ruler svg').getBoundingClientRect().width, rulerWant: px(108), coins: [] }
  document.querySelectorAll('.coin').forEach(f => {
    const w = f.querySelector('svg').getBoundingClientRect().width
    const mm = parseFloat((f.querySelector('figcaption').innerText.match(/([\d.]+) mm/) || [])[1] || 0)
    out.coins.push({ label: f.querySelector('b').textContent, drawn: Math.round(w), want: Math.round(px(mm + 2)) })
  })
  return out
})
ok(Math.abs(geo.ruler - geo.rulerWant) < 1, `the 100 mm reference bar renders at its true length (${Math.round(geo.ruler)}px)`)
ok(geo.coins.length >= 8, `coins are drawn (${geo.coins.length})`)
ok(geo.coins.every(c => c.drawn === c.want), 'every circle renders at exactly the millimetre size it claims')
const noCircle = await page.evaluate(() => [...document.querySelectorAll('.coin b')].map(b => b.textContent))
ok(!noCircle.includes('Shilling') && !noCircle.includes('Florin'),
   'no circle is drawn for a coin whose diameter is not sourced (shilling, florin)')
const undrawnText = await page.evaluate(() => document.body.innerText)
ok(/Coinage Acts set a coin's/.test(undrawnText), 'the page explains why most pre-decimal coins have no circle')

// ---- the collector's HUD. Its one irreversible-feeling action is marking a coin, so the
// storage is driven rather than inspected: mark, reload, and require the mark to survive.
await page.goto(`${base}/collection/`)
await page.waitForTimeout(700)
ok(await page.$$eval('.denbtn', b => b.length) > 10, 'the rail lists every denomination')
await page.click('.denbtn[data-den="florin"]')
await page.waitForTimeout(300)
const coins = await page.$$eval('.coin', c => c.length)
ok(coins > 30, `choosing a denomination fills the grid (${coins})`)
ok(await page.$$eval('.coin img', c => c.length) > 20, 'coins we have photographed show their photograph')
await page.click('.coin')
await page.waitForTimeout(200)
ok(await page.evaluate(() => !document.querySelector('#panel').hidden), 'clicking a coin opens its panel')
ok(/We will not say/.test(await page.evaluate(() => document.querySelector('#panel').innerText)), 'the panel still refuses to give a value')
await page.click('#mark')
await page.waitForTimeout(200)
ok(await page.$$eval('.coin.owned', c => c.length) === 1, 'marking a coin marks exactly one')
const stored = await page.evaluate(() => localStorage.getItem('aw-au-coins-collection'))
ok(/au-florin-/.test(stored ?? ''), 'the mark is written to this browser only')
await page.reload()
await page.waitForTimeout(700)
await page.click('.denbtn[data-den="florin"]')
await page.waitForTimeout(300)
ok(await page.$$eval('.coin.owned', c => c.length) === 1, 'the mark survives a reload')
// filters must actually filter
await page.click('.f[data-f="silver"]')
await page.waitForTimeout(200)
const allSilver = await page.$$eval('.coin', cs => cs.length)
ok(allSilver > 0 && allSilver <= coins, `filtering to silver narrows the grid (${allSilver} of ${coins})`)

// ---- no link in the payload may point at a page that was not built.
//
// This shipped 928 dead links. The payload computed a coin's URL from the same rule that
// decides which coins get pages, which meant two copies of that rule, and when the rule
// tightened from 461 pages to 55 only one copy changed. Every link now comes from the
// FILESYSTEM instead, and this check is what keeps the two honest.
{
  const app = JSON.parse(await readFile('public/tools/australian-coins/api/app.json', 'utf8'))
  const bad = []
  for (const i of app.issues) {
    if (!i.href) continue
    if (!existsSync(`public${i.href}index.html`)) bad.push(`${i.id} -> ${i.href}`)
  }
  ok(bad.length === 0, `every coin link in the payload points at a page that exists${bad.length ? `: ${bad.length} do not, e.g. ${bad[0]}` : ''}`)
  const anchored = app.issues.filter(i => !i.href && i.anchor).length
  ok(anchored > 0, `coins without a page of their own fall back to a denomination anchor (${anchored})`)
  // and the fallback has to land somewhere real too
  const anchorBad = app.issues.filter(i => !i.href && i.anchor)
    .filter(i => !existsSync(`public${i.anchor.split('#')[0]}index.html`))
  ok(anchorBad.length === 0, `every fallback anchor points at a denomination page that exists${anchorBad.length ? `: ${anchorBad.length} do not` : ''}`)
}

// ---- what a first-time visitor sees. This shipped landing on Fifty cents, which is
// alphabetically first, is decimal, and is almost entirely coins whose designs we may not
// photograph: 76 empty circles, which reads as a broken page rather than a copyright limit.
// The landing view is chosen by evidence now, and this stops it drifting back.
await page.goto(`${base}/collection/`)
await page.waitForTimeout(800)
const landing = await page.evaluate(() => ({
  den: document.querySelector('#head h2')?.textContent ?? '',
  coins: document.querySelectorAll('.coin').length,
  photos: document.querySelectorAll('.coin img').length,
}))
ok(landing.coins >= 20, `the landing denomination is big enough to be representative (${landing.coins} coins)`)
// Both faces, because the reverse is the side that tells an Australian coin apart and the
// museum does not label which of its two images is which.
ok(landing.photos >= landing.coins * 1.5,
   `photographed coins show BOTH faces, not one (${landing.photos} images across ${landing.coins} coins)`)
ok((await page.evaluate(() => [...document.querySelectorAll('.coin img')].filter(i => i.naturalWidth === 0).length)) === 0,
   'every coin image actually loads from the museum')
ok(landing.photos / landing.coins > 0.8,
   `the landing view is mostly photographed, not mostly empty (${landing.photos} of ${landing.coins} in ${landing.den})`)
// and a denomination with none must explain itself rather than look broken
await page.click('.denbtn[data-den="fifty-cents"]')
await page.waitForTimeout(300)
const why = await page.evaluate(() => document.querySelector('.nophotonote')?.innerText ?? '')
ok(/copyright/i.test(why), 'a denomination we may not photograph says why, rather than showing empty circles')

// ---- coins we may not photograph are DRAWN from the statute, and the drawing must be as
// honest as a figure: right shape, true relative size where the diameter is sourced, and
// visibly not to scale where it is not.
{
  const app = JSON.parse(await readFile('public/tools/australian-coins/api/app.json', 'utf8'))
  const drawn = app.issues.filter(i => !i.photo && i.diagram)
  ok(drawn.length > 400, `unphotographed coins are drawn rather than left blank (${drawn.length})`)
  // The fifty cents went twelve-sided in 1969 and a circle would be a visible lie.
  const fifty69 = app.issues.find(i => i.den === 'fifty-cents' && i.year >= 1969 && i.diagram)
  const fifty66 = app.issues.find(i => i.den === 'fifty-cents' && i.year === 1966 && i.diagram)
  ok(fifty69?.diagram.shape === 'dodecagon', 'the fifty cents from 1969 is drawn twelve-sided, as the Regulations require')
  ok(!fifty66 || fifty66.diagram.shape === 'circle', 'the round 1966 fifty cents is not drawn twelve-sided')
  // relative size must follow the sourced diameters, not be uniform
  const byDen = {}
  for (const i of drawn) if (i.diagram.mm_sourced) byDen[i.den] ??= i.diagram.mm
  ok(byDen['five-cents'] < byDen['fifty-cents'], `a five cents is drawn smaller than a fifty cents (${byDen['five-cents']} mm against ${byDen['fifty-cents']} mm)`)
  ok(drawn.some(i => !i.diagram.mm_sourced), 'coins whose diameter is not sourced are still drawn, at a neutral size')

  await page.goto(`${base}/collection/#fifty-cents`)
  await page.waitForTimeout(900)
  ok(await page.$$eval('.drawn polygon', p => p.length) > 50, 'the twelve-sided fifty cents renders as a polygon, not a circle')
  const widths = await page.$$eval('.coin .drawn svg', s => [...new Set(s.map(x => x.getAttribute('width')))])
  ok(widths.length >= 1, 'diagrams render at a size')
  const cap = await page.evaluate(() => { document.querySelector('.coin')?.click(); return null })
  await page.waitForTimeout(400)
  const fig = await page.evaluate(() => document.querySelector('.pfaces figcaption')?.innerText ?? '')
  ok(/Not a photograph|photograph/i.test(fig), 'the panel says whether it is showing a photograph or a drawing')

  // A milled edge is drawn ONLY where the instrument says milled. The twelve-sided fifty
  // cents is plain-edged and must not be given reeding it never had.
  await page.goto(`${base}/collection/#twenty-cents`)
  await page.waitForTimeout(700)
  ok(await page.$$eval('.drawn line', l => l.length) > 0, 'a milled coin is drawn with its milling')
  await page.goto(`${base}/collection/#fifty-cents`)
  await page.waitForTimeout(700)
  const fiftyMilling = await page.evaluate(() => {
    const c = [...document.querySelectorAll('.coin')].find(x => x.querySelector('polygon'))
    return c ? c.querySelectorAll('line').length : -1
  })
  ok(fiftyMilling === 0, 'the plain-edged twelve-sided fifty cents is drawn without milling')
}

// ---- varieties, which had been reduced to a bare count
{
  await page.goto(`${base}/collection/#penny/1919`)
  await page.waitForTimeout(900)
  const items = await page.$$eval('.vars li', l => l.length)
  ok(items >= 3, `a coin's varieties are listed, not just counted (${items})`)
  const first = await page.evaluate(() => document.querySelector('.vars li')?.innerText ?? '')
  ok(/How you tell it apart/.test(first), 'each variety says how you physically tell it apart')
  ok(await page.$$eval('.grade', g => g.length) >= 3, 'each variety carries its evidence grade')
  const legend = await page.evaluate(() => document.querySelector('#panel dd')?.parentElement?.innerText ?? document.body.innerText)
  ok(/primary|scholarly|trade|hobbyist/.test(legend), 'the grades are explained rather than left as jargon')
  // and a variety whose sources disagree must say so
  const app = JSON.parse(await readFile('public/tools/australian-coins/api/app.json', 'utf8'))
  const dis = app.issues.find(i => (i.variety_list ?? []).some(v => v.disagreement))
  ok(!!dis, 'varieties carrying a recorded disagreement reach the payload')
}

// ---- a phone. The page's whole point is the coins, and on a 390px screen the filter panel
// and a stacked list of sixteen denominations pushed the first one to y=901, below the fold.
{
  const phone = await browser.newPage({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, deviceScaleFactor: 2 })
  const perrs = []
  phone.on('pageerror', e => perrs.push(e.message))
  await phone.goto(`${base}/collection/`)
  await phone.waitForTimeout(1000)
  const m = await phone.evaluate(() => ({
    overflow: document.documentElement.scrollWidth - window.innerWidth,
    firstCoin: Math.round((document.querySelector('.coin')?.getBoundingClientRect().top ?? 0) + window.scrollY),
    perRow: (() => { const c = [...document.querySelectorAll('.coin')].slice(0, 10).map(x => Math.round(x.getBoundingClientRect().top)); return c.filter(t => t === c[0]).length })(),
    filtersOpen: document.querySelector('.filters')?.hasAttribute('open'),
    rails: document.querySelectorAll('.denbtn').length,
  }))
  ok(m.overflow === 0, `the collection view does not scroll sideways on a phone (${m.overflow}px)`)
  ok(m.firstCoin < 700, `a coin is reachable without scrolling past everything (first at y=${m.firstCoin})`)
  ok(m.perRow >= 3, `coins are laid out several to a row on a phone (${m.perRow})`)
  ok(m.filtersOpen === false, 'the filter panel is folded on a phone and open on a desktop')
  ok(m.rails > 10, `every denomination is still reachable, as a row you swipe (${m.rails})`)
  ok(perrs.length === 0, `no JavaScript errors on a phone${perrs.length ? ': ' + perrs[0] : ''}`)
  await phone.close()
}

// ---- search, which is the only way to reach a coin without already knowing where it lives
await page.goto(`${base}/collection/`)
await page.waitForTimeout(700)
for (const [q, want] of [['1930 penny', '1930 penny'], ['florin 1912', '1912 florin'], ['sovereign 1855', '1855 sovereign']]) {
  await page.fill('#q', q)
  await page.waitForTimeout(250)
  const first = await page.$eval('.hit b', b => b.textContent.trim()).catch(() => null)
  ok(first === want, `searching ${JSON.stringify(q)} puts ${JSON.stringify(want)} first (got ${JSON.stringify(first)})`)
}
// A denomination with no dated issue is invisible to a grid built from issues. The crown is
// exactly that, and coming back empty for it would be the search lying about the catalogue.
await page.fill('#q', 'crown')
await page.waitForTimeout(250)
const crownHref = await page.$eval('.hit', h => h.getAttribute('href')).catch(() => null)
ok(crownHref === '/tools/australian-coins/crown/', 'searching for the crown offers its page, though it has no dated issue')
await page.fill('#q', '1930 penny')
await page.waitForTimeout(250)
await page.click('.hit')
await page.waitForTimeout(400)
ok(/1930 penny/.test(await page.evaluate(() => document.querySelector('#panel h3')?.textContent ?? '')), 'clicking a result opens that coin')
ok(await page.evaluate(() => location.hash) === '#penny/1930', 'and gives it an address that can be shared')

await page.click('.denbtn[data-den="sixpence"]')
await page.waitForTimeout(300)
await page.click('.coin')
await page.waitForTimeout(500)
ok(await page.$$eval('.pfaces img', i => i.length) === 2, 'the panel shows both faces of a coin')
ok(/does not record which image is the obverse/.test(await page.evaluate(() => document.querySelector('.pfaces figcaption')?.innerText ?? '')),
   'and says the museum does not label which face is which, rather than guessing')

// ── the ordering, which has two axes because one of them loses the coin that matters ──────
await page.click('.denbtn[data-den="penny"]')
await page.waitForTimeout(300)
const years = async () => page.$$eval('#grid .coin .yr', e => e.map(x => x.textContent))
const mintages = async () => page.$$eval('#grid .coin .m', e => e.map(x => x.textContent.replace(/[^0-9]/g, '')))

ok((await page.$$eval('#sort option', o => o.map(x => x.value))).join(',') === 'year,rank,look',
   'the grid offers three orders: by year, scarcest first, and look at these twice')

await page.selectOption('#sort', 'rank'); await page.waitForTimeout(350)
{
  const m = (await mintages()).filter(Boolean).map(Number)
  ok(m.every((v, n) => !n || v >= m[n - 1]), `scarcest first really is ascending by mintage (${m[0]} then ${m[1]})`)
  // No figure is not a low figure, so an unranked issue must not be presented as the rarest.
  const raw = await page.$$eval('#grid .coin .m', e => e.map(x => x.textContent))
  const firstNo = raw.indexOf('no figure')
  ok(firstNo === -1 || firstNo >= raw.filter(x => x !== 'no figure').length,
     'issues with no figure sort last under scarcest, not first')
}

// The reason the second axis exists. The 1920 penny is unremarkable by mintage and is the coin
// whose dot varieties you would least like to have bagged unlooked-at, so an order that only
// knows about rarity buries it.
const posIn = async (mode, year) => {
  await page.selectOption('#sort', mode); await page.waitForTimeout(300)
  return (await years()).indexOf(year) + 1
}
const byRank = await posIn('rank', '1920')
const byLook = await posIn('look', '1920')
ok(byLook < byRank, `look-at-these-twice pulls the 1920 penny forward, ${byRank} to ${byLook}, because rarity alone buries it`)

await page.reload({ waitUntil: 'domcontentloaded' }); await page.waitForTimeout(900)
ok(await page.inputValue('#sort') === 'look', 'the chosen order survives a reload')
await page.selectOption('#sort', 'year'); await page.waitForTimeout(300)

// ── the three bands, and the mint breakdown ───────────────────────────────────────────────
{
  const app = JSON.parse(readFileSync('public/tools/australian-coins/api/app.json', 'utf8'))
  const I = app.issues
  const banded = I.filter(i => i.band)

  ok(I.every(i => i.band === null || ['scarce', 'ordinary', 'common'].includes(i.band)),
     'every band is one of scarce, ordinary, common, or nothing')
  const pct = 100 * I.filter(i => i.band === 'scarce').length / banded.length
  ok(pct > 5 && pct < 25, `scarce is ${pct.toFixed(0)}% of the ${banded.length} banded issues, which is a minority`)

  // The measure: a ratio to the MEDIAN of the denomination, which needs no total and so never
  // adds figures counted on different bases together.
  const byDen = {}
  for (const i of I) if (typeof i.mintage === 'number' && i.mintage > 0) (byDen[i.den] ??= []).push(i.mintage)
  const med = (a) => { const s = a.slice().sort((x, y) => x - y); return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2 }
  const wrongTypical = banded.filter(i => Math.abs(i.band_typical - med(byDen[i.den])) > 0.5)
  ok(wrongTypical.length === 0, 'each band is measured against the median figure of its own denomination')
  const wrongRatio = banded.filter(i => Math.abs(i.band_ratio - i.mintage / i.band_typical) > 0.005)
  ok(wrongRatio.length === 0, 'band_ratio really is the figure divided by that median')
  const wrongBand = banded.filter(i => {
    const want = i.band_ratio < 0.33 ? 'scarce' : i.band_ratio >= 2 ? 'common' : 'ordinary'
    return i.band !== want
  })
  ok(wrongBand.length === 0, 'every band follows the printed thresholds: scarce under a third of typical, common at double')

  // The coin that sent this measure back twice. Liam: "1925 should definitely trigger as scarce."
  const p1925 = I.find(i => i.id === 'au-penny-1925')
  ok(p1925?.band === 'scarce', `the 1925 penny comes out scarce (${p1925?.band_ratio}x a typical penny), which the basis-scoped version got wrong`)

  ok(I.filter(i => (typeof i.mintage !== 'number' || i.mintage <= 0) && i.band).length === 0,
     'an issue with no figure, or an evidenced zero, is never banded')

  // The branch mints, which a single figure hides completely.
  const withMints = I.filter(i => i.mint_count)
  const multi = I.filter(i => i.mint_count > 1)
  ok(withMints.length > 100 && multi.length > 20,
     `${withMints.length} issues carry a branch-mint breakdown and ${multi.length} name more than one mint`)

  // A mintmarked issue must only ever be shown its OWN mint. Getting this wrong showed three
  // sovereign 1930 issues the whole year's figures, Melbourne's included.
  const MARK = { S: 'Sydney', M: 'Melbourne', P: 'Perth' }
  const foreign = I.filter(i => i.mintmark && (i.mints ?? []).some(m => m.mint !== MARK[i.mintmark]))
  ok(foreign.length === 0, 'a mintmarked issue is only ever shown its own mint, never the whole year')

  const wide = I.filter(i => (i.mint_spread ?? 0) >= 5)
  ok(wide.length >= 5, `${wide.length} issues have mints differing by 5x or more, the widest being ${
    wide.sort((a, b) => b.mint_spread - a.mint_spread)[0]?.den} ${wide[0]?.year} at ${wide[0]?.mint_spread}x`)
  // The one that makes the case: 1946 halfpenny, Melbourne 187,200 against Perth 13,560,000.
  const hp46 = I.find(i => i.id === 'au-halfpenny-1946')
  ok(hp46?.mints?.some(m => m.mint === 'Melbourne' && m.pieces === 187200)
     && hp46?.mints?.some(m => m.mint === 'Perth' && m.pieces === 13560000),
     'the 1946 halfpenny shows both mints, 187,200 against 13,560,000')

  // ── the figures block reads as one thing, not the same thing twice ─────────────────────
  // It used to print "Each figure" and "What each mint reported" as separate lists of the same
  // numbers, and the basis leaked into the prose as a slug: "what the Perth mint
  // struck-in-report-year during report year 1946".
  const withMintTable = I.filter(i => i.mint_count && i.values?.length)
  // The real invariant, written the third time, and the first two are worth keeping because
  // both were wrong in ways that read as fine.
  //
  // The first was `... === false ? false : (... && false)`, which can never be true. It passed
  // on every input, including a panel showing nothing at all.
  //
  // The second keyed on (value, basis) and asked whether anything was LOST. It could not fail
  // either, and measuring rather than assuming showed why: the fault it was aimed at does not
  // lose rows, it DUPLICATES them. Filtering the national rows by a regex on prose rather than
  // on the data leaves in figures the mint table already shows, on 39 issues. The 1946
  // halfpenny looked like a dropped row and was not: the row that disappeared was a duplicate
  // of the Treasury one by value and basis, so nothing was lost there at all.
  //
  // So the invariant is the one that fault actually violates.
  const repeated = withMintTable.filter((i) => {
    const inMints = new Set(i.mints.map((m) => `${m.pieces}|${m.basis}`))
    const national = i.values.filter((v) => !i.mints.some((m) => m.pieces === v.value && m.basis === v.basis))
    return national.some((v) => inMints.has(`${v.value}|${v.basis}`))
  })
  ok(repeated.length === 0,
     `no figure is printed twice, once as a mint row and again as a national one, across ${withMintTable.length} issues with a mint table`)
  const reached = withMintTable.filter((i) => {
    const rows = new Set([...i.mints.map((m) => `${m.pieces}|${m.basis}`),
      ...i.values.filter((v) => !i.mints.some((m) => m.pieces === v.value && m.basis === v.basis)).map((v) => `${v.value}|${v.basis}`)])
    return i.values.every((v) => rows.has(`${v.value}|${v.basis}`))
  })
  ok(reached.length === withMintTable.length, 'and every figure an issue holds reaches one')

  const dupRows = withMintTable.filter(i => {
    const rest = i.values.filter(v => !i.mints.some(m => m.pieces === v.value && m.basis === v.basis))
    const keys = rest.map(v => `${v.value}|${v.basis}`)
    return new Set(keys).size !== keys.length
  })
  ok(dupRows.length > 0, `${dupRows.length} issues carry the same figure on the same basis twice, which the panel folds into one row rather than showing as an error`)

  // The slug must never reach a reader.
  const slugLeak = I.filter(i => (i.values ?? []).some(v => /struck-in-report-year|final-mintage-as-published/.test(v.counts ?? '')))
  ok(slugLeak.length === 0, 'no schema slug leaks into the sentence saying what a figure counted')
  const unnamed = I.filter(i => (i.values ?? []).some(v => /the unstated mint/.test(v.counts ?? '')))
  ok(unnamed.length === 0, 'a mint the report does not name is described in words, not as "the unstated mint"')

  // ── the dates recovered from agreeing public catalogues ────────────────────────────────
  const dated = JSON.parse(readFileSync('research/au-coins/data/dated-issues.json', 'utf8'))
  const recovered = I.filter((i) => /two independent public coin catalogues/.test(i.known_from ?? ''))
  ok(recovered.length === dated.issues.length,
     `all ${dated.issues.length} dates the two catalogues agree on are now issues`)

  // Every one of them says on its own record where the claim of existence came from, because
  // "this coin exists" is itself a claim and this catalogue does not make unattributed ones.
  ok(recovered.every((i) => /no primary document in this catalogue names one/.test(i.known_from)),
     'and each says plainly that no primary document here names it')

  // THE RULE THAT MATTERS. Both catalogues print mintage figures and state no source for them.
  // Nothing may take a figure from either.
  //
  // The first version of this check read v.source off api/app.json, where no value carries a
  // source field at all, so it compared undefined against a regex and passed on everything. It
  // was theatre: the payload is the wrong place to ask, because provenance is deliberately not
  // shipped there. catalogue.json is where a value's source lives, so that is what is read.
  const full = JSON.parse(readFileSync('public/tools/australian-coins/api/catalogue.json', 'utf8'))
  const withSource = full.facts.flatMap((f) => (f.values ?? []).map((v) => v.source)).filter(Boolean)
  ok(withSource.length > 500, `provenance is actually present to test: ${withSource.length} values name a source`)
  const tainted = full.facts.flatMap((f) => (f.values ?? [])
    .filter((v) => /public-catalogues/.test(v.source ?? '')).map((v) => `${f.subject} ${v.value}`))
  ok(tainted.length === 0,
     `no figure in the catalogue comes from the two public catalogues, only the fact that a date is listed${tainted.length ? `: ${tainted[0]}` : ''}`)

  const html = readFileSync('public/tools/australian-coins/collection/index.html', 'utf8')
  ok(/typical/.test(html) && /median/.test(html) && /not a valuation/.test(html),
     'the page explains the median measure and says a dot is not a valuation')
  ok(/cannot tell you which variety/.test(html) && /which mint struck yours/.test(html),
     'and says a dot speaks to neither the variety nor the mint')
}
await page.click('.denbtn[data-den="two-dollars"]')
await page.waitForTimeout(350)
{
  const dots = await page.$$eval('#grid .coin', els => els.map(e => {
    const d = e.querySelector('.bnd')
    return { band: d ? [...d.classList].find(c => c.startsWith('b-')) : null,
             m: Number((e.querySelector('.m')?.textContent || '').replace(/[^0-9]/g, '')) || null }
  }))
  const scarceMax = Math.max(...dots.filter(d => d.band === 'b-scarce').map(d => d.m))
  const ordMin = Math.min(...dots.filter(d => d.band === 'b-ordinary').map(d => d.m))
  ok(scarceMax < ordMin, `the dots run in mintage order within a denomination (scarce to ${scarceMax.toLocaleString()})`)
  ok((await page.$$eval('.key i', e => e.length)) === 3, 'the grid carries a key for all three dots')
}
// The photo credit is printed once even when both faces come from one museum record.
await page.click('.denbtn[data-den="halfpenny"]')
await page.waitForTimeout(300)
await page.evaluate(() => { location.hash = '#halfpenny/1946' })
await page.waitForTimeout(600)
{
  const cap = await page.evaluate(() => document.querySelector('.pfaces figcaption')?.innerText ?? '')
  const credits = cap.split('\n').filter(l => /Museums Victoria/.test(l))
  ok(credits.length === 1, `the photographer is credited once, not once per face (${credits.length})`)
  const txt = await page.evaluate(() => document.querySelector('#panel')?.innerText ?? '')
  ok(!/Each figure/i.test(txt), 'the panel does not print the figures twice under two headings')
  ok(!/struck-in-report-year during/.test(txt), 'and no schema slug reaches the panel')
}

// And the breakdown reaches the reader, not just the payload.
await page.click('.denbtn[data-den="halfpenny"]')
await page.waitForTimeout(350)
await page.evaluate(() => { location.hash = '#halfpenny/1946' })
await page.waitForTimeout(600)
{
  const txt = await page.evaluate(() => document.querySelector('#panel')?.innerText ?? '')
  ok(/187,200/.test(txt) && /13,560,000/.test(txt),
     'opening the 1946 halfpenny shows what each mint reported, which one figure hides')
  ok(/72(\.\d)?x/.test(txt), 'and says how far apart the two mints were')
}

ok(errors.length === 0, `no JavaScript errors on any page${errors.length ? ': ' + errors[0] : ''}`)

await browser.close(); srv.close()
console.log(`\n${pass} passed, ${fail} failed`)
process.exit(fail ? 1 : 0)
