#!/usr/bin/env node
// verify-the-four-names-that-were-not-enough.mjs
//
// Every load-bearing claim on /strata/the-four-names-that-were-not-enough/ , checked.
// Run: node research/kinship-algebra/verify-the-four-names-that-were-not-enough.mjs
//
// The rule this file exists to keep: nothing on the page is asserted about a section
// system that is not COMPUTED here from a table transcribed out of a named published
// source. The tables are in systems.json with their citations. If a table were mistyped
// the algebra would almost certainly stop closing, and these checks would go red.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import E, {
  makeSystem, identifyGroup, isRegular, isTransitive, permOrder, cycles,
  compose, inverse, permEq, idPerm, pathMap, crossCousinPath, fixedPoints,
} from './engine.mjs';
import { census, crossCousinDegree } from './census.mjs';
import { enumeratePaths, inSpouseCategory, collisionProfile } from './paths.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const data = JSON.parse(fs.readFileSync(path.join(HERE, 'systems.json'), 'utf8'));
const SYS = Object.fromEntries(data.systems.map((s) => [s.id, makeSystem(s)]));
const SPEC = Object.fromEntries(data.systems.map((s) => [s.id, s]));

let pass = 0, fail = 0;
const failures = [];
function check(name, cond, detail) {
  if (cond) { pass++; console.log(`  ok   ${name}`); }
  else { fail++; failures.push(name); console.log(`  FAIL ${name}${detail ? '  -> ' + detail : ''}`); }
}
function section(t) { console.log(`\n${t}`); }

// ---------------------------------------------------------------------------
section('1. The transcribed tables are internally coherent as marriage systems');

for (const spec of data.systems) {
  const sys = SYS[spec.id];
  check(`${spec.id}: no structural problems in the transcribed table`, sys.problems.length === 0, sys.problems.join('; '));
  check(`${spec.id}: marriage is symmetric and nobody marries their own category`,
    permEq(compose(sys.w, sys.w), idPerm(sys.n)) && fixedPoints(sys.w).length === 0);

  // the source gives father/mother/child triples; rebuild them from w and m and compare
  const rebuilt = spec.sourceTable.map((r) => {
    const mi = sys.indexOf(r.mother);
    return { father: sys.nameOf(sys.w[mi]), mother: r.mother, child: sys.nameOf(sys.m[mi]) };
  });
  const same = spec.sourceTable.every((r, i) =>
    rebuilt[i].father === r.father && rebuilt[i].child === r.child);
  check(`${spec.id}: every father/mother/child row in the source is reproduced by the two maps`, same,
    JSON.stringify(rebuilt));
}

// ---------------------------------------------------------------------------
section('2. Kariera (Brown 1913): four sections, and the algebra the paper describes in words');

{
  const k = SYS['kariera-1913'];
  const g = identifyGroup(k.group);
  check('Kariera: the group generated by marriage and descent has order 4', g.order === 4);
  check('Kariera: it is commutative', g.abelian === true);
  check('Kariera: it is the Klein four-group', /Klein/.test(g.name || ''), g.name);
  check('Kariera: the action on the four sections is regular', isRegular(k.group) === true);

  // Brown names the cycles and couples in prose; check ours are his
  const matri = cycles(k.m).map((c) => c.map((i) => k.nameOf(i)).sort().join('+')).sort();
  check('Kariera: the matrilineal cycles are {Banaka,Karimera} and {Burung,Palyeri}, as Brown states',
    JSON.stringify(matri) === JSON.stringify(['Banaka+Karimera', 'Burung+Palyeri']), JSON.stringify(matri));
  const patri = cycles(k.p).map((c) => c.map((i) => k.nameOf(i)).sort().join('+')).sort();
  check('Kariera: the patrilineal couples are {Banaka,Palyeri} and {Burung,Karimera}, as Brown states',
    JSON.stringify(patri) === JSON.stringify(['Banaka+Palyeri', 'Burung+Karimera']), JSON.stringify(patri));

  check('Kariera: a mother and her children are in the same cycle but not the same section',
    k.sections.every((_, i) => k.m[i] !== i));
  check('Kariera: the first cross-cousin (MBD) is in the section a person must marry',
    permEq(pathMap(k, 'MBD'), k.w));
  check('Kariera: the mother\'s brother\'s daughter and the father\'s sister\'s daughter share a section',
    permEq(pathMap(k, 'MBD'), pathMap(k, 'FZD')));
  check('Kariera: a person\'s father\'s father is in their own section', permEq(pathMap(k, 'FF'), idPerm(4)));
  check('Kariera: a person\'s mother\'s mother is in their own section', permEq(pathMap(k, 'MM'), idPerm(4)));
  check('Kariera: the least k for which the k-th cross-cousin is the prescribed spouse is 1',
    crossCousinDegree(k.w, k.m) === 1);
}

