// verify.mjs, every claim the page makes, checked against the fold model and
// against independently known bibliographic facts. Run: node verify.mjs
import {
  sheet, foldTimes, legalFolds, paginate, formeLayout, spineEdges,
  chainDirection, markPosition, FORMATS,
  duodecimo,
} from './fold.mjs';
import { ATTESTED } from './attested.mjs';
import { matchesUnder } from './match.mjs';

let pass = 0, fail = 0;
const results = [];
function ok(name, cond, detail = '') {
  if (cond) { pass++; results.push(['PASS', name, detail]); }
  else { fail++; results.push(['FAIL', name, detail]); }
}

const DIRS = { 1: [false], 2: [false, false], 3: [false, false, false], 4: [false, false, false, false], 5: [false, false, false, false, false] };

// ---- 1. Every fold produces a legal, correctly numbered gathering -----------
for (let k = 1; k <= 5; k++) {
  const st = foldTimes(k, DIRS[k]);
  const pages = paginate(st);
  const n = 1 << k;
  ok(`${FORMATS[k].name}: ${2 * n} pages exactly once`,
    pages.length === 2 * n && new Set(pages.map((p) => p.page)).size === 2 * n);

  // conjugacy: leaf i pairs with leaf n+1-i, and pages 2i-1,2i sit on leaf i
  let conjOk = true;
  for (const p of pages) {
    if (p.leaf !== Math.ceil(p.page / 2)) conjOk = false;
    if (p.conjugate !== n + 1 - p.leaf) conjOk = false;
  }
  ok(`${FORMATS[k].name}: leaf/conjugate bookkeeping`, conjOk);

  ok(`${FORMATS[k].name}: spine survives on the left`, spineEdges(st).includes('left'));
}

// ---- 2. Forme sets match the published imposition schemes -------------------
// A page prints on the outer forme (the side carrying page 1) iff its number is
// 1 or 0 mod 4. This is the invariant every printer's grammar states.
for (let k = 1; k <= 5; k++) {
  const st = foldTimes(k, DIRS[k]);
  const L = formeLayout(st);
  const frontHas1 = L.front.flat().some((c) => c && c.page === 1);
  const outer = (frontHas1 ? L.front : L.back).flat().filter(Boolean).map((c) => c.page);
  const expected = [];
  for (let p = 1; p <= (1 << k) * 2; p++) if (p % 4 === 1 || p % 4 === 0) expected.push(p);
  ok(`${FORMATS[k].name}: outer forme = pages ≡ 0,1 mod 4`,
    JSON.stringify(outer.slice().sort((a, b) => a - b)) === JSON.stringify(expected),
    `{${outer.slice().sort((a, b) => a - b).join(',')}}`);
}

// ---- 3. Half the pages on every forme print upside down (k>=2) --------------
for (let k = 2; k <= 5; k++) {
  const st = foldTimes(k, DIRS[k]);
  const L = formeLayout(st);
  const inv = L.front.flat().filter(Boolean).filter((c) => c.inverted).length;
  const tot = L.front.flat().filter(Boolean).length;
  ok(`${FORMATS[k].name}: exactly half of each forme is inverted`, inv * 2 === tot, `${inv}/${tot}`);
}
// folio: nothing is inverted (a single fold never turns a page)
{
  const L = formeLayout(foldTimes(1, DIRS[1]));
  const anyInv = L.front.flat().filter(Boolean).some((c) => c.inverted);
  ok('folio: no page is inverted', !anyInv);
}

// ---- 4. Chain-line direction alternates 90° per fold ------------------------
// The bibliographer's first test. Independently known result:
//   folio vertical, quarto horizontal, octavo vertical, 16mo horizontal, 32mo vertical.
const expectedChain = { 1: 'vertical', 2: 'horizontal', 3: 'vertical', 4: 'horizontal', 5: 'vertical' };
for (let k = 1; k <= 5; k++) {
  const st = foldTimes(k, DIRS[k]);
  const dir = chainDirection(paginate(st)[0]);
  // every leaf must agree
  const allAgree = paginate(st).every((p) => chainDirection(p) === dir);
  ok(`${FORMATS[k].name}: chain lines ${expectedChain[k]}`, dir === expectedChain[k] && allAgree, dir);
}

