import markdown as _md
from django.utils.html import escape, mark_safe

FORMAT_PLAIN = "plain"
FORMAT_MARKDOWN = "markdown"
FORMAT_HTML = "html"

CONTENT_FORMAT_CHOICES = [
    (FORMAT_PLAIN, "Plain Text"),
    (FORMAT_MARKDOWN, "Markdown"),
    (FORMAT_HTML, "HTML"),
]

_MD_EXTENSIONS = ["extra", "nl2br", "sane_lists"]


def render_content(text: str, fmt: str) -> str:
    if not text:
        return mark_safe("")

    if fmt == FORMAT_HTML:
        return mark_safe(text)

    if fmt == FORMAT_MARKDOWN:
        return mark_safe(_md.markdown(text, extensions=_MD_EXTENSIONS))

    paragraphs = text.split("\n\n")
    parts = []
    for para in paragraphs:
        para = para.strip()
        if para:
            lines = escape(para).split("\n")
            parts.append("<p>" + "<br>".join(lines) + "</p>")
    return mark_safe("".join(parts) if parts else f"<p>{escape(text)}</p>")
