# retoor <retoor@molodetz.nl>

import html
import re

import mistune

_markdown = mistune.create_markdown(
    escape=False,
    hard_wrap=True,
    plugins=["table", "strikethrough", "url"],
)

_RENDER_BLOCK = re.compile(
    r'<div class="docs-content" data-render>(.*?)</div>', re.DOTALL
)


def _convert(match: re.Match) -> str:
    source = html.unescape(match.group(1)).strip()
    return f'<div class="docs-content">{_markdown(source)}</div>'


def render_prose(slug: str, context: dict) -> str:
    from devplacepy.templating import templates

    rendered = templates.env.get_template(f"docs/{slug}.html").render(**context)
    return _RENDER_BLOCK.sub(_convert, rendered, count=1)