// ---- 5. Watermark test: which leaf catches the mark -------------------------
// The mark sits at the centre of one half of the mould. Known facts:
//   folio , centred in one leaf (the whole half IS one leaf)
//   quarto, falls in the SPINE fold / gutter (the mould half is split by a fold)
//   octavo, driven into a CORNER of one leaf
// We verify the mark's position within its leaf moves toward an edge as k grows.
for (let k = 1; k <= 3; k++) {
  const st = foldTimes(k, DIRS[k]);
  const m = markPosition(st, { x: 0.25, y: 0.5 }); // centre of left half of sheet
  ok(`${FORMATS[k].name}: watermark lands in a leaf`, m !== null,
    m ? `leaf ${m.leaf} at (u=${m.u}, v=${m.v})` : 'lost');
}
// The exact landing places, against McKerrow's own words (An Introduction to
// Bibliography for Literary Students, 1928 corrected impression, pp. 166-7):
//   folio  "the watermark will now be in the middle of a leaf"
//   quarto "the watermark will be on its side in the centre of the inner margins"
//   octavo "the watermark will be found upright at the top of the inner margin"
// (u = 0 is the spine edge of the leaf, v = 1 its head.)
{
  const at = (k) => markPosition(foldTimes(k, DIRS[k]), { x: 0.25, y: 0.5 });
  const near = (a, b) => Math.abs(a - b) < 1e-9;
  const f = at(1), q = at(2), o = at(3);
  ok('folio: watermark in the middle of the leaf (McKerrow)',
    near(f.u, 0.5) && near(f.v, 0.5), `u=${f.u}, v=${f.v}`);
  ok('quarto: watermark in the centre of the inner margin (McKerrow)',
    near(q.u, 0) && near(q.v, 0.5), `u=${q.u}, v=${q.v}`);
  ok('octavo: watermark at the top of the inner margin (McKerrow)',
    near(o.u, 0) && near(o.v, 1), `u=${o.u}, v=${o.v}`);
}

// ---- 6. Count of legal fold sequences ---------------------------------------
// Every one of the 2^k lift-choices yields a valid spine-left gathering under
// the standard rule, differing only by mirror/rotation (all are attested variants).
for (let k = 1; k <= 4; k++) {
  ok(`${FORMATS[k].name}: all ${1 << k} lift-choices are legal gatherings`, legalFolds(k).length === (1 << k));
}

// ---- 7. Moxon's rule, 1683 ---------------------------------------------------
// "in the Twelves Volumn next the First Page stands the Twenty Fourth, 1 and 24
//  added makes 25 ... one more than the number of Pages in the whole Sheet."
//  (Moxon, Mechanick Exercises, 1683; De Vinne's 1896 literal reprint, vol. 2.)
// The geometric content: conjugate leaves lie side by side on the sheet, joined
// across the spine fold. So the page beside page 1 is the last page of the sheet.
function conjugatesAreNeighbours(st, label) {
  const pages = paginate(st);
  const n = st.stack.length;
  const total = 2 * n;
  const rectOf = new Map();
  for (const p of pages) rectOf.set(p.leaf, p.rect);
  let allAdjacent = true, allSum = true;
  for (let i = 1; i <= n / 2; i++) {
    const A = rectOf.get(i), B = rectOf.get(n + 1 - i);
    // share a full edge?
    const shareV = (Math.abs(A.x1 - B.x0) < 1e-9 || Math.abs(B.x1 - A.x0) < 1e-9)
      && Math.abs(A.y0 - B.y0) < 1e-9 && Math.abs(A.y1 - B.y1) < 1e-9;
    const shareH = (Math.abs(A.y1 - B.y0) < 1e-9 || Math.abs(B.y1 - A.y0) < 1e-9)
      && Math.abs(A.x0 - B.x0) < 1e-9 && Math.abs(A.x1 - B.x1) < 1e-9;
    if (!shareV && !shareH) allAdjacent = false;
    if ((2 * i - 1) + 2 * (n + 1 - i) !== total + 1) allSum = false;
  }
  ok(`${label}: conjugate leaves lie side by side on the sheet`, allAdjacent);
  ok(`${label}: pages across the spine fold sum to ${total + 1} (Moxon 1683)`, allSum);
}
for (let k = 1; k <= 4; k++) conjugatesAreNeighbours(foldTimes(k, DIRS[k]), FORMATS[k].name);

// ---- 8. The leaf proportion alternates ---------------------------------------
// Because hand-press sheets were not in the ratio 1 : root 2, the leaf shape
// alternates between two proportions. Folio and octavo share one; quarto and
// 16mo share the other, and it is squarer. Carter & Barker, ABC for Book
// Collectors, 8th ed., FORMAT: a quarto is "essentially squarish in shape".
{
  const ratio = (k) => { const s = foldTimes(k, DIRS[k]); return s.H / s.W; };
  const r1 = ratio(1), r2 = ratio(2), r3 = ratio(3), r4 = ratio(4);
  ok('folio and octavo share a leaf proportion', Math.abs(r1 - r3) < 1e-9, r1.toFixed(3));
  ok('quarto and 16mo share the other', Math.abs(r2 - r4) < 1e-9, r2.toFixed(3));
  ok('the quarto proportion is the squarer of the two', r2 < r1, `${r2.toFixed(3)} < ${r1.toFixed(3)}`);
}

