import markdown
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from nh3 import clean

from markdown.extensions import Extension
from markdown.treeprocessors import Treeprocessor

register = template.Library()


class DaisyClassTreeprocessor(Treeprocessor):
    extra_classes = (
        ("table", "table"),
        ("ul", "list-disc m-2 gap-1"),
        ("ol", "list-decimal m-2 gap-1"),
        ("h1", "m-2"),
        ("p", "m-2"),
        ("h2", "m-2"),
        ("h3", "m-2"),
        ("h4", "m-2"),
        ("h5", "m-2"),
        ("h6", "m-2"),
    )

    def run(self, root):
        for extra_class in self.extra_classes:
            for elem in root.iter(extra_class[0]):
                current_class = elem.get("class", "")
                if current_class:
                    elem.set("class", f"{current_class} {extra_class[1]}")
                else:
                    elem.set("class", extra_class[1])
        return root


class DaisyClassExtension(Extension):
    def extendMarkdown(self, md):
        md.treeprocessors.register(
            DaisyClassTreeprocessor(md), "daisy_class_processor", 0
        )


@register.filter
@stringfilter
def convert_markdown(value):
    return mark_safe(
        markdown.markdown(
            clean(value),
            extensions=[
                "extra",
                "sane_lists",
                "nl2br",
                "codehilite",
                DaisyClassExtension(),
            ],
        )
    )
