// measure.mjs: run the page's own radif detector over every ghazal Ganjoor holds.
//
//   bash research/the-word-that-comes-back/fetch.sh /some/dir     # 281 SQLite files, ~290 MB
//   node research/the-word-that-comes-back/measure.mjs /some/dir/x
//
// Reads the per-poet SQLite databases Ganjoor publishes for its apps, keeps the
// categories that are collections of whole ghazals, runs engine.mjs on each
// ghazal and writes:
//   data/ghazals.tsv   one row per ghazal (the measurement; committed)
//   data/sample.json   the rhyme lines of a fixed sample (poem id divisible by 17, and all of
//                      Hafez; poets who died before 1956 only), so the verifier can rerun
//                      the engine without the 290 MB of databases
//   ../../public/strata/the-word-that-comes-back/lex.json  the corpus words
//                      the rule consults (count >= LEX_MIN), for the page
// Needs Node 22 (node:sqlite). No network.

import { DatabaseSync } from 'node:sqlite';
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import * as E from '../../public/strata/the-word-that-comes-back/engine.mjs';

const DIR = process.argv[2];
if (!DIR) { console.error('usage: node measure.mjs <dir of .gdb files>'); process.exit(2); }
const HERE = new URL('.', import.meta.url).pathname;
const PAGE = new URL('../../public/strata/the-word-that-comes-back/', import.meta.url).pathname;

// Which Ganjoor categories are collections of whole ghazals. Excluded by title:
// unfinished ghazals, selected couplets, mixed-genre sections, Turkish ghazals,
// poems marked as later additions, taghazzul (a qasida's opening).
const EXCLUDE = ['ناتمام', 'ابیات برگزیده', 'قصاید', 'قطعات', 'مقطعات', 'ترکی', 'الحاقی', 'تغزل'];
export const isGhazalCat = (t) => !!t && t.includes('غزل') && !EXCLUDE.some((w) => t.includes(w));

// Texts are committed and published only for poets who died before 1956 (life plus seventy
// years). Poets Ganjoor does not date are all modern, so they are withheld too.
const POETS = JSON.parse(readFileSync(join(HERE, 'data/ganjoor-poets-2026-09-25.json'), 'utf8'));
export const textIsFree = (poetId) => {
  const p = POETS.find((x) => x.id === poetId);
  return !!(p && p.deathYearInLHijri && E.hijriToCE(p.deathYearInLHijri) < 1956);
};

const files = readdirSync(DIR).filter((f) => f.endsWith('.gdb')).sort();
const open = (f) => new DatabaseSync(join(DIR, f), { readOnly: true });

// Pass 1: the lexicon, every ZWNJ-split word of every line of every poem.
const lex = new Map();
for (const f of files) {
  for (const { text } of open(f).prepare('select text from verse').iterate()) {
    for (const w of E.words(text, 'Z')) lex.set(w, (lex.get(w) || 0) + 1);
  }
}

// Pass 2: the ghazals.
const out = [['poem', 'poet', 'cat', 'couplets', 'S', 'Z', 'C', 'D', 'j', 'rhyme', 'end', 'shown', 'url'].join('\t')];
const sample = [];
let seen = 0, skipped = 0;
const gdbPoets = {};
for (const f of files) {
  const db = open(f);
  for (const p of db.prepare('select id, name from poet').all()) gdbPoets[p.id] = p.name;
  const verses = new Map();
  for (const v of db.prepare('select poem_id, vorder, position, text from verse order by poem_id, vorder').iterate()) {
    if (!verses.has(v.poem_id)) verses.set(v.poem_id, []);
    verses.get(v.poem_id).push(v);
  }
  for (const cat of db.prepare('select id, poet_id, text, url from cat').all()) {
    if (!isGhazalCat(cat.text)) continue;
    for (const p of db.prepare('select id, url from poem where cat_id = ? order by id').all(cat.id)) {
      seen++;
      const vs = verses.get(p.id) || [];
      const plain = vs.length >= 6 && vs.length % 2 === 0 && vs.every((v, i) => v.position === i % 2);
      if (!plain) { skipped++; continue; }
      const couplets = [];
      for (let i = 0; i < vs.length; i += 2) couplets.push([vs[i].text, vs[i + 1].text]);
      const a = E.analyse(couplets, lex);
      if (!a) { skipped++; continue; }
      out.push([p.id, cat.poet_id, cat.id, couplets.length, a.S, a.Z, a.C, a.D, a.j, a.rhyme, a.end, a.shown, (p.url || '').replace('https://ganjoor.net', '')].join('\t'));
      // a fixed, reproducible sample: every poem whose id is divisible by 17, and all of Hafez
      if ((p.id % 17 === 0 || cat.poet_id === 2) && textIsFree(cat.poet_id)) sample.push({ poem: p.id, lines: a.lines });
    }
  }
}

// The poems the page quotes whole, straight from the databases: Hafez 1, 2, 3 and 86,
// Saadi 46, and one of Amir Khosrow's.
const EXAMPLES = { 2130: 'hafez.gdb', 2131: 'hafez.gdb', 2132: 'hafez.gdb', 2215: 'hafez.gdb', 9368: 'saadi.gdb', 61731: 'khosro.gdb' };
const examples = {};
for (const [id, f] of Object.entries(EXAMPLES)) {
  const db = open(f);
  const vs = db.prepare('select position, text from verse where poem_id = ? order by vorder').all(+id);
  const couplets = [];
  for (let i = 0; i < vs.length; i += 2) couplets.push([vs[i].text, vs[i + 1].text]);
  examples[id] = { url: db.prepare('select url from poem where id = ?').get(+id).url.replace('https://ganjoor.net', ''), couplets };
}
writeFileSync(join(PAGE, 'examples.json'), JSON.stringify(examples));

writeFileSync(join(HERE, 'data/ghazals.tsv'), out.join('\n') + '\n');
writeFileSync(join(HERE, 'data/sample.json'), JSON.stringify(sample));
writeFileSync(join(HERE, 'data/gdb-poets.json'), JSON.stringify(gdbPoets));
const lexOut = {};
for (const [w, n] of [...lex].sort((a, b) => b[1] - a[1])) if (n >= E.LEX_MIN) lexOut[w] = n;
writeFileSync(join(PAGE, 'lex.json'), JSON.stringify(lexOut));
console.log(`${seen} poems in ghazal categories; ${out.length - 1} measured, ${skipped} not plain couplets of 3+; sample ${sample.length}; lexicon ${Object.keys(lexOut).length} words >= ${E.LEX_MIN}`);
