"""Authorization decorator for delegation-scoped writes.

Standards: NIST SP 800-162 (ABAC); NIST SP 800-53 AC-5, AC-6;
ISO 27001 A.5.15, A.5.18; Rule 10; Rule 13; Rule 28.

FIX (2026-10-28): DisciplineDelegation model is missing. Fall back to
matching exams.models_delegation.TaskDelegation by URL path, so students
with a valid time-bound delegation can access the pages.
"""
from functools import wraps
from django.core.exceptions import PermissionDenied
from django.contrib.auth.views import redirect_to_login
from django.utils import timezone


def _student_access_enabled():
    """Read the discipline student-access kill switch."""
    try:
        from academy.models import AcademySetting
        return bool(AcademySetting.load().discipline_student_access_enabled)
    except Exception:
        return True


def _has_discipline_delegation(user, scopes):
    """Try the native discipline delegation system (may not exist)."""
    try:
        from discipline.models import DisciplineDelegation
        return DisciplineDelegation.objects.filter(
            student=user,
            scope__in=scopes,
            revoked_at__isnull=True,
            expires_at__gt=timezone.now(),
        ).exists()
    except (ImportError, AttributeError):
        return False


def _has_exam_delegation_for_path(user, url_path):
    """Fallback: match exams.models_delegation.TaskDelegation by URL."""
    try:
        from exams.models_delegation import TaskDelegation
        now = timezone.now()
        url_path_norm = (url_path or '').rstrip('/') + '/'
        for d in TaskDelegation.objects.filter(assignee=user, expires_at__gt=now):
            try:
                target = getattr(d, 'custom_url', '') or getattr(d, 'target_url', '') or ''
            except Exception:
                target = ''
            if not target:
                continue
            target_norm = target.rstrip('/') + '/'
            if url_path_norm == target_norm or url_path_norm.startswith(target_norm):
                return True
        return False
    except Exception:
        return False


def discipline_scope_required(*scopes):
    """Allow the view only if request.user is a teacher OR has an active
    delegation of ANY of the provided `scopes` (or an active TaskDelegation
    whose target URL matches this view's path).
    """
    def decorator(view):
        @wraps(view)
        def wrapped(request, *args, **kwargs):
            user = getattr(request, "user", None)
            if not user or not user.is_authenticated:
                return redirect_to_login(request.get_full_path())
            if user.is_staff or user.is_superuser:
                return view(request, *args, **kwargs)
            if not _student_access_enabled():
                raise PermissionDenied("Student access abhi band hai.")

            # Check #1: native discipline delegation (preferred)
            if _has_discipline_delegation(user, scopes):
                return view(request, *args, **kwargs)

            # Check #2: fallback to exams TaskDelegation by URL
            if _has_exam_delegation_for_path(user, request.path):
                return view(request, *args, **kwargs)

            # Audit the denial (best-effort)
            try:
                from discipline.services.audit_ops import log_event
                from discipline.models import DisciplineAuditEvent as E
                log_event(
                    actor=user,
                    action=E.ACTION_DENIED_WRITE,
                    target_model=getattr(view, "__name__", "view"),
                    detail=f"scopes={scopes} path={request.path}",
                )
            except Exception:
                pass

            raise PermissionDenied("Aapko is section ka access nahi diya gaya.")
        return wrapped
    return decorator
