"""Render operator-supplied markdown to sanitized, safe HTML for public display.

This is the XSS trust boundary: markdown may contain raw HTML, so the rendered
output is passed through bleach with a strict allowlist before it is marked safe.
"""

import bleach
import markdown as markdown_lib
from django.utils.safestring import mark_safe

ALLOWED_TAGS = {
    "p",
    "br",
    "strong",
    "em",
    "b",
    "i",
    "h2",
    "h3",
    "h4",
    "ul",
    "ol",
    "li",
    "a",
    "blockquote",
    "code",
    "pre",
    "hr",
    "del",
}
ALLOWED_ATTRS = {"a": ["href", "title"]}


def render_markdown(text: str) -> str:
    """Markdown -> sanitized HTML. Returns '' for blank input. Links open safely."""
    if not text or not text.strip():
        return ""
    html = markdown_lib.markdown(text, extensions=["extra", "sane_lists", "nl2br"])
    cleaned = bleach.clean(
        html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRS, strip=True
    )
    # Harden every surviving anchor (bleach already validated the href).
    cleaned = cleaned.replace("<a ", '<a rel="nofollow noopener" target="_blank" ')
    return mark_safe(cleaned)
