// research/church-axes/verify-geom.mjs — the geometry engine, and the defect it exists
// to prevent.
//
// Run: node research/church-axes/verify-geom.mjs
//
// The central test is NEGATIVE and it is the reason this file was written before any
// census ran. Regular polygons have no long axis. A naive principal-axis solver does not
// say so; it returns the direction of the arithmetic's residual anisotropy, which is the
// same direction every time. This suite builds those shapes exactly, on OSM's real
// coordinate grid, at five latitudes, and requires the engine to REFUSE them — and it
// first demonstrates, with the admission test switched off, that the naive answer really
// is due east, so the test is guarding a live defect rather than an imagined one.

import {
  parseWkt, projector, covariance, principalAxis, measure, minAreaRectBearing,
  axialDiff, ewScore, ELONGATION_MIN,
} from './lib/geom.mjs'

let pass = 0, fail = 0
const failures = []
function ok (cond, msg, detail) {
  if (cond) { pass++ } else { fail++; failures.push(msg + (detail ? `  [${detail}]` : '')) }
}
function near (a, b, tol, msg) {
  ok(Math.abs(a - b) <= tol, msg, `got ${a}, want ${b} +/- ${tol}`)
}

const R = 6378137.0, DEG = Math.PI / 180
// Build a shape in METRES around (lon0,lat0) and write it to OSM's 1e-7 degree grid,
// which is what a real footprint is: quantised, not continuous.
function shapeWkt (lon0, lat0, ptsMetres, quantise = true) {
  const kx = Math.cos(lat0 * DEG) * R * DEG, ky = R * DEG
  const q = v => quantise ? Math.round(v * 1e7) / 1e7 : v
  const ring = ptsMetres.map(([x, y]) => [q(lon0 + x / kx), q(lat0 + y / ky)])
  ring.push(ring[0])
  return 'POLYGON((' + ring.map(([a, b]) => `${a} ${b}`).join(',') + '))'
}
function regularNgon (n, radius, rotDeg = 0) {
  const out = []
  for (let i = 0; i < n; i++) {
    const t = (i / n) * 2 * Math.PI + rotDeg * DEG
    out.push([radius * Math.cos(t), radius * Math.sin(t)])
  }
  return out
}
function rect (w, h, rotDeg = 0) {
  const c = Math.cos(rotDeg * DEG), s = Math.sin(rotDeg * DEG)
  return [[-w / 2, -h / 2], [w / 2, -h / 2], [w / 2, h / 2], [-w / 2, h / 2]]
    .map(([x, y]) => [x * c - y * s, x * s + y * c])
}

console.log('\n=== 1. WKT parsing ===')
ok(parseWkt('POINT(1 2)') === null, 'a POINT is not an areal geometry')
ok(parseWkt('LINESTRING(0 0,1 1)') === null, 'a LINESTRING is not an areal geometry')
{
  const g = parseWkt('POLYGON((0 0,1 0,1 1,0 1,0 0),(0.2 0.2,0.4 0.2,0.4 0.4,0.2 0.4,0.2 0.2))')
  ok(g && g.parts.length === 1, 'polygon parses to one part')
  ok(g && g.parts[0].length === 2, 'its hole is kept as a second ring')
  const mp = parseWkt('MULTIPOLYGON(((0 0,1 0,1 1,0 0)),((5 5,6 5,6 6,5 5)))')
  ok(mp && mp.parts.length === 2, 'multipolygon parses to two parts')
}

console.log('\n=== 2. Area and centroid against closed forms ===')
{
  // a 40 m x 10 m rectangle at the equator: area 400 m^2
  const w = 40, h = 10
  const wkt = shapeWkt(0, 0, rect(w, h), false)
  const g = parseWkt(wkt)
  const pr = projector(0, 0)
  const cov = covariance(g.parts.map(r => r.map(ring => ring.map(pr))))
  near(cov.area, w * h, 1e-3, 'rectangle area = w*h')
  near(cov.cx, 0, 1e-6, 'rectangle centroid x at origin')
  near(cov.cy, 0, 1e-6, 'rectangle centroid y at origin')
  // second moments of a rectangle about its centre: w^2/12 and h^2/12
  near(cov.mxx, w * w / 12, 1e-4, 'rectangle mxx = w^2/12')
  near(cov.myy, h * h / 12, 1e-4, 'rectangle myy = h^2/12')
  near(cov.mxy, 0, 1e-6, 'rectangle mxy = 0')
}
{
  // hole subtraction: a 40x40 square with a 20x20 hole has area 1200
  const kx = Math.cos(0) * R * DEG, ky = R * DEG
  const ring = (s) => rect(s, s).map(([x, y]) => `${x / kx} ${y / ky}`).concat([`${-s / 2 / kx} ${-s / 2 / ky}`]).join(',')
  const wkt = `POLYGON((${ring(40)}),(${ring(20)}))`
  const g = parseWkt(wkt)
  const pr = projector(0, 0)
  const cov = covariance(g.parts.map(r => r.map(rg => rg.map(pr))))
  near(cov.area, 1600 - 400, 1e-2, 'hole is subtracted from area')
}

