# retoor <retoor@molodetz.nl>

import html
import re
from functools import lru_cache

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
)

_HEADING = re.compile(r"<h([23])>(.*?)</h\1>", re.DOTALL)


def heading_slug(text: str) -> str:
    plain = html.unescape(re.sub(r"<[^>]+>", "", text)).strip().lower()
    slug = re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
    return slug or "section"


def _anchor_headings(rendered: str) -> str:
    seen: dict[str, int] = {}

    def _inject(match: re.Match) -> str:
        level, inner = match.group(1), match.group(2)
        slug = heading_slug(inner)
        count = seen.get(slug, 0)
        seen[slug] = count + 1
        if count:
            slug = f"{slug}-{count}"
        return (
            f'<h{level} id="{slug}">{inner}'
            f'<a class="docs-heading-anchor" href="#{slug}" aria-label="Link to this section">#</a>'
            f"</h{level}>"
        )

    return _HEADING.sub(_inject, rendered)


@lru_cache(maxsize=512)
def _render_markdown(source: str) -> str:
    return _anchor_headings(_markdown(source))


def _convert(match: re.Match) -> str:
    source = html.unescape(match.group(1)).strip()
    return f'<div class="docs-content">{_render_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)