// ---- 9. Duodecimo: where halving stops and cutting begins --------------------
// Checked against Gaskell 1972 fig. 55, "Sheet of common duodecimo, or twelves".
{
  const { gathering, offcut } = duodecimo();
  const pages = paginate(gathering);
  const n = gathering.stack.length;
  ok('duodecimo: twelve leaves, twenty-four pages', n === 12 && pages.length === 24);
  ok('duodecimo: the spine still survives on the left', spineEdges(gathering).includes('left'));

  // the offcut carries leaves 5-8, i.e. pages 9-16, and is inset in the middle
  // sheet coordinates are the unit square; the cut falls at x = 2/3
  const off = pages.filter((p) => ((p.rect.x0 + p.rect.x1) / 2) > (2 / 3))
    .map((p) => p.page).sort((a, b) => a - b);
  ok('duodecimo: the offcut third carries pages 9 to 16 (leaves 5 to 8)',
    JSON.stringify(off) === JSON.stringify([9, 10, 11, 12, 13, 14, 15, 16]), `{${off.join(',')}}`);

  // the forme set matches Gaskell fig. 55 exactly
  const p1side = pages.find((p) => p.page === 1).side;
  const outer = pages.filter((p) => p.side === p1side).map((p) => p.page).sort((a, b) => a - b);
  ok('duodecimo: outer forme = Gaskell fig. 55 set',
    JSON.stringify(outer) === JSON.stringify([1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24]),
    `{${outer.join(',')}}`);

  // chain lines horizontal (Goucher/Rare Book School: "The chain lines will be horizontal")
  const dir = chainDirection(pages[0]);
  ok('duodecimo: chain lines horizontal', dir === 'horizontal'
    && pages.every((p) => chainDirection(p) === dir), dir);

  // and the leaf is the tall narrow shape a duodecimo is known for
  ok('duodecimo: leaf is taller and narrower than an octavo leaf',
    gathering.H / gathering.W > foldTimes(3, DIRS[3]).H / foldTimes(3, DIRS[3]).W,
    (gathering.H / gathering.W).toFixed(3));

  // the offcut alone is a four-leaf quire
  ok('duodecimo: the offcut folds into a four-leaf quire', offcut.stack.length === 4);
}

// ---- 10. Against the grids the hand-press manuals actually print -------------
// Transcribed from page images in attested.mjs: Moxon 1683 (plates 26-27),
// Smith 1755, Cowie 1830, De Vinne 1904. This is the strongest check here, because
// it compares every cell, page number AND inversion, against four printed sources
// spanning 1683 to 1904.
//
// The one subtlety, and it is a real one rather than a fudge: WHICH ROW READS
// UPSIDE DOWN IS NOT A FACT ABOUT THE FOLD. Turn the sheet round on the stone and
// the inverted row becomes the upright one. So a forme diagram's inversion pattern
// is fixed by the orientation the manual draws it in ("with the Foots of the Pages
// towards you", says Moxon), not by the geometry. We therefore compare up to sheet
// orientation, and check separately that the PAGE POSITIONS match on the nose.
{
  const NAMES = { 1: 'folio', 2: 'quarto', 3: 'octavo', 4: 'sixteenmo' };
  for (let k = 1; k <= 4; k++) {
    const A = ATTESTED[NAMES[k]];
    const hits = [];
    for (const v of ['direct', 'flipH', 'flipV', 'rot180']) hits.push(...matchesUnder(k, v).map((h) => ({ ...h, v })));
    ok(`${NAMES[k]}: outer forme matches the printed manuals, cell for cell, up to sheet orientation`,
      hits.length > 0, hits.length ? `${hits.length} folding(s), view=${[...new Set(hits.map((h) => h.v))].join('/')}` : 'none');
    ok(`${NAMES[k]}: and the inner forme matches an attested variant too`,
      hits.some((h) => h.innerMatch !== 'none'),
      [...new Set(hits.filter((h) => h.innerMatch !== 'none').map((h) => 'Variant ' + h.innerMatch))].join(', '));
  }
  // The flip needed is decided by the parity of the fold count, which is exactly
  // what the alternating quarter-turn between folds predicts.
  const viewFor = (k) => [...new Set(['direct', 'flipH', 'flipV', 'rot180']
    .filter((v) => matchesUnder(k, v).length > 0))];
  const odd = [...viewFor(1), ...viewFor(3)], even = [...viewFor(2), ...viewFor(4)];
  ok('odd fold counts (folio, octavo) share one diagram orientation',
    odd.length === 2 && odd[0] === odd[1], odd.join(','));
  ok('even fold counts (quarto, 16mo) share the other',
    even.length === 2 && even[0] === even[1], even.join(','));
  ok('and the two orientations differ, exactly as the alternating quarter-turn predicts',
    odd[0] !== even[0], `${odd[0]} vs ${even[0]}`);
}

// ---- report -----------------------------------------------------------------
for (const [s, name, detail] of results) {
  console.log(`${s === 'PASS' ? ' ok ' : 'FAIL'}  ${name}${detail ? '   [' + detail + ']' : ''}`);
}
console.log(`\n${pass}/${pass + fail} checks passed.`);
process.exit(fail === 0 ? 0 : 1);
