/**
 * Transforms poorly-formatted math HTML from practice question data
 * into readable notation using Unicode symbols and inline fraction HTML.
 *
 * Handles: fractions, powers, roots, function notation, spacing issues,
 * trailing commas, descriptive math text, and more.
 */
export function transformMathHtml(html: string): string {
  let s = html;

  /* ── 1. Fix decimal spacing: "0 . 0 2" → "0.02" ── */
  // Fix space around decimal point
  s = s.replace(/(\d)\s+\.\s+(\d)/g, '$1.$2');
  // Collapse spaced digits after decimal: "0.0 2" → "0.02"
  s = s.replace(/(\.\d) (\d)/g, '$1$2');
  s = s.replace(/(\.\d\d) (\d)/g, '$1$2');

  /* ── 2. Fix thousands separator spacing: "3, 000" → "3,000" ── */
  s = s.replace(/(\d),\s+(\d{3})\b/g, '$1,$2');
  // Run twice for millions: "3, 000, 000" → "3,000,000"
  s = s.replace(/(\d),\s+(\d{3})\b/g, '$1,$2');

  /* ── 3. Nth-root patterns: "the fourth root of, …, end root" ── */
  s = s.replace(/the\s+fourth\s+root\s+of,?\s*(.+?),?\s*end\s+root/gi, '⁴√($1)');
  s = s.replace(/the\s+cube\s+root\s+of,?\s*(.+?),?\s*end\s+root/gi, '∛($1)');
  s = s.replace(/the\s+square\s+root\s+of,?\s*(.+?),?\s*end\s+root/gi, '√($1)');

  /* ── 4. "the √ …, end root" → "√(…)" ── */
  s = s.replace(/the\s+√,?\s*(.+?),?\s*end\s+root/gi, '√($1)');

  /* ── 5. "the fraction with numerator … and denominator …[, end fraction]" ── */
  // With "end fraction" marker
  s = s.replace(
    /the\s+fraction\s+with\s+numerator\s+(.+?),?\s+and\s+denominator\s+(.+?),?\s*end\s+fraction/gi,
    '<span class="ifrac"><span class="num">$1</span><span class="den">$2</span></span>'
  );
  // Without "end fraction" marker (common variant)
  s = s.replace(
    /the\s+fraction\s+with\s+numerator\s+(.+?),?\s+and\s+denominator\s+([^,]+)/gi,
    '<span class="ifrac"><span class="num">$1</span><span class="den">$2</span></span>'
  );

  /* ── 6. "the fraction X over Y[, end fraction]" ── */
  s = s.replace(
    /the\s+fraction\s+(.+?)\s+over\s+(.+?),?\s*end\s+fraction/gi,
    '<span class="ifrac"><span class="num">$1</span><span class="den">$2</span></span>'
  );
  // Without "end fraction"
  s = s.replace(
    /the\s+fraction\s+(.+?)\s+over\s+([^,]+)/gi,
    '<span class="ifrac"><span class="num">$1</span><span class="den">$2</span></span>'
  );

  /* ── 7. Clean up remaining end markers ── */
  s = s.replace(/,?\s*end\s+root/gi, '');
  s = s.replace(/,?\s*end\s+fraction/gi, '');

  /* ── 8. Standalone "the √ " → "√" ── */
  s = s.replace(/the\s+√\s*/gi, '√');

  /* ── 9. Power notation → superscripts ── */
  const namedPowers: Record<string, string> = {
    first: '¹', second: '²', third: '³', fourth: '⁴',
    fifth: '⁵', sixth: '⁶', seventh: '⁷', eighth: '⁸',
    ninth: '⁹', tenth: '¹⁰',
  };

  // ", to the Nth power" or "to the x power"
  s = s.replace(/,?\s*to\s+the\s+(\w+)\s+power,?/gi, (_, p) => {
    const key = p.toLowerCase();
    if (namedPowers[key]) return namedPowers[key];
    // Variable power like "x", "n", "m"
    return `<sup>${p}</sup>`;
  });

  // "raised to the one half power" etc.
  s = s.replace(/,?\s*raised\s+to\s+the\s+one\s+half\s+power,?/gi, '<sup>½</sup>');
  s = s.replace(/,?\s*raised\s+to\s+the\s+one\s+third\s+power,?/gi, '<sup>⅓</sup>');
  s = s.replace(/,?\s*raised\s+to\s+the\s+one\s+fourth\s+power,?/gi, '<sup>¼</sup>');

  /* ── 10. Fraction words → Unicode fractions ── */
  // Map of numerator words → digits
  const numWord: Record<string, string> = {
    one: '1', two: '2', three: '3', four: '4', five: '5',
    six: '6', seven: '7', eight: '8', nine: '9', ten: '10',
    eleven: '11', twelve: '12',
  };
  // Map of denominator words (singular + plural) → digits
  const denWord: Record<string, string> = {
    half: '2', halves: '2', third: '3', thirds: '3',
    fourth: '4', fourths: '4', fifth: '5', fifths: '5',
    sixth: '6', sixths: '6', seventh: '7', sevenths: '7',
    eighth: '8', eighths: '8', ninth: '9', ninths: '9',
    tenth: '10', tenths: '10',
  };
  // Build inline fraction HTML using the ifrac class (stacked, legible)
  const buildFrac = (n: string, d: string) =>
    `<span class="ifrac"><span class="num">${n}</span><span class="den">${d}</span></span>`;

  // Build regex: match "negative, NUM DEN" or "NUM DEN" (word numerators)
  const numPat = Object.keys(numWord).join('|');
  const denPat = Object.keys(denWord).join('|');
  const fracRe = new RegExp(
    `(negative,?\\s+)?(${numPat})\\s+(${denPat})`,
    'gi'
  );
  s = s.replace(fracRe, (_, neg, nw, dw) => {
    const n = numWord[nw.toLowerCase()];
    const d = denWord[dw.toLowerCase()];
    if (!n || !d) return _;
    const frac = buildFrac(n, d);
    return (neg ? '−' : '') + frac;
  });

  // Also handle digit numerators: "4 thirds", "7 eighths", etc.
  const digitFracRe = new RegExp(
    `\\b(\\d+)\\s+(${denPat})\\b`,
    'gi'
  );
  s = s.replace(digitFracRe, (_, digits, dw) => {
    const d = denWord[dw.toLowerCase()];
    if (!d) return _;
    return buildFrac(digits, d);
  });

  /* ── 11. Function notation: "f of x" → "f(x)", "f of 5" → "f(5)" ── */
  s = s.replace(/\b([a-zA-Z])\s+of\s+([a-zA-Z0-9])\b/g, '$1($2)');

  /* ── 12. " comma " → ", " (coordinate text) ── */
  s = s.replace(/\s+comma\s+/g, ', ');

  /* ── 13. Trailing comma in parentheses: "(stuff, )" → "(stuff)" ── */
  s = s.replace(/,\s*\)/g, ')');

  /* ── 14. Parenthesized fractions: "(num) / (den)" → inline fraction ── */
  s = s.replace(
    /\(([^()]+)\)\s*\/\s*\(([^()]+)\)/g,
    '<span class="ifrac"><span class="num">$1</span><span class="den">$2</span></span>'
  );

  /* ── 15. Clean up double spaces ── */
  s = s.replace(/  +/g, ' ');

  return s;
}

/**
 * Returns true if a question is too broken to display
 * (e.g. contains unresolved (expression) placeholders).
 */
export function isQuestionBroken(q: {
  questionHtml: string;
  choices: { text: string }[];
}): boolean {
  if (q.questionHtml.includes('<em>(expression)</em>')) return true;
  const broken = q.choices.filter(c => c.text.includes('<em>(expression)</em>')).length;
  if (broken >= 2) return true;

  return false;
}
