export function markdownToText(markdown: string): string {
  return markdown
    .replace(/```[\s\S]*?```/g, '')
    .replace(/^#{1,6}\s+/gm, '')
    .replace(/\*{1,3}([^*]+)\*{1,3}/g, '$1')
    .replace(/_{1,3}([^_]+)_{1,3}/g, '$1')
    .replace(/~~([^~]+)~~/g, '$1')
    .replace(/`([^`]+)`/g, '$1')
    .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
    .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
    .replace(/^>\s?/gm, '')
    .replace(/^\s*[-*+]\s+/gm, '')
    .replace(/^\s*\d+[.)]\s+/gm, '')
    .replace(/^[-*_]{3,}$/gm, '')
    .replace(/<[^>]+>/g, '')
    .replace(/[^\S\n]+/g, ' ')
    .replace(/\n{3,}/g, '\n\n')
    .trim()
}

// Escapes text for type="text" XML elements (single XML-encoding layer).
export function escXml(s: string): string {
  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}

// Escapes plain text for type="html" Atom elements.
// The XML parser unescapes once (&amp; → &), then the HTML parser unescapes again
// (&amp; → &), so text must be double-encoded to survive both layers intact.
function escHtmlContent(s: string): string {
  return s
    .replace(/&/g, '&amp;amp;')
    .replace(/</g, '&amp;lt;')
    .replace(/>/g, '&amp;gt;')
    .replace(/"/g, '&amp;quot;')
}

export function buildAtomSummary(text: string, postUrl?: string, postTitle?: string): string {
  const html = escHtmlContent(text)
    .replace(/\n\n+/g, '&lt;/p&gt;&lt;p&gt;')
    .replace(/\n/g, '&lt;br/&gt;')

  let preamble = '';
  if (postUrl && postTitle) {
    const urlXml = escXml(postUrl);
    const titleXml = escHtmlContent(postTitle);
    preamble = `&lt;p&gt;&lt;em&gt;This is a text-only version of this post. If you want to read the full post with advanced elements like diagrams, it&amp;apos;s available at:&lt;br/&gt;&lt;a href=&quot;${urlXml}&quot;&gt;${titleXml}&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;`;
  }

  const separator = preamble ? '&lt;hr/&gt;' : '';
  return `<summary type="html">${preamble}${separator}&lt;p&gt;${html}&lt;/p&gt;</summary>`
}
