#!/usr/bin/env node
// Verifier for /strata/read-by-a-gloved-hand/
//
//   node verify-read-by-a-gloved-hand.mjs
//
// Four independent things, any one of which can fail the page.
//
//  A. The alphabet in moon.mjs is internally consistent: every letter has
//     a family key that appears in MOON_FAMILY; every path parses as
//     valid SVG-ish syntax; rotations are in {0, 90, 180, 270}; no two
//     letters share a path (the alphabet has 26 distinct glyphs).
//  B. The three family groupings really produce the numbers the page
//     claims (10 default, 7 Omeka, 6 Fakoo). And the "pre-rotation
//     forms" count reduces the alphabet to its family set (also 10).
//  C. The bundle the page SHIPS is rebuilt from moon.mjs +
//     moon-analyze.mjs and compared field by field against the JSON
//     block actually embedded in the HTML. Nothing hand-typed on the
//     page can drift from the code.
//  D. The paper-price arithmetic reproduces two independent ways. The
//     braille per-character area is NLS Spec 800; the Moon area is
//     from moon.mjs; the ratio the page prints must match both.
//
//  E. Controls that must fail, and do.

import { readFileSync, existsSync } from 'node:fs'
import { execSync } from 'node:child_process'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import {
  MOON_LETTERS, MOON_LETTER_ORDER, MOON_LETTER_COUNT,
  MOON_FAMILY, MOON_BASE_FAMILY_COUNT_DEFAULT,
  MOON_CELL_HEIGHT_IN, MOON_CELL_WIDTH_IN, MOON_LINE_PITCH_IN, MOON_CHAR_PITCH_IN,
  countBaseShapes, countDistinctFormsPreRotation, PUBLISHED_GROUPINGS,
} from './research/tactile-codes/moon.mjs'
import { NLS } from './research/tactile-codes/geometry.mjs'

const ROOT = path.dirname(fileURLToPath(import.meta.url))
const PAGE = path.join(ROOT, 'public', 'strata', 'read-by-a-gloved-hand', 'index.html')
const RES  = path.join(ROOT, 'research', 'tactile-codes')

