# core/context_processors.py
"""
Injects permission helpers into every template context.
Usage in templates:  {% if perms_can.student_add %}  or  {{ user_role }}
"""
from core.permissions import can, get_role_level, SUPPORT_ROLES, TEACHER_ROLES, MANAGEMENT_ROLES


class _PermProxy:
    """Allows {{ perms_can.student_add }} syntax in templates."""
    def __init__(self, user):
        self._user = user

    def __getattr__(self, action):
        return can(self._user, action)

    # also support {{ perms_can.student_add }} via dict-like access
    def __getitem__(self, action):
        return can(self._user, action)


def permissions(request):
    if not request.user.is_authenticated:
        return {}

    user = request.user
    role = getattr(getattr(user, 'staff_profile', None), 'role', None)
    level = get_role_level(user)

    return {
        'perms_can':      _PermProxy(user),
        'user_role':      role or ('superuser' if user.is_superuser else ''),
        'user_level':     level,
        'is_management':  level >= 70,
        'is_teacher_role': role in TEACHER_ROLES if role else False,
        'is_bursar_role': level >= 80,
        'is_head_role':   level >= 90,
        'is_support_only': role in SUPPORT_ROLES if role else False,
    }