console.log('\n=== 3. Known bearings are recovered ===')
for (const lat of [0, 13.4, 45, 51.5, -30]) {
  for (const want of [0, 22.5, 45, 67.5, 90, 112.5, 135, 157.5]) {
    // a 40x8 rectangle whose LONG side points along `want` degrees from north.
    // rect(w,h) has its long side along x (east), i.e. bearing 90; rotating the shape
    // by r degrees counterclockwise in the x-y plane moves the bearing to 90 - r.
    const r = 90 - want
    const wkt = shapeWkt(11.5, lat, rect(40, 8, r))
    const m = measure(wkt)
    ok(m.ok, `lat ${lat} bearing ${want}: admitted`, m.reason)
    if (m.ok) ok(axialDiff(m.bearing, want) < 0.5, `lat ${lat}: bearing ${want} recovered`, `got ${m.bearing.toFixed(3)}`)
  }
}

console.log('\n=== 4. THE DEFECT: without the admission test, degenerate shapes report due east ===')
// Reproduce the failure first, so the guard below is shown to be guarding something real.
let naiveEast = 0, naiveTotal = 0, naiveCardinal = 0
const naiveBearings = []
for (const lat of [13.4, 45.0, 51.5, -30.0, 8.0]) {
  for (const n of [4, 5, 22, 40, 0]) {   // 0 = circle (128-gon)
    const pts = n === 0 ? regularNgon(128, 12) : regularNgon(n, 12)
    const wkt = shapeWkt(11.5, lat, pts)
    const g = parseWkt(wkt)
    const pr = projector(11.5, lat)
    const cov = covariance(g.parts.map(r => r.map(ring => ring.map(pr))))
    const { bearing } = principalAxis(cov)
    naiveTotal++
    naiveBearings.push(bearing)
    if (axialDiff(bearing, 90) < 0.001) naiveEast++
    if (axialDiff(bearing, 90) < 0.001 || axialDiff(bearing, 0) < 0.001) naiveCardinal++
  }
}
console.log(`    naive principal axis on ${naiveTotal} regular polygons:`)
console.log(`      ${naiveCardinal} land EXACTLY on a cardinal direction (within 0.001 deg of 0/90/180)`)
console.log(`      of those, ${naiveEast} on due east-west and ${naiveCardinal - naiveEast} on due north-south`)
console.log(`      distinct bearings returned: ${[...new Set(naiveBearings.map(b => b.toFixed(3)))].join(', ')}`)
// The honest statement of the defect, and it is stronger than "they all go east". A shape
// with no axis is assigned one by the arithmetic, and the arithmetic's answer is always
// exactly cardinal. Which cardinal it picks does not rescue the census: the statistic is
// cos(2(theta-90)), so an east-west artifact scores +1 and a north-south one -1. They do
// not cancel in any principled way; they inject a bimodal spike at exactly the two
// bearings the study is trying to distinguish between.
ok(naiveCardinal === naiveTotal,
  'the defect reproduces: a naive solver assigns every degenerate shape an exactly cardinal axis',
  `${naiveCardinal}/${naiveTotal}`)
ok(naiveEast > 0 && naiveEast < naiveTotal,
  'and it splits between due east-west and due north-south, so it is not a constant offset',
  `${naiveEast} east of ${naiveTotal}`)

console.log('\n=== 5. THE GUARD: measure() refuses every one of them ===')
let refused = 0, seen = 0
for (const lat of [13.4, 45.0, 51.5, -30.0, 8.0]) {
  for (const n of [3, 4, 5, 6, 8, 12, 22, 40, 0]) {
    for (const rot of [0, 17]) {
      const pts = n === 0 ? regularNgon(128, 12) : regularNgon(n, 12, rot)
      const m = measure(shapeWkt(11.5, lat, pts))
      seen++
      if (!m.ok) refused++
      else failures.push(`ADMITTED a regular ${n || 'circle'}-gon at lat ${lat} rot ${rot}: bearing ${m.bearing.toFixed(3)}, elongation ${m.elongation.toFixed(4)}`)
    }
  }
}
ok(refused === seen, 'every regular polygon and circle is refused an axis', `${refused}/${seen}`)
console.log(`    ${refused} of ${seen} degenerate shapes refused`)

