from django.core.exceptions import PermissionDenied
from django.utils import timezone
from functools import wraps

def require_delegation(view_func):
    """
    Industry-standard decorator to ensure the user has an active, time-bound 
    delegation for the current URL. Blocks access if not delegated or expired.
    """
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        from exams.models_delegation import TaskDelegation
        
        # Check if user is superuser (Owner) - they bypass this
        if request.user.is_superuser:
            return view_func(request, *args, **kwargs)

        # Use request.path to match the exact route without query strings
        current_path = request.path
        
        # Check for an active delegation matching this exact URL in custom_url
        has_access = False
        delegations = TaskDelegation.objects.filter(
            assignee=request.user,
            expires_at__gt=timezone.now()
        )
        current_path_norm = current_path.rstrip('/') + '/'
        
        for d in delegations:
            if not d.custom_url:
                continue
            target_norm = d.custom_url.rstrip('/') + '/'
            if current_path_norm == target_norm or current_path_norm.startswith(target_norm):
                has_access = True
                break

        if not has_access:
            raise PermissionDenied(
                "Aap ke paas is page ko kholne ki ijazat nahi hai, "
                "ya aap ka waqt (delegation) khatam ho gaya hai."
            )
        
        return view_func(request, *args, **kwargs)
    return _wrapped_view

def require_teacher_or_delegation(view_func):
    """
    Allows access if the user is a Teacher (Staff) OR if they are a Student
    with an active, time-bound delegation for the current URL.
    """
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        from exams.models_delegation import TaskDelegation
        
        # 1. Superuser bypasses everything
        if request.user.is_superuser:
            return view_func(request, *args, **kwargs)
            
        # 2. Teacher bypasses everything
        if request.user.is_staff:
            return view_func(request, *args, **kwargs)
            
        # 3. Student check (Delegation)
        current_path = request.path
        has_access = False
        delegations = TaskDelegation.objects.filter(
            assignee=request.user,
            expires_at__gt=timezone.now()
        )
        current_path_norm = current_path.rstrip('/') + '/'
        
        for d in delegations:
            if not d.custom_url:
                continue
            target_norm = d.custom_url.rstrip('/') + '/'
            if current_path_norm == target_norm or current_path_norm.startswith(target_norm):
                has_access = True
                break

        if has_access:
            return view_func(request, *args, **kwargs)

        raise PermissionDenied(
            "Aap ke paas is page ko kholne ki ijazat nahi hai, "
            "ya aap ka waqt (delegation) khatam ho gaya hai."
        )
    return _wrapped_view
