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

register = template.Library()


@register.filter
def get_item(obj, key):
    try:
        return obj[key]
    except (KeyError, TypeError, IndexError):
        return None


@register.simple_tag(takes_context=True)
def update_query_param(context, key, value):
    """Return a querystring with a dynamic key updated.

    Django's built-in querystring tag does not allow dynamic keyword names,
    so this helper keeps compatibility for django-tables2 prefixed fields.
    """
    request = context.get("request")
    if request is None:
        return ""

    params = request.GET.copy()
    if value in (None, ""):
        params.pop(key, None)
    else:
        params[key] = value

    encoded = params.urlencode()
    return f"?{encoded}" if encoded else ""

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)