"""Kernel firewall middleware.

Turn B (2026-10-11). Companion: design/PIPELINE-FIREWALL-v1.0.md

When PortalFeature "pipeline_freeze" is enabled, block every write
(POST/PUT/PATCH/DELETE) that would hit a kernel view. Non-staff users
receive HTTP 423 Locked. Staff always bypass (Rule 13 HITL).

Standards:
  AWS REL05-BP01 (Cell-Based Architecture)
  Azure Bulkhead Pattern
  Fowler Feature Toggles 2017
  ISO 27001 A.8.32 (change management)
  Rule 13 (HITL), Rule 23, Rule 28
"""
from django.http import HttpResponse


# Every write view that touches the pipeline write path.
# Kept in code (not read from manifest) for two reasons:
# 1. The middleware must run before manifest access.
# 2. If the manifest is corrupted, the middleware still works.
KERNEL_VIEWS = {
    "portal_task_submit",
    "book_handoff",
    "book_recall",
    "book_members",
    "portal_teacher_pipelines",
    "portal_stage_complete",
    "portal_teacher_stage_completions",
    "portal_acknowledgement",
    "portal_parent_voice_task",
}

WRITE_METHODS = {"POST", "PUT", "PATCH", "DELETE"}


def _is_frozen():
    try:
        from exams.models import PortalFeature
        return PortalFeature.objects.filter(
            key="pipeline_freeze", enabled=True
        ).exists()
    except Exception:
        # Fail-open: if the DB is unreachable, do not block students.
        # Standards: Saltzer & Schroeder 1975 — but fail-open is safer
        # for the student here than fail-closed. The freeze flag is
        # a developer convenience, not a security control.
        return False


def _frozen_message():
    return (
        "<html lang=\"ur-Latn\"><head><title>System update</title></head>"
        "<body style=\"font-family:sans-serif;max-width:600px;margin:80px auto;"
        "text-align:center\">"
        "<h2>System update chal raha hai</h2>"
        "<p>Thori der mein dobara koshish karein. Aap ka kaam safe hai.</p>"
        "</body></html>"
    )


class KernelGuardMiddleware:
    """Block student writes to kernel views while pipeline_freeze is ON.

    Staff always bypass. Read methods are never blocked.
    """

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

    def __call__(self, request):
        return self.get_response(request)

    def process_view(self, request, view_func, view_args, view_kwargs):
        if request.method not in WRITE_METHODS:
            return None
        user = getattr(request, "user", None)
        if not (user and user.is_authenticated):
            return None
        if user.is_staff:
            return None
        if not _is_frozen():
            return None
        view_name = getattr(view_func, "__name__", "")
        if view_name not in KERNEL_VIEWS:
            return None
        return HttpResponse(_frozen_message(), status=423)
