// verify.mjs: checks for /strata/the-word-that-comes-back/.
// Run: node research/the-word-that-comes-back/verify.mjs      (no network, no databases)
//
// 1. Reruns the page's own engine on the committed sample (3,908 ghazals' rhyme lines) and
//    holds every field against the stored measurement, data/ghazals.tsv.
// 2. Planted cases: a refrain it must find, one it must not, and each hard case the rule
//    was built for, plus the six poems the page quotes.
// 3. Recomputes the page's numbers from data/ghazals.tsv by a second route (plain counting,
//    no build-data.mjs) and holds data.json to them.
// 4. Reads the page's own prose and checks the numbers printed in it.
// 5. The rise and fall: every choice of era boundaries within 25 years, every rule; and a
//    permutation test with a different seed from the page's.
// 6. The final audit, rescored against the stored measurement.
//
// ENGINE=<path> points it at another engine file; mutate.mjs uses that to check that a
// broken engine makes this fail.

import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';

const HERE = new URL('.', import.meta.url);
const PAGE = new URL('../../public/strata/the-word-that-comes-back/', import.meta.url);
const E = await import(process.env.ENGINE ? pathToFileURL(process.env.ENGINE).href : new URL('engine.mjs', PAGE).href);
const read = (u) => readFileSync(u, 'utf8');
const lex = JSON.parse(read(new URL('lex.json', PAGE)));
const data = JSON.parse(read(new URL('data.json', PAGE)));
const examples = JSON.parse(read(new URL('examples.json', PAGE)));
const html = read(new URL('index.html', PAGE));
const sample = JSON.parse(read(new URL('data/sample.json', HERE)));
const poetsAPI = JSON.parse(read(new URL('data/ganjoor-poets-2026-09-25.json', HERE)));
const tsv = read(new URL('data/ghazals.tsv', HERE)).trim().split('\n');
const H = tsv.shift().split('\t');
const rows = tsv.map((l) => { const v = l.split('\t'); const r = {}; H.forEach((h, i) => { r[h] = v[i] ?? ''; }); return r; });
const byPoem = new Map(rows.map((r) => [r.poem, r]));