// ---------------------------------------------------------------------------
section('3. Arunta (Spencer & Gillen 1899): eight subsections');

{
  const a = SYS['arunta-1899'];
  const g = identifyGroup(a.group);
  check('Arunta 8: the group generated by marriage and descent has order 8', g.order === 8);
  check('Arunta 8: it is NOT commutative', g.abelian === false);
  check('Arunta 8: it is D4, the symmetry group of a square', /^D4/.test(g.name || ''), g.name);
  check('Arunta 8: the action on the eight subsections is regular', isRegular(a.group) === true);
  check('Arunta 8: the matrilineal cycles have length 4', permOrder(a.m) === 4);
  check('Arunta 8: there are exactly two matrilineal cycles', cycles(a.m).length === 2);
  check('Arunta 8: a man\'s son\'s son is back in his own subsection (patrilineal couples)',
    permEq(compose(a.p, a.p), idPerm(8)));
  check('Arunta 8: there are exactly four patrilineal couples', cycles(a.p).length === 4);

  check('Arunta 8: the FIRST cross-cousin is NOT in the prescribed spouse\'s subsection',
    !permEq(pathMap(a, 'MBD'), a.w));
  check('Arunta 8: the SECOND cross-cousin IS in the prescribed spouse\'s subsection',
    permEq(pathMap(a, 'MMBDD'), a.w));
  check('Arunta 8: the least k for which the k-th cross-cousin is the prescribed spouse is 2',
    crossCousinDegree(a.w, a.m) === 2);

  // The anthropological literature lists four second-cousin types as the Aranda-type
  // marriage. They are named independently of this algebra; all four must land on the
  // spouse's subsection, and they do.
  for (const p of ['MMBDD', 'MFZDD', 'FFZSD', 'FMBSD'])
    check(`Arunta 8: the published second-cousin type ${p} lands in the spouse's subsection`,
      permEq(pathMap(a, p), a.w));

  check('Arunta 8: a person\'s father\'s father is in their own subsection', permEq(pathMap(a, 'FF'), idPerm(8)));
  check('Arunta 8: a person\'s mother\'s mother is NOT in their own subsection', !permEq(pathMap(a, 'MM'), idPerm(8)));
  check('Arunta 8: a person\'s mother\'s mother\'s mother\'s mother IS in their own subsection',
    permEq(pathMap(a, 'MMMM'), idPerm(8)));
}

// ---------------------------------------------------------------------------
section('4. The two Arunta tables in the same 1899 book are consistent with each other');

