// engine.mjs: the tone rules of Tang regulated verse, scored under three readers.
// No dependencies; the page runs this file in the reader's browser and
// /checks/verify-tang-poetry-tone-rules.mjs runs the same file in Node.
//
// Input is readings.json (made by research/tang-poetry-tone-rules/extract/extract.mjs):
//   g[char]          every Guangyun (1008) tone the character is listed under: 平 上 去 入
//   poem.c[line][i]  Cantonese jyutping of that character in its line (to-jyutping 3.1.1)
//   poem.m[line][i]  Mandarin pinyin with tone number (pinyin-pro 3.29.4)
//
// A tone class is 'P' (level, 平), 'Z' (oblique, 仄), 'A' (Guangyun lists it in both) or null
// (no reading). Only P and Z are scored.

export const LEVEL = 'P', OBLIQUE = 'Z', AMBIG = 'A';

export const REGULATED = ['五言絕句', '七言絕句', '五言律詩', '七言律詩'];
export const CONTROL = ['五言古詩', '七言古詩'];
export const group = type => REGULATED.includes(type) ? 'regulated' : CONTROL.includes(type) ? 'control' : 'yuefu';

// G: a set of Middle Chinese tones -> class
export function classG(tones) {
  if (!tones || !tones.length) return null;
  const lv = tones.includes('平');
  const ob = tones.some(t => t !== '平');
  return lv && ob ? AMBIG : lv ? LEVEL : OBLIQUE;
}
export const enteringG = tones => !!tones && tones.includes('入');

// C: jyutping -> class. Tones 1 and 4 are level unless the syllable is checked (-p -t -k).
export function classC(jp) {
  const m = /^([a-z]+)([1-6])$/.exec(jp || '');
  if (!m) return null;
  if (/[ptk]$/.test(m[1])) return OBLIQUE;
  return m[2] === '1' || m[2] === '4' ? LEVEL : OBLIQUE;
}

// M: pinyin with tone number -> class. 1 and 2 level, 3 and 4 oblique, neutral unscored.
export function classM(py) {
  const m = /^[a-zü:v]+([0-5])$/.exec(py || '');
  if (!m) return null;
  const t = m[1];
  return t === '1' || t === '2' ? LEVEL : t === '3' || t === '4' ? OBLIQUE : null;
}

// Every reader's class for every character of a poem: grid[reader][line][pos]
export function readPoem(poem, g) {
  const G = poem.lines.map(l => [...l].map(ch => classG(g[ch])));
  const C = poem.c.map(l => l.map(classC));
  const M = poem.m.map(l => l.map(classM));
  const E = poem.lines.map(l => [...l].map(ch => enteringG(g[ch])));
  return { G, C, M, E };
}

// The tests a poem is held to. Positions are 0-based [line, index].
// kind 'diff': the two cells must differ; 'same': must match; 'level'/'oblique': the one cell.
export function testsFor(poem) {
  const L = poem.len, n = poem.lines.length, T = [];
  const key = L === 5 ? [1, 3] : [1, 3, 5];
  for (let i = 0; i < n; i++) {
    for (let k = 0; k + 1 < key.length; k++) T.push({ rule: 'R1', kind: 'diff', cells: [[i, key[k]], [i, key[k + 1]]] });
  }
  for (let i = 0; i + 1 < n; i += 2) T.push({ rule: 'R2', kind: 'diff', cells: [[i, 1], [i + 1, 1]] });
  for (let i = 1; i + 1 < n; i += 2) T.push({ rule: 'R3', kind: 'same', cells: [[i, 1], [i + 1, 1]] });
  for (let i = 1; i < n; i += 2) T.push({ rule: 'R4', kind: 'level', cells: [[i, L - 1]] });
  for (let i = 2; i < n; i += 2) T.push({ rule: 'R5', kind: 'oblique', cells: [[i, L - 1]] });
  return T;
}

