'use strict';

/**
 * lib/html-to-markdown.js — convert the curated data/oracle-docs article
 * fragments into the markdown dialect that markdownToHtml() in routes/blog.js
 * renders.
 *
 * Extracted verbatim from scripts/seed-blog.js. Three call sites now need it
 * (that seeder, scripts/publish-awr-ash-post.js, and the startup stub repair in
 * server.js) and three private copies is how they drift — which matters here,
 * because a converter that emits a slightly different dialect produces an article
 * that renders wrong rather than one that fails loudly.
 *
 * Handles the tag set those files actually use: h1-h3, p, pre>code, code, ul/ol/li,
 * strong, em, a. Anything else passes through untouched.
 */

function htmlToMarkdown(html) {
  const dec = (t) => t
    .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, ' ');
  const inline = (t) => {
    t = t.replace(/<a\s+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi, (_, h, x) => `[${x.trim()}](${h})`);
    t = t.replace(/<strong>([\s\S]*?)<\/strong>/gi, (_, x) => `**${x.trim()}**`);
    t = t.replace(/<em>([\s\S]*?)<\/em>/gi, (_, x) => `*${x.trim()}*`);
    t = t.replace(/<code>([\s\S]*?)<\/code>/gi, (_, x) => '`' + dec(x.trim()) + '`');
    return dec(t);
  };
  const codeBlocks = [], listBlocks = [];
  html = html.replace(/<pre>\s*<code>([\s\S]*?)<\/code>\s*<\/pre>/gi, (_, code) => {
    codeBlocks.push('```\n' + dec(code.replace(/^\n+|\n+$/g, '')) + '\n```');
    return ' @@C' + (codeBlocks.length - 1) + '@@ ';
  });
  html = html.replace(/<ul>([\s\S]*?)<\/ul>/gi, (_, inner) => {
    const items = [...inner.matchAll(/<li>([\s\S]*?)<\/li>/gi)].map(m => '- ' + inline(m[1].trim()).replace(/\s+/g, ' ').trim());
    listBlocks.push(items.join('\n')); return ' @@L' + (listBlocks.length - 1) + '@@ ';
  });
  html = html.replace(/<ol>([\s\S]*?)<\/ol>/gi, (_, inner) => {
    const items = [...inner.matchAll(/<li>([\s\S]*?)<\/li>/gi)].map((m, i) => (i + 1) + '. ' + inline(m[1].trim()).replace(/\s+/g, ' ').trim());
    listBlocks.push(items.join('\n')); return ' @@L' + (listBlocks.length - 1) + '@@ ';
  });
  html = html.replace(/<\/?article>/gi, '');
  html = html.replace(/<h1>[\s\S]*?<\/h1>/gi, '');            // drop title — rendered from post.title
  html = html.replace(/<h2>([\s\S]*?)<\/h2>/gi, (_, t) => `\n## ${inline(t.trim())}\n`);
  html = html.replace(/<h3>([\s\S]*?)<\/h3>/gi, (_, t) => `\n### ${inline(t.trim())}\n`);
  html = html.replace(/<p\b[^>]*>([\s\S]*?)<\/p>/gi, (_, t) => `\n${inline(t.trim())}\n`);
  html = html.replace(/ @@C(\d+)@@ /g, (_, i) => `\n${codeBlocks[+i]}\n`);
  html = html.replace(/ @@L(\d+)@@ /g, (_, i) => `\n${listBlocks[+i]}\n`);
  html = html.split('\n').map(l => l.replace(/[ \t]+$/, '')).join('\n');
  return html.replace(/\n{3,}/g, '\n\n').trim();
}

module.exports = { htmlToMarkdown };