{
  const a8 = SYS['arunta-1899'];
  const a4 = SYS['arunta-four-1899'];
  const pairs = SPEC['arunta-1899'].refines.pairs;
  // phi: eight subsections -> four sections, using Spencer & Gillen's own pairing
  const phi = new Array(8);
  for (const [four, eight] of Object.entries(pairs))
    for (const sub of eight) phi[a8.indexOf(sub)] = a4.indexOf(four);
  check('the pairing covers all eight subsections exactly once', phi.every((v) => Number.isInteger(v)) && new Set(phi).size === 4);

  const commutesW = a8.sections.every((_, i) => phi[a8.w[i]] === a4.w[phi[i]]);
  const commutesM = a8.sections.every((_, i) => phi[a8.m[i]] === a4.m[phi[i]]);
  check('collapsing the eight onto the four turns the eight-subsection marriage rule into the four-section one', commutesW);
  check('collapsing the eight onto the four turns the eight-subsection descent rule into the four-section one', commutesM);

  // the fibres of phi are exactly the orbits of m-squared, which generates the centre of D4
  const m2 = compose(a8.m, a8.m);
  const fibresAreM2 = a8.sections.every((_, i) => phi[m2[i]] === phi[i]) && a8.sections.every((_, i) => m2[i] !== i);
  check('the pairs Spencer and Gillen describe are exactly the orbits of "mother\'s mother"', fibresAreM2);

  // ... and m^2 is central in the group
  const centre = a8.group.elems.filter((x) => a8.group.elems.every((y) => permEq(compose(x, y), compose(y, x))));
  check('the centre of the eight-subsection group has exactly two elements', centre.length === 2, String(centre.length));
  check('"mother\'s mother" is the non-identity element of that centre',
    centre.some((x) => permEq(x, m2)) && !permEq(m2, idPerm(8)));

  // The distinction the four-section system could not make (Spencer & Gillen, p. 71):
  const mbd = pathMap(a8, 'MBD');
  const differsIn8 = a8.sections.every((_, i) => mbd[i] !== a8.w[i]);
  const sameIn4 = a8.sections.every((_, i) => phi[mbd[i]] === phi[a8.w[i]]);
  check('the first cross-cousin and the prescribed spouse fall in the SAME four-section class', sameIn4);
  check('...but in DIFFERENT eight-subsection classes, for every starting subsection', differsIn8);
}

// ---------------------------------------------------------------------------
section('4b. The 1899 book contradicts itself, and the algebra says which page is right');

{
  const a8 = SYS['arunta-1899'];
  const a4 = SYS['arunta-four-1899'];
  const spec = SPEC['arunta-1899'];
  const collapse = (pairs) => {
    const phi = new Array(8);
    for (const [four, eight] of Object.entries(pairs))
      for (const sub of eight) phi[a8.indexOf(sub)] = a4.indexOf(four);
    return {
      complete: phi.every((v) => Number.isInteger(v)) && new Set(phi).size === 4,
      marriage: a8.sections.every((_, i) => phi[a8.w[i]] === a4.w[phi[i]]),
      descent: a8.sections.every((_, i) => phi[a8.m[i]] === a4.m[phi[i]]),
      descentBreaks: a8.sections.filter((_, i) => phi[a8.m[i]] !== a4.m[phi[i]]).length,
    };
  };
  const c = spec.contradiction;
  check('both contradicting sentences are recorded with their page references',
    !!(c && c.p71 && c.p71.text && c.p71.locus && c.p74 && c.p74.text && c.p74.locus));

  const good = collapse(spec.refines.pairs);
  const bad = collapse(c.alternativePairs);
  check('the p. 71 pairing is a complete pairing, and so is the p. 74 one', good.complete && bad.complete);
  check('p. 71 pairing: the marriage rule carries across', good.marriage);
  check('p. 71 pairing: the descent rule carries across', good.descent);
  check('p. 74 pairing: the marriage rule ALSO carries across (so marriage alone cannot decide it)', bad.marriage);
  check('p. 74 pairing: the descent rule FAILS', !bad.descent);
  check('p. 74 pairing: it fails for exactly four of the eight subsections', bad.descentBreaks === 4,
    String(bad.descentBreaks));
  check('so only one reading is consistent with the book\'s own two tables', good.descent && !bad.descent);
}

// ---------------------------------------------------------------------------
section('5. The commutativity theorem, checked on every system and by exhaustion');

{
  // Theorem: m.w = w.m  <=>  the first cross-cousin is the prescribed spouse.
  // (Proof: the MBD map is m . w . m^-1, and that equals w for all x exactly when m and w commute.)
  for (const spec of data.systems) {
    const s = SYS[spec.id];
    const commutes = permEq(compose(s.m, s.w), compose(s.w, s.m));
    const cousinIsSpouse = permEq(pathMap(s, 'MBD'), s.w);
    check(`${spec.id}: commutes(${commutes}) agrees with first-cross-cousin-is-spouse(${cousinIsSpouse})`,
      commutes === cousinIsSpouse);
  }
  // and by exhaustion over every system the census can build, not just the attested ones
  let checked = 0, bad = 0;
  for (const n of [2, 4, 6, 8]) {
    for (const s of census(n)) {
      const sys = { w: s.w, m: s.m, p: compose(s.m, s.w), n, sections: new Array(n).fill(0) };
      const mi = inverse(s.m);
      const mbd = compose(s.m, compose(s.w, mi));
      const commutes = permEq(compose(s.m, s.w), compose(s.w, s.m));
      if (commutes !== permEq(mbd, s.w)) bad++;
      checked++;
    }
  }
  check(`the theorem holds for all ${checked} system shapes the census finds at n = 2,4,6,8`, bad === 0, `${bad} counterexamples`);
}

