"""Vérification centralisée des permissions (RBAC + portée d'agence)."""
from __future__ import annotations

from functools import wraps

from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect

CRITICAL_PERMS = {
    "agencies.add_agency",
    "agencies.change_agency",
    "agencies.deactivate_agency",
    "agencies.delete_agency",
    "agencies.assign_manager",
    "accounts.administer_roles",
    "sync.arbitrate_conflict",
    "sync.administer_nodes",
    "core.export_auditlog",
}


def has_perm(user, perm: str, agency=None) -> bool:
    if not getattr(user, "is_authenticated", False) or not user.is_active:
        return False
    if user.is_superuser:
        return True
    if perm in CRITICAL_PERMS and not getattr(user, "is_national_super_admin", False):
        return False
    if agency is not None:
        if not user.can_access_agency(agency):
            return False
        return user.has_module_perm(perm, agency)
    return user.has_module_perm(perm)


def require_perm(perm: str, agency_arg: str | None = None):
    """Décorateur de vue : exige une permission, redirige si anonyme."""
    def decorator(view):
        @wraps(view)
        def _wrapped(request, *args, **kwargs):
            if not request.user.is_authenticated:
                return redirect("accounts:login")
            agency = getattr(request, "agency", None)
            if agency_arg:
                from .tenancy import resolve_agency
                agency_id = request.POST.get(agency_arg) or request.GET.get(agency_arg)
                if agency_id:
                    agency = resolve_agency(request.user, agency_id)
                    if agency is None:
                        raise PermissionDenied("Agence hors périmètre")
            if not has_perm(request.user, perm, agency):
                raise PermissionDenied("Permission insuffisante")
            return view(request, *args, **kwargs)
        _wrapped.permissions_requises = (perm,)  # lu par le test de couverture des URL
        return _wrapped
    return decorator
