from django import template
from django.template import Node, TemplateSyntaxError, Variable

register = template.Library()

class HelpNode(Node):
    def __init__(self, nodelist, title, icon, extra_class):
        self.nodelist = nodelist
        self.title = title
        self.icon = icon
        self.extra_class = extra_class

    def resolve(self, val, context):
        if isinstance(val, Variable):
            try:
                return val.resolve(context)
            except Exception:
                return ''
        return val

    def render(self, context):
        title = self.resolve(self.title, context) or "Help"
        icon = self.resolve(self.icon, context) or "bi bi-info-circle"
        extra_class = self.resolve(self.extra_class, context) or "help-text"
        body = self.nodelist.render(context)
        return f'<details class="{extra_class}"><summary><i class="{icon}"></i> {title}</summary>{body}</details>'

@register.tag(name="help")
def do_help(parser, token):
    bits = token.split_contents()
    title = "Help"
    icon = "bi bi-info-circle"
    extra_class = "help-text"

    for bit in bits[1:]:
        if "=" in bit:
            key, val = bit.split("=", 1)
            if (val.startswith('"') and val.endswith('"')) or (val.startswith("'") and val.endswith("'")):
                val = val[1:-1]
            else:
                val = Variable(val)
            if key == "icon":
                icon = val
            elif key in ("class", "extra_class"):
                extra_class = val
            else:
                raise TemplateSyntaxError(f"Unknown keyword for help tag: {key}")
        else:
            v = bit
            if (v.startswith('"') and v.endswith('"')) or (v.startswith("'") and v.endswith("'")):
                title = v[1:-1]
            else:
                title = Variable(v)

    nodelist = parser.parse(("endhelp",))
    parser.delete_first_token()
    return HelpNode(nodelist, title, icon, extra_class)