from django.apps import apps
from django.db.models import Q, Value
from django.db.models.functions import Lower, Replace
from django.template import Context, Template

from .utils import uuid


def convert_snippet(obj):
    try:
        Snippet = apps.get_model("roadrunner.block")
    except LookupError:
        raise KeyError("There are no snippets")

    try:
        snippets = Snippet.objects.annotate(
            slug=Lower(Replace("name", Value(" "), Value("-")))
        )
        snip = snippets.get(Q(name=obj["type"]) | Q(slug=obj["type"]))
        template = Template(snip.html)
        html = template.render(Context(obj["value"]))
        return {"type": "html", "value": {"html": html}, "id": uuid()}
    except Snippet.DoesNotExist:
        raise KeyError("this is not a snippet")
