from django import template
from django.urls import reverse, NoReverseMatch
from django.apps import apps
from risks.navigation_registry import registry

register = template.Library()

@register.inclusion_tag("risks/_extra_nav.html", takes_context=True)
def render_extra_nav(context):
    user = context["request"].user
    extra_items = []

    for item in registry:
        # Check: ist die App überhaupt installiert?
        app_label = item["permission"].split(".")[0] if item["permission"] else None
        if app_label and not apps.is_installed(app_label):
            continue

        # Check: hat der User die Berechtigung?
        if item["permission"] and not user.has_perm(item["permission"]):
            continue

        # URL auflösen
        try:
            url = reverse(item["url_name"])
        except NoReverseMatch:
            continue

        extra_items.append({
            "label": item["label"],
            "url": url,
        })

    return {"extra_items": extra_items}
