// verify-foldcut.mjs: does the crease pattern this page prints actually work?
//
// The wave that built this project's printable instruments learned its hardest lesson from a
// sheet with 441,475 passing assertions that printed 6 where it should have printed 56: every
// assertion tested arithmetic, and not one asked whether the SHEET produced the answer. So
// the assertions here are about the artifact. For every shape:
//
//   1. fold the simulated sheet by composing one reflection per crease,
//   2. check the whole cut pattern lands on one line and nothing else does,
//   3. pull the blade's line back through each face's own isometry and look at where the
//      scissors actually travel across the unfolded paper,
//   4. require that path to be the shape's outline, in millimetres.
//
// Step 3 never consults the shape. It asks the folded state where the blade lands and then
// measures what it drew, so a crease pattern that folds beautifully and cuts out the wrong
// thing fails here rather than passing quietly.
//
//   node verify-foldcut.mjs [--random N] [--verbose]

import { buildPattern, foldAndCertify, bladePreimage } from './foldcut.mjs';

const VERBOSE = process.argv.includes('--verbose');
let pass = 0, fail = 0;
const failures = [];
const ok = (c, label, detail = '') => { if (c) pass++; else { fail++; failures.push(`${label}${detail ? ' :: ' + detail : ''}`); } };

const SHEET = { w: 210, h: 297 };                      // A4 portrait, millimetres

function star(cx, cy, R, r, n = 5, phase = Math.PI / 2) {
  const p = [];
  for (let i = 0; i < 2 * n; i++) {
    const a = phase + (i * Math.PI) / n, rad = i % 2 === 0 ? R : r;
    p.push({ x: cx + rad * Math.cos(a), y: cy + rad * Math.sin(a) });
  }
  return p;
}
const reg = (cx, cy, R, n, phase = Math.PI / 2) =>
  Array.from({ length: n }, (_, i) => ({ x: cx + R * Math.cos(phase + 2 * Math.PI * i / n), y: cy + R * Math.sin(phase + 2 * Math.PI * i / n) }));

const CASES = {
  'triangle': [[{ x: 60, y: 100 }, { x: 150, y: 100 }, { x: 105, y: 175 }]],
  'square': [[{ x: 70, y: 110 }, { x: 140, y: 110 }, { x: 140, y: 180 }, { x: 70, y: 180 }]],
  'thin rectangle': [[{ x: 45, y: 130 }, { x: 165, y: 130 }, { x: 165, y: 165 }, { x: 45, y: 165 }]],
  'regular pentagon': [reg(105, 148, 55, 5)],
  'regular hexagon': [reg(105, 148, 55, 6)],
  'L-shape': [[{ x: 60, y: 100 }, { x: 150, y: 100 }, { x: 150, y: 140 }, { x: 100, y: 140 }, { x: 100, y: 190 }, { x: 60, y: 190 }]],
  'plus': [[{ x: 85, y: 100 }, { x: 125, y: 100 }, { x: 125, y: 130 }, { x: 155, y: 130 }, { x: 155, y: 170 },
    { x: 125, y: 170 }, { x: 125, y: 200 }, { x: 85, y: 200 }, { x: 85, y: 170 }, { x: 55, y: 170 },
    { x: 55, y: 130 }, { x: 85, y: 130 }]],
  'five-pointed star (Betsy Ross)': [star(105, 148, 60, 60 * Math.sin(Math.PI / 10) / Math.sin(7 * Math.PI / 10))],
  'five-pointed star (fat)': [star(105, 148, 60, 34)],
  'five-pointed star (thin)': [star(105, 148, 60, 17)],
  'six-pointed star': [star(105, 148, 60, 34, 6)],
  'two disjoint triangles': [
    [{ x: 40, y: 90 }, { x: 95, y: 90 }, { x: 67, y: 140 }],
    [{ x: 115, y: 160 }, { x: 175, y: 160 }, { x: 145, y: 215 }]],
  'letter T': [[{ x: 60, y: 100 }, { x: 150, y: 100 }, { x: 150, y: 130 }, { x: 120, y: 130 },
    { x: 120, y: 200 }, { x: 90, y: 200 }, { x: 90, y: 130 }, { x: 60, y: 130 }]],
};

