// sinaiticus.mjs: ask the Codex Sinaiticus Project, leaf by leaf, which side of
// the skin every surviving page is, and count what faces what.
//
//   curl -sO https://artwaste.land/strata/hair-faces-hair/sinaiticus.mjs
//   node sinaiticus.mjs            # about 800 small requests, a few minutes
//   node sinaiticus.mjs --save     # also keep what came back in sinaiticus-sides.csv
//
// Needs Node 18 or later (for fetch). Nothing is read from artwaste.land: every
// value comes from codexsinaiticus.org, the project run by the four libraries that
// hold the manuscript. Their physical description records, for each side of each
// leaf, "Hair or flesh side" as H or F. Their terms allow non-commercial personal
// and educational use, which is why this page hands you the program that asks them
// rather than a copy of their answers.
//
// Leaves are numbered by POSITION WITHIN THE QUIRE (1 to 8), per the project's
// methodology page, so a verso of leaf n faces the recto of leaf n+1.

import { writeFileSync } from 'node:fs';

const H = 'https://codexsinaiticus.org/handler/';
// The quire list offered by the project's own viewer (<select id="quireNo"> on
// https://codexsinaiticus.org/en/manuscript.aspx), as of 2026-09-23.
const QUIRES = [3, 10, 11, 12, 13, 15, 17, 18, 29, 34,
  ...range(35, 49), ...range(57, 72), ...range(74, 93), 95, 0];
function range(a, b) { return Array.from({ length: b - a + 1 }, (_, i) => a + i); }

async function get(url, tries = 4) {
  for (let t = 0; ; t++) {
    try {
      const r = await fetch(url, { headers: { 'user-agent': 'hair-faces-hair check (artwaste.land)' } });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      return await r.text();
    } catch (e) {
      if (t + 1 >= tries) throw new Error(`${url}: ${e.message}`);
      await new Promise((res) => setTimeout(res, 1000 * 2 ** t));
    }
  }
}

async function pool(items, n, fn) {
  const out = new Array(items.length);
  let next = 0;
  await Promise.all(Array.from({ length: n }, async () => {
    while (next < items.length) { const i = next++; out[i] = await fn(items[i]); }
  }));
  return out;
}

const jobs = [];
for (const q of QUIRES) {
  const list = await get(`${H}getFolioList.ashx?q=${q}`);
  for (const [, f] of list.matchAll(/value="([^"]*)"/g)) for (const s of ['r', 'v']) jobs.push({ q, f: Number(f), s });
}
process.stderr.write(`${jobs.length} leaf-sides listed in ${QUIRES.length} quires; asking for each...\n`);
let done = 0;
const rows = await pool(jobs, 4, async (j) => {
  const html = await get(`${H}physicalDescription.ashx?q=${j.q}&f=${j.f}&s=${j.s}&lid=en`);
  const m = html.match(/Hair or flesh side[\s\S]*?<li class="propValue phLI">([^<]*)<\/li>/);
  if (++done % 100 === 0) process.stderr.write(`  ${done}/${jobs.length}\n`);
  return { ...j, side: m ? m[1].trim() : '' };
});

// The handler sometimes answers with an empty record for a leaf it does describe
// (two runs a day apart disagreed on three leaf-sides this way). So any blank
// inside a quire that has data elsewhere is asked again, twice, and the count of
// blanks that survive is printed rather than hidden.
const hasData = new Set(rows.filter((r) => r.side).map((r) => r.q));
const blanks = rows.filter((r) => !r.side && hasData.has(r.q));
for (let pass = 0; pass < 2; pass++) {
  for (const r of blanks) {
    if (r.side) continue;
    const html = await get(`${H}physicalDescription.ashx?q=${r.q}&f=${r.f}&s=${r.s}&lid=en`);
    const m = html.match(/Hair or flesh side[\s\S]*?<li class="propValue phLI">([^<]*)<\/li>/);
    if (m) r.side = m[1].trim();
  }
}
const stillBlank = blanks.filter((r) => !r.side);
console.log(`blanks inside described quires: ${blanks.length} re-asked, ${stillBlank.length} still blank` +
  (stillBlank.length ? `  (${stillBlank.map((r) => `q${r.q} ${r.f}${r.s}`).join(', ')})` : ''));

if (process.argv.includes('--save')) {
  writeFileSync('sinaiticus-sides.csv', 'quire,leaf,side,hair_or_flesh\n' +
    rows.map((r) => `${r.q},${r.f},${r.s},${r.side}`).join('\n') + '\n');
}

// ---- count -------------------------------------------------------------------
const val = new Map(rows.map((r) => [`${r.q}.${r.f}${r.s}`, r.side]));
const withData = rows.filter((r) => r.side === 'H' || r.side === 'F');
const quires = [...new Set(withData.map((r) => r.q))].sort((a, b) => a - b);
console.log(`leaf-sides listed:            ${rows.length}`);
console.log(`leaf-sides with H or F:       ${withData.length}  (H ${withData.filter((r) => r.side === 'H').length}, F ${withData.filter((r) => r.side === 'F').length})`);
console.log(`quires with any H/F recorded: ${quires.length}  (${quires[0]} to ${quires[quires.length - 1]})`);

let firstF = 0, firstAny = 0;
const firstH = [];
let match = 0;
const miss = [];
for (const q of quires) {
  const leaves = rows.filter((r) => r.q === q).map((r) => r.f);
  const maxLeaf = Math.max(...leaves);
  const f1 = val.get(`${q}.1r`);
  if (f1) { firstAny++; if (f1 === 'F') firstF++; else firstH.push(q); }
  for (let n = 1; n < maxLeaf; n++) {
    const L = val.get(`${q}.${n}v`), R = val.get(`${q}.${n + 1}r`);
    if (!L || !R) continue;
    if (L === R) match++; else miss.push(`q${q}: ${n}v ${L} against ${n + 1}r ${R}`);
  }
}
console.log(`first page of the quire is F: ${firstF} of ${firstAny}${firstH.length ? `  (H in quire ${firstH.join(', ')})` : ''}`);
console.log(`openings inside a quire, both pages recorded: ${match + miss.length}`);
console.log(`  like against like:          ${match}`);
console.log(`  unlike:                     ${miss.length}`);
for (const m of miss) console.log(`    ${m}`);

// The eight-leaf quires, read as four nested bifolia: which face is on the OUTSIDE
// of each? Gregory's Rule, flesh out, needs F, H, F, H from the outermost inwards.
console.log('\neight-leaf quires, outside face of each bifolium, outermost first:');
const patterns = new Map();
for (const q of quires) {
  const outs = [1, 2, 3, 4].map((j) => val.get(`${q}.${j}r`) || '?');
  const inner = [8, 7, 6, 5].map((j) => val.get(`${q}.${j}v`) || '?');
  if (!rows.some((r) => r.q === q && r.f === 8)) continue;
  // the outside of bifolium j shows on leaf j recto and on leaf 9-j verso: both must agree
  const agree = outs.every((o, j) => o === '?' || inner[j] === '?' || o === inner[j]);
  const key = outs.map((o, j) => (o !== '?' ? o : inner[j])).join('') + (agree ? '' : ' (recto and verso disagree)');
  patterns.set(key, [...(patterns.get(key) || []), q]);
}
for (const [k, qs] of [...patterns].sort((a, b) => b[1].length - a[1].length)) {
  console.log(`  ${k}  x${qs.length}${qs.length <= 3 ? `  (quire ${qs.join(', ')})` : ''}`);
}