// One test under one reader: true (pass), false (fail) or null (not scorable)
export function judge(test, grid) {
  const v = test.cells.map(([i, j]) => grid[i][j]);
  if (v.some(x => x !== LEVEL && x !== OBLIQUE)) return null;
  if (test.kind === 'diff') return v[0] !== v[1];
  if (test.kind === 'same') return v[0] === v[1];
  if (test.kind === 'level') return v[0] === LEVEL;
  return v[0] === OBLIQUE;
}

export const RULES = ['R1', 'R2', 'R3', 'R4', 'R5'];
export const READERS = ['G', 'C', 'M'];

// Score the corpus. Returns tallies[group][rule][reader] = {pass, n} on the SAME tests
// (scorable under all three readers), and own[group][rule][reader] on each reader's own
// scorable tests, plus the tests that pass under G and fail under M.
export function score(data, { only } = {}) {
  const blank = () => Object.fromEntries(RULES.map(r => [r, Object.fromEntries(READERS.map(x => [x, { pass: 0, n: 0 }]))]));
  const same = {}, own = {}, flips = [], unscored = {};
  for (const poem of data.poemsData) {
    if (!poem.scored) continue;
    if (only && !only(poem)) continue;
    const grp = group(poem.type);
    same[grp] ??= blank(); own[grp] ??= blank(); unscored[grp] ??= { tests: 0, notAllThree: 0 };
    const rd = readPoem(poem, data.g);
    for (const t of testsFor(poem)) {
      unscored[grp].tests++;
      const res = Object.fromEntries(READERS.map(x => [x, judge(t, rd[x])]));
      for (const x of READERS) if (res[x] !== null) { own[grp][t.rule][x].n++; if (res[x]) own[grp][t.rule][x].pass++; }
      if (READERS.some(x => res[x] === null)) { unscored[grp].notAllThree++; continue; }
      for (const x of READERS) { same[grp][t.rule][x].n++; if (res[x]) same[grp][t.rule][x].pass++; }
      if (res.G && !res.M) flips.push({ id: poem.id, group: grp, rule: t.rule, cells: t.cells,
        entering: t.cells.some(([i, j]) => rd.E[i][j]),
        // an entering-tone syllable is itself one that Mandarin moved to the other class
        enteringChanged: t.cells.some(([i, j]) => rd.E[i][j] && rd.G[i][j] !== rd.M[i][j]) });
    }
  }
  return { same, own, flips, unscored };
}

export const pct = t => t.n ? 100 * t.pass / t.n : NaN;

// The corrected run: the corpus's 幹 put back to 乾 or 干 where Wikisource has them
// (readings.json `errata`). The pre-registered run is score(data); this is score(applyErrata(data)).
export function applyErrata(data) {
  const poemsData = data.poemsData.map(p => {
    const es = data.errata.filter(e => e.id === p.id);
    if (!es.length) return p;
    const q = { ...p, lines: [...p.lines], c: p.c.map(l => [...l]), m: p.m.map(l => [...l]) };
    for (const e of es) {
      const chs = [...q.lines[e.line]];
      chs[e.pos] = e.to; q.lines[e.line] = chs.join('');
      q.c[e.line][e.pos] = e.c; q.m[e.line][e.pos] = e.m;
    }
    return q;
  });
  return { ...data, poemsData };
}

// Poems that break no rule, counted on the tests all three readers can score
export function cleanPoems(data, grp = 'regulated') {
  const out = { poems: 0, G: 0, C: 0, M: 0 };
  for (const p of data.poemsData) {
    if (!p.scored || group(p.type) !== grp) continue;
    out.poems++;
    const rd = readPoem(p, data.g);
    const fails = { G: 0, C: 0, M: 0 };
    for (const t of testsFor(p)) {
      const res = READERS.map(x => judge(t, rd[x]));
      if (res.includes(null)) continue;
      READERS.forEach((x, k) => { if (!res[k]) fails[x]++; });
    }
    for (const x of READERS) if (!fails[x]) out[x]++;
  }
  return out;
}