function run(label, shapes) {
  let pat, rep, blade;
  const t0 = Date.now();
  try { pat = buildPattern(SHEET, shapes); }
  catch (e) { ok(false, label, `build threw: ${e.message}`); return null; }
  try { rep = foldAndCertify(pat); }
  catch (e) { ok(false, label, `fold threw: ${e.message}`); return null; }
  try { blade = bladePreimage(pat, rep); }
  catch (e) { ok(false, label, `blade threw: ${e.message}`); return null; }
  const ms = Date.now() - t0;

  ok(rep.ok, `${label}: certifies`, rep.reasons.join('; '));
  ok(rep.worstConsistency < 1e-6, `${label}: fold is single-valued`, `${rep.worstConsistency.toExponential(2)}`);
  ok(rep.worstOnLine < 1e-6, `${label}: every cut edge lands on the cut line`, `${rep.worstOnLine.toExponential(2)} mm`);
  ok(rep.strayOnLine === 0, `${label}: nothing else lands on the cut line`, `${rep.strayOnLine} strays`);
  ok(blade.worst < 1e-6, `${label}: the blade's path IS the outline`, `worst ${blade.worst.toExponential(2)} mm`);

  if (VERBOSE) console.log(`  ${label.padEnd(34)} ${String(rep.creases).padStart(4)} creases  ${String(rep.faces).padStart(4)} faces  ${String(rep.layersAtCut).padStart(3)} layers  ${String(ms).padStart(5)} ms  ${rep.ok ? 'CERTIFIED' : 'REFUSED: ' + rep.reasons[0]}`);
  return { pat, rep, blade };
}

// ── negative controls ─────────────────────────────────────────────────────────
// Three ways to break a working pattern, each of which a different check must catch. A
// certificate that has never refused anything is not a certificate.
function controls() {
  const shapes = CASES['L-shape'];
  const good = buildPattern(SHEET, shapes);
  ok(foldAndCertify(good).ok, 'control: the undamaged L-shape certifies');

  // (a) rotate one crease by half a degree
  const bent = { ...good, segs: good.segs.map(s => ({ ...s })) };
  const i = bent.segs.findIndex(s => s.role === 'skeleton');
  const s = bent.segs[i], mx = (s.a.x + s.b.x) / 2, my = (s.a.y + s.b.y) / 2, th = 0.5 * Math.PI / 180;
  const rot = (p) => ({ x: mx + (p.x - mx) * Math.cos(th) - (p.y - my) * Math.sin(th), y: my + (p.x - mx) * Math.sin(th) + (p.y - my) * Math.cos(th) });
  bent.segs[i] = { ...s, a: rot(s.a), b: rot(s.b) };
  ok(!foldAndCertify(bent).ok, 'control: a crease rotated by 0.5 deg is REFUSED');

  // (b) delete one perpendicular, which is the loose-end failure our first build shipped
  const short = { ...good, segs: good.segs.filter((x, k) => !(x.role === 'perp' && k === good.segs.findIndex(y => y.role === 'perp'))) };
  ok(!foldAndCertify(short).ok, 'control: a missing perpendicular crease is REFUSED');

  // (c) treat a cut edge as a fold, which folds correctly and cuts out nothing
  const welded = { ...good, segs: good.segs.map(x => x.role === 'cut' ? { ...x, role: 'skeleton' } : x) };
  const wr = foldAndCertify(welded);
  const wb = bladePreimage(welded, wr);
  ok(!wr.ok || wb.worst > 1e-6 || wb.segments.length === 0,
     'control: folding ALONG the outline instead of across it is REFUSED',
     `ok=${wr.ok} bladeWorst=${wb.worst.toExponential(2)} segs=${wb.segments.length}`);
}

controls();
if (VERBOSE) console.log('');
const results = {};
for (const [label, shapes] of Object.entries(CASES)) results[label] = run(label, shapes);

// ── how often does this construction actually certify? ────────────────────────
const nRandom = process.argv.includes('--random') ? Number(process.argv[process.argv.indexOf('--random') + 1] || 100) : 0;
if (nRandom) {
  let seed = 20260815, certified = 0, refused = 0;
  const reasons = new Map();
  const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
  for (let i = 0; i < nRandom; i++) {
    const n = 3 + Math.floor(rnd() * 12);
    const pts = [];
    for (let k = 0; k < n; k++) {
      const ang = (2 * Math.PI * k) / n;
      const rad = 18 + rnd() * 55;
      pts.push({ x: +(105 + rad * Math.cos(ang)).toFixed(3), y: +(148 + rad * Math.sin(ang)).toFixed(3) });
    }
    try {
      const pat = buildPattern(SHEET, [pts]);
      const rep = foldAndCertify(pat);
      const blade = bladePreimage(pat, rep);
      if (rep.ok && blade.worst < 1e-6) certified++;
      else { refused++; const r = rep.reasons[0] || `blade off by ${blade.worst.toExponential(2)} mm`; reasons.set(r.replace(/-?\d[\d.]*(e[+-]?\d+)?/gi, "N"), (reasons.get(r.replace(/-?\d[\d.]*(e[+-]?\d+)?/gi, "N")) || 0) + 1); }
    } catch (e) { refused++; reasons.set('threw: ' + e.message, (reasons.get('threw: ' + e.message) || 0) + 1); }
  }
  console.log(`\nrandom polygons: ${certified}/${nRandom} certified, ${refused} refused`);
  for (const [r, c] of [...reasons.entries()].sort((a, b) => b[1] - a[1])) console.log(`   ${String(c).padStart(4)}  ${r}`);
}

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