"""Global portal kill switch.

When AcademySetting.portal_enabled=False, non-staff users see a maintenance
page. Staff can still log in and toggle it.

Standard: Rule 18 (kill switch); NIST SP 800-53 AC-3; ISO 27001 A.5.15.
"""
from django.http import HttpResponse
from django.shortcuts import render


ALLOW_PREFIXES = (
    "/admin/",
    "/static/",
    "/media/",
    "/health/",
    "/api/health/",
    "/api/portal/login/",
    "/api/portal/logout/",
)
ALLOW_EXACT = (
    "/api/academy/portal-toggle/",
)


class GlobalPortalMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # STAFF WORKSHOP BYPASS
        if request.path.startswith("/workshop/"):
            return self.get_response(request)
        path = request.path or "/"
        if any(path.startswith(p) for p in ALLOW_PREFIXES) or path in ALLOW_EXACT:
            return self.get_response(request)
        try:
            from academy.models import AcademySetting
            s = AcademySetting.load()
        except Exception:
            return self.get_response(request)
        if s.portal_enabled:
            return self.get_response(request)
        user = getattr(request, "user", None)
        if user and user.is_authenticated and (user.is_staff or user.is_superuser):
            return self.get_response(request)
        try:
            return render(request, "maintenance.html",
                          {"message": s.portal_message or ""}, status=503)
        except Exception:
            return HttpResponse("<h1>Portal band hai</h1>",
                                status=503,
                                content_type="text/html; charset=utf-8")