// ---------------------------------------------------------------------------
section('6. The census: which systems are even possible');

{
  const expect = {
    2: [{ matri: 1, order: 2 }, { matri: 2, order: 2 }],
    4: [{ matri: 2, order: 4 }, { matri: 4, order: 8 }],
    6: [{ matri: 3, order: 6 }, { matri: 6, order: 12 }],
    8: [{ matri: 4, order: 8 }, { matri: 8, order: 16 }],
  };
  for (const n of [2, 4, 6, 8]) {
    const c = census(n);
    check(`n = ${n}: exactly two shapes satisfy the four rules`, c.length === 2, `found ${c.length}`);
    const got = c.map((s) => ({ matri: s.matriCycleLength, order: s.groupOrder }));
    check(`n = ${n}: the shapes are as recorded`, JSON.stringify(got) === JSON.stringify(expect[n]), JSON.stringify(got));
    check(`n = ${n}: every shape obeys the patrilineal rule (a man's son's son is his own category)`,
      c.every((s) => s.patriCycleLength <= 2));
    if (n >= 4)
      check(`n = ${n}: exactly one of the two shapes acts regularly`, c.filter((s) => s.regular).length === 1);
    check(`n = ${n}: every group the census finds is dihedral`,
      c.every((s) => /^(D\d|C2 x C2|S3|C2)/.test(s.group.name || '')), c.map((s) => s.group.name).join(' / '));
  }
  // n = 2 is the degenerate case and it is worth saying what it actually is: with two
  // categories the only systems are the two kinds of moiety, and both act regularly.
  {
    const c2 = census(2);
    check('n = 2: the two shapes are matrilineal moieties and patrilineal moieties',
      c2.length === 2 && c2.some((s) => s.matriCycleLength === 1) && c2.some((s) => s.patriCycleLength === 1));
    check('n = 2: both act regularly (there is nothing yet for a section system to do)',
      c2.every((s) => s.regular));
  }
  // the two attested Australian sizes, and what they cost
  check('a four-section system prescribes the first cross-cousin',
    crossCousinDegree(...(() => { const s = census(4).find((x) => x.regular); return [s.w, s.m]; })()) === 1);
  check('an eight-subsection system prescribes the second cross-cousin',
    crossCousinDegree(...(() => { const s = census(8).find((x) => x.regular); return [s.w, s.m]; })()) === 2);
  check('a six-category system would prescribe the THIRD cross-cousin',
    crossCousinDegree(...(() => { const s = census(6).find((x) => x.regular); return [s.w, s.m]; })()) === 3);
}

// ---------------------------------------------------------------------------
section('7. What the name cannot tell you (the compression, measured)');

{
  const a = SYS['arunta-1899'];
  const prof = collisionProfile(a, 5);
  check('every one of the eight subsections is reachable by some genealogical path of length <= 5',
    prof.categoriesReached === 8, String(prof.categoriesReached));
  check('far more distinct genealogical positions than subsections to hold them',
    prof.totalPaths > 100 * 8, `${prof.totalPaths} paths`);

  // the sharp version: relatives who share the prescribed spouse's subsection
  const inSpouse = inSpouseCategory(a, 4);
  const shortest = inSpouse[0];
  check('some path of length <= 4 already lands in the prescribed spouse\'s subsection', !!shortest);
  check('more than one distinct relative shares the prescribed spouse\'s subsection at length <= 4',
    new Set(inSpouse.map((p) => p.path)).size > 1, String(inSpouse.length));

  // a person's own sister is never in the marriageable subsection (the system does bar that)
  check('a sister is never in the subsection a man must marry', pathMap(a, 'Z')[0] !== a.w[0]);
  check('a mother is never in the subsection a man must marry', pathMap(a, 'M')[0] !== a.w[0]);
  check('a daughter is never in the subsection a man must marry', pathMap(a, 'D')[0] !== a.w[0]);
}