let pass = 0, fail = 0;
const out = [];
const ok = (name, cond, detail = '') => { cond ? pass++ : fail++; out.push(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  :  ' + detail : ''}`); };
const head = (t) => out.push('', `-- ${t}`);
const r1 = (x) => Math.round(x * 10) / 10;
const median = (a) => { const s = [...a].sort((x, y) => x - y); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };

// ---------------------------------------------------------------------------
head('1. The page engine, rerun on the committed sample, against the stored measurement');
{
  let n = 0, bad = 0; const firstBad = [];
  for (const g of sample) {
    const r = byPoem.get(String(g.poem));
    const L = g.lines;
    const S = E.wordRadif(L, 'S'), Z = E.wordRadif(L, 'Z');
    const C = E.letterRadif(L, lex, 0), D = E.letterRadif(L, lex, 1);
    const got = {
      S: String(S.n), Z: String(Z.n),
      C: String(C.radif ? C.radif.split(' ').length : 0), D: String(D.radif ? D.radif.split(' ').length : 0),
      j: String(C.j), rhyme: String(E.sharedRhyme(L, C.j)), end: C.j ? '' : E.sharedEnding(L),
      shown: C.j ? E.tailLetters(L[1], C.j) : '',
    };
    n++;
    const diff = Object.keys(got).filter((k) => !r || got[k] !== r[k]);
    if (diff.length) { bad++; if (firstBad.length < 3) firstBad.push(`${g.poem}:${diff.join(',')}`); }
  }
  ok(`all ${n.toLocaleString('en-US')} sample ghazals reproduce all eight stored fields`, bad === 0, bad ? `${bad} differ, e.g. ${firstBad.join(' ')}` : `${n * 8} fields`);
  ok('the sample holds only poets who died before 1956', sample.every((g) => {
    const p = poetsAPI.find((x) => x.id === +byPoem.get(String(g.poem)).poet);
    return p && p.deathYearInLHijri && E.hijriToCE(p.deathYearInLHijri) < 1956;
  }));
}

// ---------------------------------------------------------------------------
head('2. Planted cases, and the poems the page quotes');
{
  const C = (lines, tol = 0) => E.letterRadif(lines, lex, tol);
  const shown = (lines, tol = 0) => { const c = C(lines, tol); return c.j ? E.tailLetters(lines[1], c.j) : ''; };
  const planted = [
    ['a plain refrain after a rhyme', ['دلم ز دست برفت ای نگار باز بیا', 'که بی تو نیست قرار ای بهار باز بیا', 'ز هجر سوخت دلم در کنار باز بیا', 'بسوخت جان من از انتظار باز بیا'], 'باز بیا'],
    ['no refrain: the lines only rhyme (Hafez 101)', ['شراب و عیش نهان چیست؟ کار بی‌بنیاد', 'زدیم بر صف رندان و هر چه بادا باد', 'که فکر هیچ مهندس چنین گره نگشاد', 'از این فسانه هزاران هزار دارد یاد'], ''],
    ['a verb behind joined preverbs (بر، در، سر)', ['ساقی بیا که یار ز رخ پرده برگرفت', 'کار چراغ خلوتیان باز درگرفت', 'وین پیر سالخورده جوانی ز سر گرفت', 'وان لطف کرد دوست که دشمن حذر گرفت'], 'گرفت'],
    ['the plural -hā is an ending, not a radif', ['که عشق آسان نمود اول ولی افتاد مشکل‌ها', 'ز تاب جعد مشکینش چه خون افتاد در دل‌ها', 'جرس فریاد می‌دارد که بربندید محمل‌ها', 'که سالک بی‌خبر نبود ز راه و رسم منزل‌ها'], ''],
    ['a rhyme written with madda (درآ) still rhymes', ['موبمو حال پریشان مرا می گوید', 'همه شب پیر خرابات صلا می گوید', 'جرس قافله هرچند درآ می گوید', 'بت پرست از ته دل نام خدا می گوید'], 'می گوید'],
    ['آید is a verb, not the ending -ید', ['دمی که بوی گل از باد نوبهار آید', 'به غنچه ی دل من بی تو زخم خار آید', 'دو چشم من نگران هر طرف که یار آید', 'که سبزه بر دمد از خاک و گل به بار آید'], 'آید'],
    ['a split the edition never writes (با|شد) is refused', ['شوریده صحرائی در خانه چسان باشد', 'از عقل چو شد برتر فرزانه چسان باشد', 'گر پرده نیفتد زو افسانه چرا باشد', 'تا جان ندهد از کف جانانه چسان باشد'], ''],
    ['a short word hiding inside a longer one (یا|داری) is refused (Nezari, audit round 1, G117)', ['توقع است که گوشی به حال ما داری', 'روا مدار که آزار ما روا داری', 'مسیح جان منی یک دمی کجا داری', 'مرا رسد که کنم دعوی هواداری', 'بدیع نیست که چشمان آشنا داری', 'دگر چه ماند مگر قصد جان ما داری', 'که گه‌گهی ز نزاری زار یاد آری'], ''],
    ['... while the same poem without that line has the refrain داری', ['توقع است که گوشی به حال ما داری', 'روا مدار که آزار ما روا داری', 'مسیح جان منی یک دمی کجا داری', 'مرا رسد که کنم دعوی هواداری', 'بدیع نیست که چشمان آشنا داری', 'دگر چه ماند مگر قصد جان ما داری'], 'داری'],
  ];
  const same = ['آمد بهار آمد بهار', 'آمد بهار آمد بهار', 'آمد بهار آمد بهار'];
  ok('planted: identical lines, and the as-written rule still leaves one word for the rhyme', E.wordRadif(same, 'S').n === 3, String(E.wordRadif(same, 'S').n));
  const counts = Object.values(lex);
  ok(`lex.json holds exactly the words the rule can use (every count >= LEX_MIN, and the smallest is LEX_MIN = ${E.LEX_MIN})`,
    counts.every((n) => n >= E.LEX_MIN) && Math.min(...counts) === E.LEX_MIN, `smallest count ${Math.min(...counts)}`);
  for (const [name, lines, want] of planted) ok(`planted: ${name}`, shown(lines) === want, `found ${JSON.stringify(shown(lines))}`);
  ok('planted: the tolerant rule forgives one line (چسان باشد)', shown(planted[6][1], 1) === 'چسان باشد', JSON.stringify(shown(planted[6][1], 1)));
  const ex = (id) => E.analyse(examples[id].couplets, lex);
  const cases = [
    ['Hafez 3 (Turk of Shiraz): radif را', ex(2132).shown === 'را' && ex(2132).C === 1],
    ['Hafez 86: radif گرفت, which the as-written rule misses', ex(2215).shown === 'گرفت' && ex(2215).S === 0],
    ['Hafez 2: the strict rule refuses کجا, the tolerant rule finds it', ex(2131).C === 0 && ex(2131).D === 1 && ex(2131).S === 1],
    ['Hafez 1: no radif by any rule', ex(2130).S === 0 && ex(2130).C === 0 && ex(2130).D === 0],
    ['Saadi 46: no radif, a shared ending noted', ex(9368).C === 0 && ex(9368).end !== ''],
    ['Amir Khosrow: the counting refrain, eight words', ex(61731).shown === 'یک دو سه چار و پنج و شش' && ex(61731).shown.split(' ').length === 8],
  ];
  for (const [n, c] of cases) ok(n, c);
}

// ---------------------------------------------------------------------------
head('3. The page\'s numbers, recounted straight from ghazals.tsv');
{
  const N = rows.length;
  const has = (k) => rows.filter((r) => +r[k] > 0).length;
  ok('60,059 ghazals', N === 60059 && data.total.ghazals === N, String(N));
  ok('146 poets', new Set(rows.map((r) => r.poet)).size === 146 && data.total.poets === 146);
  ok('517,492 couplets', rows.reduce((s, r) => s + +r.couplets, 0) === 517492 && data.total.couplets === 517492);
  for (const k of ['S', 'Z', 'C', 'D']) ok(`share with a radif, rule ${k}: ${r1(100 * has(k) / N)}%`, r1(100 * has(k) / N) === data.total[k]);
  const withC = rows.filter((r) => +r.C > 0);
  ok('41,888 ghazals with a radif (letters rule)', withC.length === 41888, String(withC.length));
  const L = (t) => t.replace(/[\s‌]/g, '');
  const f = new Map(); for (const r of withC) f.set(L(r.shown), (f.get(L(r.shown)) || 0) + 1);
  ok('7,219 distinct radifs', f.size === 7219 && data.total.distinct === 7219, String(f.size));
  const top = [...f].sort((a, b) => b[1] - a[1]);
  ok('the commonest is است, in 1,605 ghazals', top[0][0] === 'است' && top[0][1] === 1605, `${top[0][0]} ${top[0][1]}`);
  const astPoets = new Set(withC.filter((r) => L(r.shown) === 'است').map((r) => r.poet)).size;
  ok('... by 111 poets', astPoets === 111, String(astPoets));
  ok('then را (1,549) and نیست (1,087)', top[1][0] === 'را' && top[1][1] === 1549 && top[2][0] === 'نیست' && top[2][1] === 1087);
  const words = (t) => t.split(' ').filter(Boolean).length;
  const lens = {}; for (const r of rows) { const w = +r.C ? words(r.shown) : 0; lens[w] = (lens[w] || 0) + 1; }
  ok('the length distribution matches data.json', JSON.stringify(lens) === JSON.stringify(data.lengths), JSON.stringify(lens));
  const longest = withC.reduce((a, r) => (words(r.shown) > words(a.shown) ? r : a));
  ok('the longest radif by words is the count to six (poem 61731), 8 words', longest.poem === '61731' && words(longest.shown) === 8);
  ok('it is the only 8-word radif', lens[8] === 1);
  // per-poet, by counting
  const by = new Map(); for (const r of rows) { if (!by.has(r.poet)) by.set(r.poet, []); by.get(r.poet).push(r); }
  const share = (id, k) => r1(100 * by.get(String(id)).filter((r) => +r[k] > 0).length / by.get(String(id)).length);
  const P = new Map(data.poets.map((p) => [p.id, p]));
  let agree = 0; for (const p of data.poets) if (['S', 'Z', 'C', 'D'].every((k) => share(p.id, k) === p[k])) agree++;
  ok('every poet\'s four shares in data.json match a recount', agree === data.poets.length, `${agree} of ${data.poets.length}`);
  ok('Saeb: 6,994 ghazals, 86.1%', by.get('22').length === 6994 && share(22, 'C') === 86.1);
  ok('Bidel: 54.1% as written, 73.6% by letters', share(43, 'S') === 54.1 && share(43, 'C') === 73.6);
  ok('Ghalib: 84.1%', share(123, 'C') === 84.1);
  ok('Hafez 62.4%, Saadi 43.7%, Jami 60.1%', share(2, 'C') === 62.4 && share(7, 'C') === 43.7 && share(24, 'C') === 60.1);
  const ceil = (id) => r1(100 * by.get(String(id)).filter((r) => +r.C > 0 || r.end).length / by.get(String(id)).length);
  ok('ceilings: Hafez 85.7, Saadi 81.9, Jami 76.9, Saeb 93.0', ceil(2) === 85.7 && ceil(7) === 81.9 && ceil(24) === 76.9 && ceil(22) === 93.0,
    [2, 7, 24, 22].map(ceil).join(' '));
  ok('Mohseni: Hafez, Saadi and Jami consistent with lying between the two columns; Saeb above the second',
    share(2, 'C') < 80 && ceil(2) > 80 && share(7, 'C') < 80 && ceil(7) > 80 && share(24, 'C') < 66 && ceil(24) > 66 && ceil(22) < 94);
  // the wider count of endings the page quotes for Saeb (92% to 95% on the committed sample)
  {
    const wide = [...E.ENDINGS, 'ها', 'ان', 'ند', 'ید', 'د', 'مان', 'تان', 'شان'];
    const sb = sample.filter((g) => byPoem.get(String(g.poem)).poet === '22');
    const lettersOf = (L) => L.map((x) => E.words(x, 'Z').join(''));
    const narrow = sb.filter((g) => +byPoem.get(String(g.poem)).C > 0 || byPoem.get(String(g.poem)).end).length;
    const wider = sb.filter((g) => +byPoem.get(String(g.poem)).C > 0 || wide.some((e) => lettersOf(g.lines).every((t) => t.length > e.length && t.endsWith(e)))).length;
    ok('Saeb in the sample: 92% with the page\'s endings, 95% with plural and verb endings too',
      Math.round(100 * narrow / sb.length) === 92 && Math.round(100 * wider / sb.length) === 95, `${narrow}/${sb.length} and ${wider}/${sb.length}`);
  }
  // eras and centuries, recomputed
  const tl = data.poets.filter((p) => p.n >= 100 && p.ce);
  ok('92 poets on the timeline', tl.length === 92, String(tl.length));
  const span = (a, b, k) => median(tl.filter((p) => p.ce >= a && p.ce < b).map((p) => p[k]));
  ok('median poet before 1500: 62.6%; 1500 to 1799: 83.3%; from 1800: 61.1% (letters)',
    r1(span(0, 1500, 'C')) === 62.6 && r1(span(1500, 1800, 'C')) === 83.3 && r1(span(1800, 3000, 'C')) === 61.1,
    [span(0, 1500, 'C'), span(1500, 1800, 'C'), span(1800, 3000, 'C')].map(r1).join(' '));
  const cm = (c) => r1(span(c, c + 100, 'C'));
  ok('century medians: 1100s to 1400s between 61 and 68; 1500s to 1700s between 81.5 and 84.5; 1800s 58.5; 1900s 66.9',
    [1100, 1200, 1300, 1400].every((c) => cm(c) >= 61 && cm(c) <= 68) && [1500, 1600, 1700].every((c) => cm(c) >= 81.5 && cm(c) <= 84.5) && cm(1800) === 58.5 && cm(1900) === 66.9,
    [1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900].map(cm).join(' '));
  ok('data.json century medians agree', data.cents.every((c) => c.C === cm(c.c)));
  // the Return poets
  const ret = [[154, 'Moshtaq', 1756], [148, 'Azar', 1781], [167, 'Rafiq', 1797], [149, 'Neshat', 1829], [235, 'Fath-Ali Shah', 1834]];
  ok('the Return: Moshtaq and his students at 74 to 81%; Neshat and Fath-Ali Shah at 57 and 59%, below the pre-1500 median',
    ret.slice(0, 3).every(([id]) => Math.round(P.get(id).C) >= 74 && Math.round(P.get(id).C) <= 81) && Math.round(P.get(149).C) === 57 && Math.round(P.get(235).C) === 59
      && ret.slice(3).every(([id]) => P.get(id).C < median(data.poets.filter((p) => p.n >= 100 && p.ce && p.ce < 1500).map((p) => p.C))) && ret.every(([id, , y]) => P.get(id).ce === y),
    ret.map(([id, n]) => `${n} ${P.get(id).C}`).join(', '));
  const cs = rows.map((r) => +r.couplets).sort((a, b) => a - b);
  ok('ghazals run 5 to 12 couplets in most cases (median 8)', cs[cs.length >> 1] === 8 && cs.filter((c) => c >= 5 && c <= 12).length / cs.length > 0.85);
}

// ---------------------------------------------------------------------------
head('4. The numbers printed in the page\'s own prose');
{
  const text = html.replace(/<script[\s\S]*?<\/script>/g, '').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ');
  const must = ['60,059', '146 poets', '517,492 couplets', '41,888', '7,219', '1,605 ghazals by 111 poets', '6,994 ghazals, carries a radif in 86%',
    'as written, 54% of his ghazals have a radif, and read by letters, 74%', 'radif in 84% of his ghazals', '148 of 150', 'same words in 104 of 105', '141 of 150', '74 to 81%', '57 and 59%', '58.5% in the 1800s', 'survives moving either boundary by 25 years',
    '0 of 420,413', '281 files', 'Seven in ten', '7,015', '21 more ghazals', 'thirteen rhyme lines', 'from 92% to 95%', 'Eight and a half centuries', 'stays at 73%', 'Ten rhyme lines', '3,908'];
  for (const m of must) ok(`the page says "${m}"`, text.includes(m));
  ok('the sample size in the page is the committed one', text.includes(sample.length.toLocaleString('en-US')));
}

// ---------------------------------------------------------------------------
head('5. The rise and fall, under every boundary within 25 years and every rule');
{
  const tl = data.poets.filter((p) => p.n >= 100 && p.ce);
  let worst = Infinity, cells = 0;
  for (const a of [1475, 1500, 1525]) for (const b of [1775, 1800, 1825]) for (const k of ['S', 'Z', 'C', 'D']) {
    const g = (x, y) => median(tl.filter((p) => p.ce >= x && p.ce < y).map((p) => p[k]));
    const mid = g(a, b), lo = Math.max(g(0, a), g(b, 3000));
    worst = Math.min(worst, mid - lo); cells++;
  }
  ok(`the middle span beats both others by at least 15 points in all ${cells} cases`, worst >= 15, `smallest gap ${r1(worst)} points`);
  // permutation test, seed different from build-data.mjs
  let seed = 977; const rnd = () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648; };
  const mid = tl.filter((p) => p.ce >= 1500 && p.ce < 1800).map((p) => p.C);
  for (const [name, other] of [['before 1500', tl.filter((p) => p.ce < 1500)], ['from 1800', tl.filter((p) => p.ce >= 1800)]]) {
    const b = other.map((p) => p.C); const obs = median(mid) - median(b);
    const all = [...mid, ...b]; let hit = 0; const iters = 20000;
    for (let i = 0; i < iters; i++) {
      for (let j = all.length - 1; j > 0; j--) { const t = Math.floor(rnd() * (j + 1)); [all[j], all[t]] = [all[t], all[j]]; }
      if (Math.abs(median(all.slice(0, mid.length)) - median(all.slice(mid.length))) >= Math.abs(obs)) hit++;
    }
    ok(`1500 to 1799 against ${name}: difference ${r1(obs)} points, no shuffle of 20,000 as large`, hit === 0 && obs > 15, `${hit} of ${iters}`);
  }
}

// ---------------------------------------------------------------------------
head('6. The final audit (round 3), rescored against the stored measurement');
{
  const dir = new URL('audits/round-3/', HERE);
  const ids = JSON.parse(read(new URL('ids.json', dir)));
  const load = (f) => { const d = {}; for (const l of read(new URL(f, dir)).split('\n')) { const m = l.match(/^\s*G(\d{3})\s*\|\s*([^|]*?)\s*(\||$)/); if (m) d[+m[1]] = m[2].trim(); } return d; };
  const A = load('reader-E.txt'), B = load('reader-F.txt');
  const has = (s) => s.toUpperCase() !== 'NONE';
  const L = (s) => s.replace(/[\s‌]/g, '').replace(/آ/g, 'ا');
  const agreeAB = ids.filter((_, i) => has(A[i + 1]) === has(B[i + 1])).length;
  const agree = (R, k) => ids.filter((id, i) => has(R[i + 1]) === (+byPoem.get(String(id))[k] > 0)).length;
  ok('the two readers agree with each other on 150 of 150', agreeAB === 150, String(agreeAB));
  ok('letters rule: 148 of 150 with each reader', agree(A, 'C') === 148 && agree(B, 'C') === 148, `${agree(A, 'C')} ${agree(B, 'C')}`);
  ok('as-written rule: 141 of 150 with each reader', agree(A, 'S') === 141 && agree(B, 'S') === 141, `${agree(A, 'S')} ${agree(B, 'S')}`);
  const both = ids.map((id, i) => [id, i + 1]).filter(([id, g]) => has(A[g]) && has(B[g]) && +byPoem.get(String(id)).C > 0);
  const same = both.filter(([id, g]) => L(A[g]) === L(byPoem.get(String(id)).shown) && L(B[g]) === L(byPoem.get(String(id)).shown)).length;
  ok('the radif text: rule and both readers give the same words in 104 of 105', both.length === 105 && same === 104, `${same} of ${both.length}`);
}

console.log(out.join('\n'));
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