// The tradition's "first special form" (zh.wikipedia 律诗, 第一类特殊形式): an unrhymed line whose
// last three syllables run oblique-level-oblique, (仄仄)平平仄平仄, so that key positions that
// should differ are both level. Returns true (it is that shape), 'maybe' (it would be, if the
// ambiguous syllable before the last two were oblique) or false. Odd-numbered lines only
// (index 0, 2, 4 ...), the line that does not rhyme.
export function specialForm(gridLine, lineIndex) {
  if (lineIndex % 2 !== 0) return false;
  const L = gridLine.length, a = gridLine[L - 4], b = gridLine[L - 3], c = gridLine[L - 2], d = gridLine[L - 1];
  if (a !== LEVEL || c !== LEVEL || d !== OBLIQUE) return false;
  if (b === OBLIQUE) return true;
  return b === AMBIG ? 'maybe' : false;
}

// Every R1 failure under G in a group, sorted by whether it is the special form
export function r1FailuresG(data, grp = 'regulated') {
  const out = { total: 0, special: 0, maybe: 0, other: [], specialLines: [] };
  for (const p of data.poemsData) {
    if (!p.scored || group(p.type) !== grp) continue;
    const rd = readPoem(p, data.g);
    for (const t of testsFor(p)) {
      if (t.rule !== 'R1' || judge(t, rd.G) !== false) continue;
      out.total++;
      const i = t.cells[0][0];
      const onTail = t.cells[1][1] === p.len - 2;
      const s = onTail ? specialForm(rd.G[i], i) : false;
      if (s === true) { out.special++; out.specialLines.push({ id: p.id, line: i, head: rd.G[i][p.len - 5] }); } else if (s === 'maybe') out.maybe++; else out.other.push({ id: p.id, line: i, cells: t.cells });
    }
  }
  return out;
}

// Syllables whose only Guangyun tone is entering, and what the two modern readers make of them
export function enteringStats(data, grp = 'regulated') {
  const out = { syllables: 0, entering: 0, mLevel: 0, mOblique: 0, mNone: 0, cOblique: 0, cLevel: 0, cNone: 0 };
  for (const p of data.poemsData) {
    if (!p.scored || group(p.type) !== grp) continue;
    p.lines.forEach((l, i) => [...l].forEach((ch, j) => {
      out.syllables++;
      const t = data.g[ch];
      if (!t || t.length !== 1 || t[0] !== '入') return;
      out.entering++;
      const m = classM(p.m[i][j]), c = classC(p.c[i][j]);
      if (m === LEVEL) out.mLevel++; else if (m === OBLIQUE) out.mOblique++; else out.mNone++;
      if (c === OBLIQUE) out.cOblique++; else if (c === LEVEL) out.cLevel++; else out.cNone++;
    }));
  }
  return out;
}

// All five rules together, on the same tests: {G:{pass,n}, C:..., M:...}
export function totals(sameGroup) {
  const out = Object.fromEntries(READERS.map(x => [x, { pass: 0, n: 0 }]));
  for (const r of RULES) for (const x of READERS) { out[x].pass += sameGroup[r][x].pass; out[x].n += sameGroup[r][x].n; }
  return out;
}

// The two-choice quatrain skeleton: what R1 to R5 force in a five-syllable quatrain, given the
// tone of line 1's second syllable and whether line 1 rhymes (if it does not, its last syllable
// is oblique by the tradition's convention; R5 itself starts at line 3). null = left free.
export function skeleton(first, rhymes) {
  const flip = t => (t === LEVEL ? OBLIQUE : LEVEL);
  const p2 = [first, flip(first), flip(first), first];
  return p2.map((x, i) => [null, x, null, flip(x), i === 0 ? (rhymes ? LEVEL : OBLIQUE) : i % 2 ? LEVEL : OBLIQUE]);
}