console.log('\n=== 6. The guard is not simply refusing everything (a control that can fail) ===')
{
  // Aspect ratios either side of the threshold. l1/l2 = r^2 for a rectangle, so
  // elongation = aspect ratio exactly.
  const admits = []
  for (const ar of [1.02, 1.05, 1.09, 1.11, 1.2, 1.5, 2, 4, 10]) {
    const m = measure(shapeWkt(11.5, 45, rect(10 * ar, 10, 30)))
    admits.push([ar, m.ok, m.ok ? m.elongation : m.reason])
  }
  for (const [ar, isOk, v] of admits) {
    if (ar < ELONGATION_MIN) ok(!isOk, `aspect ${ar} (< ${ELONGATION_MIN}) refused`, String(v))
    else {
      ok(isOk, `aspect ${ar} (>= ${ELONGATION_MIN}) admitted`, String(v))
      if (isOk) near(v, ar, 0.02, `aspect ${ar}: elongation equals the aspect ratio`)
    }
  }
}

console.log('\n=== 7. Engine B (minimum-area rectangle) agrees where both admit ===')
{
  let agree = 0, tried = 0
  for (const want of [0, 20, 40, 60, 80, 100, 120, 140, 160]) {
    const wkt = shapeWkt(2.35, 48.85, rect(50, 12, 90 - want))
    const a = measure(wkt), b = minAreaRectBearing(wkt)
    if (a.ok && b) { tried++; if (axialDiff(a.bearing, b.bearing) < 1.0) agree++ }
  }
  ok(tried === 9 && agree === 9, 'both engines agree on clearly elongated rectangles', `${agree}/${tried}`)
}
{
  // ...and the point of section 4: engine B is NOT an independent check on degeneracy.
  // State it as a measured fact so nobody later mistakes the cross-check for a guard.
  let bothEast = 0
  for (const n of [4, 8, 40]) {
    const wkt = shapeWkt(11.5, 45, regularNgon(n, 12))
    const b = minAreaRectBearing(wkt)
    const g = parseWkt(wkt); const pr = projector(11.5, 45)
    const naive = principalAxis(covariance(g.parts.map(r => r.map(ring => ring.map(pr))))).bearing
    if (b && axialDiff(naive, b.bearing) < 46) bothEast++
  }
  console.log(`    on ${3} regular polygons the two engines' naive answers are within 45 deg of each other in ${bothEast} cases`)
  console.log(`    (recorded to make the point: agreement between them is NOT evidence an axis exists)`)
}

console.log('\n=== 8. The east-west score ===')
near(ewScore(90), 1, 1e-12, 'due east-west scores +1')
near(ewScore(0), -1, 1e-12, 'due north-south scores -1')
near(ewScore(45), 0, 1e-12, 'a diagonal scores 0')
near(ewScore(135), 0, 1e-12, 'the other diagonal scores 0')
{
  // uniform bearings average to zero
  let s = 0, n = 3600
  for (let i = 0; i < n; i++) s += ewScore(i * 180 / n)
  near(s / n, 0, 1e-9, 'a uniform distribution of bearings scores 0 on average')
}

console.log('\n=== 9. Real specimens from the corpus ===')
{
  // Notre-Dame de Paris, OSM way 201611261, from the frozen extract. A cathedral that
  // genuinely is oriented, and long: the engine must admit it and put it near east-west.
  const fs = await import('node:fs')
  const path = '/home/liam/aw-claude-quenching-fermi-2b8e/.work/church/chunks'
  let found = 0, admitted = 0, refusedReal = 0
  const reasons = {}
  if (fs.existsSync(path)) {
    const files = fs.readdirSync(path).filter(f => f.endsWith('.tsv')).slice(0, 1)
    const lines = fs.readFileSync(path + '/' + files[0], 'utf8').split('\n').slice(1, 4001)
    for (const line of lines) {
      const t = line.split('\t')
      if (t.length < 3) continue
      found++
      const m = measure(t[2])
      if (m.ok) admitted++
      else { refusedReal++; reasons[m.reason] = (reasons[m.reason] || 0) + 1 }
    }
    console.log(`    ${found} real footprints: ${admitted} admitted, ${refusedReal} refused`)
    console.log(`    refusal reasons: ${JSON.stringify(reasons)}`)
    ok(found > 3000, 'read real footprints from the frozen extract', String(found))
    ok(admitted > found * 0.4, 'a healthy majority of real churches do have an axis', `${admitted}/${found}`)
    ok(refusedReal > 0, 'and some real churches are correctly refused one', String(refusedReal))
  } else {
    console.log('    (extract not present; skipped)')
  }
}

console.log(`\n${'='.repeat(60)}`)
console.log(`${pass} passed, ${fail} failed`)
if (failures.length) {
  console.log('\nFAILURES:')
  for (const f of failures.slice(0, 40)) console.log('  - ' + f)
}
process.exit(fail ? 1 : 0)