// ---------------------------------------------------------------------------
section('8. The source quotations are present verbatim in the data file');

{
  let n = 0;
  for (const spec of data.systems) for (const q of spec.quotes || []) {
    n++;
    check(`${spec.id}: quotation at ${q.locus} is non-empty and attributed`,
      typeof q.text === 'string' && q.text.length > 40 && !!spec.source.author && !!spec.source.year);
  }
  check('every system carries at least one citation', data.systems.every((s) => s.source && s.source.url));
  console.log(`  (${n} quotations)`);
}

// ---------------------------------------------------------------------------
section("9. Weil's own condition, and that it is the same condition as ours");

{
  // Weil (1949) works with marriage TYPES and two maps: f takes a marriage to the
  // marriage its son will contract, g to the marriage its daughter will contract. With
  // one marriage formula per category, a marriage type is fixed by the husband's
  // category, so f = p and g = w . p. Weil's condition (C), "any man must be able to
  // marry his mother's brother's daughter", is fg = gf. Ours is mw = wm. They should
  // agree on every table, and with the cross-cousin fact itself.
  for (const spec of data.systems) {
    const s = SYS[spec.id];
    const f = s.p, g = compose(s.w, s.p);
    const weil = permEq(compose(f, g), compose(g, f));
    const ours = permEq(compose(s.m, s.w), compose(s.w, s.m));
    const cousin = permEq(pathMap(s, 'MBD'), s.w);
    check(`${spec.id}: Weil's fg=gf (${weil}), our mw=wm (${ours}) and MBD-is-spouse (${cousin}) all agree`,
      weil === ours && ours === cousin);
  }
  // and the sting: the eight-subsection table does NOT satisfy Weil's condition (C),
  // so the system Spencer and Gillen tabulated is excluded by his third axiom.
  const a = SYS['arunta-1899'];
  check("Weil's condition (C) FAILS on the 1899 eight-subsection table",
    !permEq(compose(a.p, compose(a.w, a.p)), compose(compose(a.w, a.p), a.p)));
  const k = SYS['kariera-1913'];
  check("Weil's condition (C) HOLDS on the 1913 four-section table",
    permEq(compose(k.p, compose(k.w, k.p)), compose(compose(k.w, k.p), k.p)));
}

// ---------------------------------------------------------------------------
section('10. The page is reading exactly these tables, and its quoted figures carry sources');

{
  const { PAGE, embeddedBlock } = await import('./embed.mjs');
  let html = null;
  try { html = fs.readFileSync(PAGE, 'utf8'); } catch { /* page not built yet */ }
  check('the immersive page exists', !!html, PAGE);
  if (html) {
    const block = embeddedBlock(html);
    check('the page carries an embedded data block', !!block);
    if (block) {
      let same = false, why = '';
      try {
        same = JSON.stringify(JSON.parse(block)) === JSON.stringify(data);
      } catch (e) { why = 'embedded block is not valid JSON: ' + e.message; }
      check('the page\'s embedded tables are byte-identical in content to systems.json', same,
        why || 'run `node research/kinship-algebra/embed.mjs`');
    }
    check('the page names its verifier', html.includes('verify-the-four-names-that-were-not-enough.mjs'));
  }

  const rows = data.conformity.rows;
  check('every conformity figure carries a source and a URL',
    rows.length > 0 && rows.every((r) => r.source && r.url && r.n && r.counted && r.figure));
  check('the conformity table counts BOTH the coarse rule and the fine prescription',
    rows.some((r) => /skin|section|category|rule/i.test(r.counted)) &&
    rows.some((r) => /MMBDD|genealogical|bestowal/i.test(r.counted)));
  check('the measurement caveat is present with its source', !!(data.conformity.caveat
    && data.conformity.caveat.text && data.conformity.caveat.source && data.conformity.caveat.url));
}

// ---------------------------------------------------------------------------
console.log(`\n${'='.repeat(64)}`);
console.log(`PASS ${pass}/${pass + fail}`);
if (fail) { console.log('FAILURES:'); failures.forEach((f) => console.log('  - ' + f)); process.exit(1); }
console.log('all checks green');
