/**
 * markdown.mjs — Markdown renderer wrapping the marked library
 */

let markedLib = null;

async function ensureMarked() {
  if (markedLib) return markedLib;
  try {
    // marked is served by express.static from node_modules or lib
    const mod = await import('/lib/marked.esm.js');
    markedLib = mod.marked || mod.default;
  } catch {
    // Fallback: try the CDN-style path that server.mjs may expose
    try {
      const mod = await import('https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js');
      markedLib = mod.marked || mod.default;
    } catch {
      // Final fallback: basic passthrough
      markedLib = null;
    }
  }

  if (markedLib?.setOptions) {
    markedLib.setOptions({
      breaks: true,
      gfm: true
    });
  }

  return markedLib;
}

export async function renderMarkdown(text) {
  const marked = await ensureMarked();
  if (!marked) return escapeBasic(text);
  try {
    return marked.parse(text);
  } catch {
    return escapeBasic(text);
  }
}

export function renderMarkdownSync(text) {
  if (!markedLib) return escapeBasic(text);
  try {
    return markedLib.parse(text);
  } catch {
    return escapeBasic(text);
  }
}

function escapeBasic(text) {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\n/g, '<br>');
}