let passed = 0, failed = 0
const ok = (name, cond, extra = '') => {
  if (cond) passed++; else failed++
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`)
}
const section = s => console.log(`\n── ${s} ${'─'.repeat(Math.max(0, 66 - s.length))}`)
const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps

const html = readFileSync(PAGE, 'utf8')

// ────────────────────────────────────────────────────────────────────────
section('A. the alphabet, internal consistency')

ok('26 letters',                MOON_LETTER_ORDER.length === 26, `${MOON_LETTER_ORDER.length}`)
ok('MOON_LETTER_COUNT is 26',   MOON_LETTER_COUNT === 26)
ok('order is A..Z',             MOON_LETTER_ORDER.join('') === 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')

const badFamily = MOON_LETTER_ORDER.filter(L => !MOON_FAMILY[MOON_LETTERS[L].family])
ok('every letter has a known family', badFamily.length === 0, badFamily.length ? `bad: ${badFamily.join(',')}` : '')

const validRots = new Set([0, 90, 180, 270])
const badRot = MOON_LETTER_ORDER.filter(L => !validRots.has(MOON_LETTERS[L].rotation))
ok('every rotation is 0/90/180/270', badRot.length === 0, badRot.length ? `bad: ${badRot.join(',')}` : '')

// SVG path sanity: must start with M and contain only allowed commands
const cmdRe = /^[MmLlHhVvQqCcAaZzTtSs0-9\s.,\-]+$/
const badPath = MOON_LETTER_ORDER.filter(L => {
  const p = MOON_LETTERS[L].path
  return !p.trim().startsWith('M') || !cmdRe.test(p)
})
ok('every path parses as SVG-ish', badPath.length === 0, badPath.length ? `bad: ${badPath.join(',')}` : '')

const uniquePaths = new Set(MOON_LETTER_ORDER.map(L => MOON_LETTERS[L].path))
ok('26 distinct glyphs (no accidental duplicates)', uniquePaths.size === 26, `${uniquePaths.size}`)

// The letter H is the only filled shape, per moon.mjs.
const filled = MOON_LETTER_ORDER.filter(L => MOON_LETTERS[L].filled)
ok('exactly one filled shape (H)', filled.length === 1 && filled[0] === 'H', filled.join(','))

// The four fourfold families (angle, ell, stemBow, arc) each carry
// exactly four letters and use each of the four rotations exactly once.
for (const fam of ['angle', 'ell', 'stemBow', 'arc']) {
  const members = MOON_LETTER_ORDER.filter(L => MOON_LETTERS[L].family === fam)
  const rots = new Set(members.map(L => MOON_LETTERS[L].rotation))
  ok(`family "${fam}" has 4 members and 4 distinct rotations`,
    members.length === 4 && rots.size === 4,
    `members ${members.join('')}, rots ${[...rots].sort((a,b)=>a-b).join('/')}`)
}

// ────────────────────────────────────────────────────────────────────────
section('B. base-shape counts under the three published groupings')

ok('default family count is 10',                        MOON_BASE_FAMILY_COUNT_DEFAULT === 10, `${MOON_BASE_FAMILY_COUNT_DEFAULT}`)
ok('Fakoo grouping reduces to 6',                       countBaseShapes(PUBLISHED_GROUPINGS.fakoo6) === 6)
ok('UVic Omeka / Classified Alphabet reduces to 7',     countBaseShapes(PUBLISHED_GROUPINGS.omeka7) === 7)
ok('pre-rotation-forms count reduces to 10',            countDistinctFormsPreRotation() === 10)

// A synthetic grouping that merges only stemBow with arc gives 9.
ok('a synthetic merge of stemBow into arc gives 9',
   countBaseShapes({ stemBow: 'arc' }) === 9)

// ────────────────────────────────────────────────────────────────────────
section('C. the bundle the page ships is rebuilt from source')

// Rebuild the bundle without touching disk beyond re-running the script.
execSync(`node ${path.join(RES, 'moon-build-page.mjs')}`, { stdio: 'ignore' })
const rebuilt = JSON.parse(readFileSync(path.join(RES, 'moon-page-data.json'), 'utf8'))

// Extract the bundle actually in the HTML.
const openTag = '<script id="moon-data" type="application/json">'
const closeTag = '</script>'
const i = html.indexOf(openTag)
const j = html.indexOf(closeTag, i)
ok('page contains the bundle anchor', i >= 0 && j > i)
const shipped = JSON.parse(html.slice(i + openTag.length, j))

ok('rebuilt and shipped bundles have same top-level keys',
   JSON.stringify(Object.keys(rebuilt).sort()) === JSON.stringify(Object.keys(shipped).sort()))
ok('rebuilt and shipped bundles have same 26 letters',
   JSON.stringify(Object.keys(rebuilt.letters).sort()) === JSON.stringify(Object.keys(shipped.letters).sort()))
ok('every letter path matches',
   MOON_LETTER_ORDER.every(L => rebuilt.letters[L].path === shipped.letters[L].path),
   'rebuilt vs shipped')
ok('geometry: brailleArea matches',   near(rebuilt.geom.brailleArea, shipped.geom.brailleArea))
ok('geometry: moonArea matches',      near(rebuilt.geom.moonArea, shipped.geom.moonArea))
ok('geometry: ratio matches',         near(rebuilt.geom.ratio, shipped.geom.ratio))
ok('counts.default matches',          rebuilt.counts.default === shipped.counts.default)
ok('counts.fakoo6 matches',           rebuilt.counts.fakoo6 === shipped.counts.fakoo6)
ok('counts.omeka7 matches',           rebuilt.counts.omeka7 === shipped.counts.omeka7)

// ────────────────────────────────────────────────────────────────────────
section('D. paper price reproduces two independent ways')

const brailleAreaHere = NLS.cellPitch * NLS.linePitch                 // 0.245 * 0.400 = 0.098
const moonAreaHere    = MOON_CHAR_PITCH_IN * MOON_LINE_PITCH_IN       // 0.35 * 0.60 = 0.210
const moonOneSided    = moonAreaHere * 2
const ratioHere       = moonOneSided / brailleAreaHere

ok('braille area per char is 0.098 in² (NLS Spec 800)',   near(brailleAreaHere, 0.098))
ok('moon area per char is 0.210 in² (two-sided; moon.mjs)', near(moonAreaHere, 0.210))
ok('moon one-sided area per char is 0.420 in² (interpoint parity)', near(moonOneSided, 0.420))
ok('ratio is 0.420 / 0.098 = 4.2857...',                   near(ratioHere, 0.420 / 0.098))
ok('shipped ratio matches this arithmetic',                near(shipped.geom.ratio, ratioHere))

// KJV Bible area.
const BIBLE_KJV_CHARS = 3_100_000
const bibleBraille_in2 = BIBLE_KJV_CHARS * brailleAreaHere
const bibleMoon_in2    = BIBLE_KJV_CHARS * moonOneSided
ok('KJV braille area works out (in²)',   near(bibleBraille_in2, shipped.geom.bibleBraille_ft2 * 144, 1))
ok('KJV Moon area works out (in²)',      near(bibleMoon_in2,    shipped.geom.bibleMoon_ft2    * 144, 1))
ok('shipped Bible ratio matches ratioHere', near(shipped.geom.ratio, bibleMoon_in2 / bibleBraille_in2))

// The 1858 Bible historical figures are held in the bundle.
ok('shipped bibleMoonPages is 5000',    shipped.geom.bibleMoonPages === 5000)
ok('shipped bibleMoonVolumes is 60',    shipped.geom.bibleMoonVolumes === 60)

// ────────────────────────────────────────────────────────────────────────
section('E. controls that must fail (and do)')

const control1 = countBaseShapes(PUBLISHED_GROUPINGS.fakoo6) !== 7   // must be true (fakoo6 is 6, not 7)
ok('CONTROL: fakoo6 grouping is not 7', control1)

const control2 = countBaseShapes({}) === MOON_BASE_FAMILY_COUNT_DEFAULT
ok('CONTROL: empty merge does not change the count', control2)

const control3 = uniquePaths.size !== 25    // the alphabet is not accidentally 25 letters
ok('CONTROL: alphabet is not 25 distinct glyphs', control3)

// The em-dash gate check: any em dash the page owns must be inside a
// blockquote (already exempted) or explicitly marked em-dash-ok.
const em = /—/g
const emCount = (html.match(em) || []).length
const okMarker = /em-dash-ok/g
const okMarks  = (html.match(okMarker) || []).length
ok('page carries no em dashes outside its explicitly marked quote lines',
   emCount <= okMarks, `em dashes ${emCount}, ok-marked lines ${okMarks}`)

// ────────────────────────────────────────────────────────────────────────

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