#!/usr/bin/env node
// verify-melt.mjs — drive the metal calculator and check its arithmetic against the statute.
//
// The numbers on this page are the ones a reader will act on, so they are checked against the
// Acts independently rather than against the page's own data file.

import { chromium } from 'playwright'
import { pathToFileURL } from 'node:url'
import { resolve } from 'node:path'

const PAGE = pathToFileURL(resolve('public/tools/australian-coins/what-metal-is-in-it/index.html')).href
let pass = 0, fail = 0
const ok = (c, m) => { if (c) { pass++; console.log('  ok   ' + m) } else { fail++; console.log('  FAIL ' + m) } }
const near = (a, b, tol) => Math.abs(a - b) <= tol

// Computed here from the statutes, NOT read from the page's data, so the two can disagree.
const TROY = 31.1034768
const GRAIN = 0.06479891
const EXPECT = {
  // Coinage Act 1936 schedule: florin 11.31036 g, thirty-seven fortieths fine silver
  florin_sterling: 11.31036 * 37 / 40,
  // Coinage Act 1947 schedule: same weight, one-half fine
  florin_half: 11.31036 * 0.5,
  // Currency Act 1965: fifty cents 205 grains, four-fifths fine silver
  fifty_1966: 205 * GRAIN * 0.8,
  // Coinage Act 1870: sovereign 7.98805 g at millesimal 916.66
  sovereign: 7.98805 * 916.66 / 1000,
}

const browser = await chromium.launch()
const page = await browser.newPage()
const errs = []
page.on('pageerror', e => errs.push(String(e)))
await page.goto(PAGE, { waitUntil: 'domcontentloaded' })

const options = await page.locator('#coin option').allTextContents()
ok(options.length >= 10, `${options.length} bullion specifications offered`)

async function pick (match) {
  const idx = options.findIndex(o => match.every(m => o.includes(m)))
  if (idx < 0) return null
  await page.selectOption('#coin', { index: idx })
  await page.waitForTimeout(90)
  return (await page.textContent('#result')) + ' || ' + (await page.textContent('#provenance'))
}

console.log('the fine metal weights match the statutes')
let t = await pick(['Fifty cents', 'silver'])
ok(t !== null, 'the 1966 silver fifty cents is offered')
ok(t.includes(EXPECT.fifty_1966.toFixed(4)), `1966 fifty cents shows ${EXPECT.fifty_1966.toFixed(4)} g fine silver`)

t = await pick(['Sovereign'])
ok(t.includes(EXPECT.sovereign.toFixed(4)), `sovereign shows ${EXPECT.sovereign.toFixed(4)} g fine gold`)
ok(/two statements do not agree/i.test(t), 'the sovereign page warns that the Act states its standard two ways')

console.log('\nquantity and price arithmetic')
await page.fill('#qty', '20')
await page.fill('#spot', '100')
await page.waitForTimeout(90)
const res = await page.textContent('#result')
const ozt = EXPECT.sovereign / TROY * 20
ok(res.includes((EXPECT.sovereign * 20).toFixed(4)), `20 sovereigns show ${(EXPECT.sovereign * 20).toFixed(4)} g`)
const shown = Number((res.match(/\$([\d,]+\.\d\d)/) ?? [])[1]?.replace(/,/g, ''))
ok(near(shown, ozt * 100, 0.02), `20 sovereigns at 100/ozt reads ${shown}, expected ${(ozt * 100).toFixed(2)}`)

console.log('\nit refuses to invent a price')
await page.fill('#spot', '')
await page.waitForTimeout(90)
const empty = await page.textContent('#result')
ok(/does not supply one/i.test(empty), 'with no price entered, the page says it will not supply one')
ok(!/\$/.test(empty), 'and shows no currency figure at all')

const body = await page.textContent('body')
ok(/will not tell you what your coin is worth/i.test(body), 'the page states plainly that metal value is not market value')
ok(/lost metal to wear/i.test(body), 'and that a circulated coin no longer weighs the statutory standard')
ok(errs.length === 0, `script errors: ${errs.slice(0, 2).join(' | ') || 'none'}`)

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