// verify-skeleton.mjs: make the browser engine's straight skeleton agree with CGAL's.
//
// The page has to compute a straight skeleton live, in a browser, for a shape the reader
// draws, so the engine is ours. An engine that passes its own tests has told us nothing, so
// every skeleton here is also computed by CGAL 5.6 (oracle/skel.cpp, exact predicates, a
// completely separate implementation by other people) and the two are required to agree
// segment for segment.
//
//   node verify-skeleton.mjs            # the fixed cases
//   node verify-skeleton.mjs --random N # N pseudo-random simple polygons as well
//
// Run from research/one-straight-cut/.

import { execFileSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { straightSkeleton } from './skeleton.mjs';

const ORACLE = new URL('./oracle/skel', import.meta.url).pathname;
let pass = 0, fail = 0;
const failures = [];

function ok(cond, label, detail = '') {
  if (cond) { pass++; } else { fail++; failures.push(`${label}${detail ? ' :: ' + detail : ''}`); }
}

function cgal(rings) {
  const input = rings.map(r => r.map(p => `${p.x} ${p.y}`).join(' ')).join('\n') + '\n\n';
  const out = execFileSync(ORACLE, { input, encoding: 'utf8' });
  return out.trim().split('\n').filter(Boolean).map(line => {
    const f = line.split(/\s+/);
    return { a: { x: +f[0], y: +f[1] }, b: { x: +f[2], y: +f[3] }, ta: +f[4], tb: +f[5], kind: f[6] };
  // At a fully degenerate node (a tangential polygon, where every edge touches one inscribed
  // circle and the whole wavefront vanishes at a single instant) CGAL emits zero-length arcs
  // between coincident copies of that node. A zero-length segment is not a segment, and our
  // engine never emits one, so drop them on both sides rather than paper over the difference.
  }).filter(s => Math.hypot(s.a.x - s.b.x, s.a.y - s.b.y) > 1e-9);
}

// Compare two arc sets as unordered sets of undirected segments. Both implementations are
// free to report an arc's endpoints in either order, so orient each one canonically before
// comparing, and carry the arrival times through that same reordering - otherwise the time
// check silently compares one implementation's head against the other's tail.
function ends(seg, q = 1e4) {
  const r = (p) => `${Math.round(p.x * q)},${Math.round(p.y * q)}`;
  const A = { s: r(seg.a), t: seg.ta }, B = { s: r(seg.b), t: seg.tb };
  return A.s <= B.s ? [A, B] : [B, A];
}
function key(seg) { const [u, w] = ends(seg); return `${u.s}|${w.s}`; }

function compare(label, rings) {
  let mine, theirs;
  try { mine = straightSkeleton(rings).arcs; }
  catch (e) { ok(false, label, `engine threw: ${e.message}`); return; }
  try { theirs = cgal(rings); }
  catch (e) { ok(false, label, `oracle threw: ${e.message}`); return; }

  const A = new Map(), B = new Map();
  for (const s of mine) A.set(key(s), s);
  for (const s of theirs) B.set(key(s), s);

  const onlyMine = [...A.keys()].filter(k => !B.has(k));
  const onlyTheirs = [...B.keys()].filter(k => !A.has(k));
  ok(onlyMine.length === 0 && onlyTheirs.length === 0, `${label}: arcs match CGAL`,
     `engine ${mine.length} arcs, CGAL ${theirs.length}; engine-only ${onlyMine.length} (${onlyMine.slice(0, 3)}), CGAL-only ${onlyTheirs.length} (${onlyTheirs.slice(0, 3)})`);

  // Arrival times must agree too, not just the geometry.
  let worstT = 0;
  for (const [k, s] of A) {
    const o = B.get(k); if (!o) continue;
    const [s0, s1] = ends(s), [o0, o1] = ends(o);
    worstT = Math.max(worstT, Math.abs(s0.t - o0.t), Math.abs(s1.t - o1.t));
  }
  ok(worstT < 1e-6, `${label}: arrival times match CGAL`, `worst ${worstT.toExponential(2)} mm`);
}

// ── the fixed cases ────────────────────────────────────────────────────────────
const CASES = {
  'triangle': [[{ x: 0, y: 0 }, { x: 100, y: 0 }, { x: 50, y: 80 }]],
  'square': [[{ x: 0, y: 0 }, { x: 100, y: 0 }, { x: 100, y: 100 }, { x: 0, y: 100 }]],
  'rectangle': [[{ x: 0, y: 0 }, { x: 160, y: 0 }, { x: 160, y: 60 }, { x: 0, y: 60 }]],
  'L-shape (one reflex vertex)': [[
    { x: 0, y: 0 }, { x: 90, y: 0 }, { x: 90, y: 40 }, { x: 40, y: 40 }, { x: 40, y: 90 }, { x: 0, y: 90 }]],
  'plus (four reflex vertices)': [[
    { x: 30, y: 0 }, { x: 60, y: 0 }, { x: 60, y: 30 }, { x: 90, y: 30 }, { x: 90, y: 60 },
    { x: 60, y: 60 }, { x: 60, y: 90 }, { x: 30, y: 90 }, { x: 30, y: 60 }, { x: 0, y: 60 },
    { x: 0, y: 30 }, { x: 30, y: 30 }]],
  'square sheet with square hole': [
    [{ x: 0, y: 0 }, { x: 100, y: 0 }, { x: 100, y: 100 }, { x: 0, y: 100 }],
    [{ x: 35, y: 35 }, { x: 35, y: 65 }, { x: 65, y: 65 }, { x: 65, y: 35 }]],
  // The configuration the fold-and-cut construction actually asks for: a shape sitting in a
  // much larger sheet, off-centre, all edges axis-aligned. Four pinches fire at one instant
  // at four different points, and getting this wrong costs an entire skeleton arc. It did.
  'big box with an off-centre square hole': [
    [{ x: -20, y: -20 }, { x: 230, y: -20 }, { x: 230, y: 317 }, { x: -20, y: 317 }],
    [{ x: 70, y: 180 }, { x: 140, y: 180 }, { x: 140, y: 110 }, { x: 70, y: 110 }]],
  'big box with an off-centre triangular hole': [
    [{ x: -400, y: -400 }, { x: 610, y: -400 }, { x: 610, y: 697 }, { x: -400, y: 697 }],
    [{ x: 60, y: 100 }, { x: 60, y: 175 }, { x: 150, y: 100 }]],
  'sheet with triangular hole': [
    [{ x: 0, y: 0 }, { x: 120, y: 0 }, { x: 120, y: 90 }, { x: 0, y: 90 }],
    [{ x: 40, y: 30 }, { x: 40, y: 60 }, { x: 80, y: 45 }]],
};

// A five-pointed star: the Betsy Ross shape, ten vertices, five of them reflex.
function star(cx, cy, R, r, n = 5, phase = Math.PI / 2) {
  const pts = [];
  for (let i = 0; i < 2 * n; i++) {
    const ang = phase + (i * Math.PI) / n;
    const rad = i % 2 === 0 ? R : r;
    pts.push({ x: cx + rad * Math.cos(ang), y: cy + rad * Math.sin(ang) });
  }
  return pts;
}
// The classical pentagram outline is TANGENTIAL: all ten edges touch one inscribed circle,
// so the entire wavefront vanishes at the centre at a single instant. That is the worst
// degeneracy this algorithm meets, and it is also the shape a reader is most likely to draw.
CASES['five-pointed star (tangential, fully degenerate)'] =
  [star(60, 60, 50, 50 * Math.sin(Math.PI / 10) / Math.sin(7 * Math.PI / 10))];
CASES['five-pointed star (fat, non-degenerate)'] = [star(60, 60, 50, 30)];
CASES['five-pointed star (thin)'] = [star(60, 60, 50, 14)];
CASES['seven-pointed star'] = [star(60, 60, 50, 26, 7)];

// ── negative control ───────────────────────────────────────────────────────────
// A comparison that has never rejected anything is not evidence. Damage a known-good
// skeleton and require the same unmodified comparison to notice, once in the geometry and
// once in the arrival times, which are checked by separate code paths and can fail apart.
function selftest() {
  const rings = CASES['L-shape (one reflex vertex)'];
  const good = straightSkeleton(rings).arcs;
  const A = new Map(good.map(s => [key(s), s]));
  const B = new Map(cgal(rings).map(s => [key(s), s]));
  ok([...A.keys()].every(k => B.has(k)) && A.size === B.size, 'selftest: baseline agrees');

  const bent = good.map(s => ({ ...s, b: { x: s.b.x, y: s.b.y } }));
  bent[0].b.y += 0.1;                                     // 100 micron displacement
  const Bk = new Map(bent.map(s => [key(s), s]));
  ok([...Bk.keys()].some(k => !B.has(k)),
     'selftest: a 0.1 mm displaced arc is REJECTED (geometry check can fail)');

  const slow = good.map(s => ({ ...s }));
  slow[0].tb += 0.01;
  let worst = 0;
  for (const s of slow) { const o = B.get(key(s)); if (!o) continue;
    const [s0, s1] = ends(s), [o0, o1] = ends(o);
    worst = Math.max(worst, Math.abs(s0.t - o0.t), Math.abs(s1.t - o1.t)); }
  ok(worst >= 1e-6, 'selftest: a 0.01 mm arrival-time error is REJECTED (time check can fail)',
     `worst ${worst.toExponential(2)}`);
}

if (!existsSync(ORACLE)) {
  console.error(`verify-skeleton: oracle not built. Run:\n  g++ -O2 -o oracle/skel oracle/skel.cpp -lgmp -lmpfr`);
  process.exit(2);
}

selftest();
for (const [label, rings] of Object.entries(CASES)) compare(label, rings);

// ── pseudo-random simple polygons ──────────────────────────────────────────────
const nRandom = process.argv.includes('--random')
  ? Number(process.argv[process.argv.indexOf('--random') + 1] || 50) : 0;
if (nRandom) {
  let seed = 20260815;
  const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
  for (let i = 0; i < nRandom; i++) {
    // star-shaped about the centre, so it is simple by construction but often very reflex
    const n = 5 + Math.floor(rnd() * 10);
    const pts = [];
    for (let k = 0; k < n; k++) {
      const ang = (2 * Math.PI * k) / n;
      const rad = 20 + rnd() * 45;
      pts.push({ x: +(60 + rad * Math.cos(ang)).toFixed(4), y: +(60 + rad * Math.sin(ang)).toFixed(4) });
    }
    compare(`random #${i} (n=${n})`, [pts]);
  }
  // Sheets with a hole in them: the case the fold-and-cut construction actually needs,
  // where the hole's wavefront expands until it merges with the sheet's own.
  for (let i = 0; i < Math.ceil(nRandom / 2); i++) {
    const n = 3 + Math.floor(rnd() * 6);
    const hole = [];
    for (let k = n - 1; k >= 0; k--) {           // clockwise, as a hole must be
      const ang = (2 * Math.PI * k) / n + rnd() * 0.3;
      const rad = 8 + rnd() * 22;
      hole.push({ x: +(60 + rad * Math.cos(ang)).toFixed(4), y: +(45 + rad * Math.sin(ang)).toFixed(4) });
    }
    compare(`random hole #${i} (n=${n})`, [
      [{ x: 0, y: 0 }, { x: 120, y: 0 }, { x: 120, y: 90 }, { x: 0, y: 90 }], hole]);
  }
}

console.log(`\nverify-skeleton: ${pass} passed, ${fail} failed`);
for (const f of failures) console.log('  FAIL ' + f);
process.exit(fail ? 1 : 0);
