"""Student lockout until parent completes KZM acknowledgment.

ACADEMIC paths are locked. MANAGEMENT (System K Kaam) stays open so
students can continue contributing work while parent acks.

Standards: Rule 14 (ACADEMIC vs MANAGEMENT); Rule 15.2; Rule 22;
  ISO 27001 A.5.15; PECA 2016 s.3; Section 23.13; MTSS/NCII.
"""
import re
from django.shortcuts import render


# Paths that are NEVER gated (regardless of ACADEMIC or MANAGEMENT)
ALWAYS_ALLOWED = (
    "/api/portal/my-todo/",
    "/api/portal/my-todo/action/",
    "/api/portal/login/",
    "/api/portal/logout/",
    "/api/portal/heartbeat/",
    "/api/portal/guide/kzm/",
    "/api/portal/acknowledgement/",
    "/api/portal/teacher/",
    "/api/portal/parent/",
    "/api/portal/admin/",
    "/api/portal/system-k-kaam-ka-safar/",
    "/api/portal/task/management/",
    "/api/portal/stage-complete/",
    "/api/portal/pipeline/",
    "/api/portal/book/",
    "/api/portal/my-assignments/",
    "/static/",
    "/media/",
    "/admin/",
    "/favicon",
    "/api/health/",
)

# Task detail URLs match /api/portal/task/<id>/ (integer). For these,
# gate only if the task category is ACADEMIC. MANAGEMENT stays open.
TASK_DETAIL_RE = re.compile(r"^/api/portal/task/(\d+)/")


class ParentAckGateMiddleware:
    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)
        user = getattr(request, "user", None)
        if not (user and user.is_authenticated and not user.is_staff):
            return self.get_response(request)

        path = request.path
        if any(path.startswith(p) for p in ALWAYS_ALLOWED):
            return self.get_response(request)

        # Special case: task detail — allow if MANAGEMENT
        m = TASK_DETAIL_RE.match(path)
        if m:
            from exams.models import StudentTask
            t = StudentTask.objects.filter(id=int(m.group(1))).only("category").first()
            if t and (t.category or "ACADEMIC").upper() == "MANAGEMENT":
                return self.get_response(request)

        # Everything else — check ack
        from exams.models import Student, ParentAcknowledgement
        student = Student.objects.filter(
            student_user=user, is_active=True,
        ).first()
        if not student:
            return self.get_response(request)
        if not student.parent_user:
            return self.get_response(request)
        # ---- PILOT BYPASS (temporary, auditable, flag-controlled) ----
        # Standards: ALCOA+ attributable; NIST AU-9 append-only audit.
        # Toggle: portal feature 'parent_ack_pilot_bypass' (default OFF).
        from exams.models import PortalFeature as _PF, PortalFeatureLog as _PFL
        if _PF.objects.filter(key='parent_ack_pilot_bypass', enabled=True).exists():
            _PFL.objects.create(
                key='parent_ack_bypass.' + student.code,
                old_enabled=False, new_enabled=False,
                changed_by=user,
                note=('pilot bypass active; path=' + path)[:240],
            )
            return self.get_response(request)
        # ---- END PILOT BYPASS ----

        has_ack = ParentAcknowledgement.objects.filter(
            user=student.parent_user,
            ack_type="kzm_disclaimer",
            ack_version="v2.0",
        ).exists()
        if has_ack:
            return self.get_response(request)
        return render(
            request,
            "exams/portal_student_locked.html",
            {"student": student},
            status=423,
        )
