"""Request id, API path aliases and security headers."""

from __future__ import annotations

import re
from collections.abc import Callable

from django.http import HttpRequest, HttpResponse

from .ids import uuid7

_RID_RE = re.compile(r"^[A-Za-z0-9_\-]{8,64}$")

# The editor spec (03_frontend) addresses the internal API as /api/editor/v1 and the admin API as
# /api/admin/v1; the backend TZ uses /internal/v1 and /admin/v1. Both spellings are served.
ALIASES = (("/api/editor/v1/", "/internal/v1/"), ("/api/admin/v1/", "/admin/v1/"))


class RequestIdMiddleware:
    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
        self.get_response = get_response

    def __call__(self, request: HttpRequest) -> HttpResponse:
        rid = request.META.get("HTTP_X_REQUEST_ID", "")
        request.request_id = rid if _RID_RE.match(rid) else str(uuid7())  # type: ignore[attr-defined]
        response = self.get_response(request)
        response["X-Request-Id"] = request.request_id  # type: ignore[attr-defined]
        return response


class ApiAliasMiddleware:
    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
        self.get_response = get_response

    def __call__(self, request: HttpRequest) -> HttpResponse:
        request.original_path = request.path_info  # type: ignore[attr-defined]
        for alias, target in ALIASES:
            if request.path_info.startswith(alias):
                request.path_info = target + request.path_info[len(alias) :]
                request.path = request.path_info
                break
        return self.get_response(request)


class SecurityHeadersMiddleware:
    CSP = (
        "default-src 'self'; img-src 'self' data: blob:; font-src 'self' data: blob:; "
        "style-src 'self' 'unsafe-inline'; connect-src 'self'; worker-src 'self' blob:"
    )

    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
        self.get_response = get_response

    def __call__(self, request: HttpRequest) -> HttpResponse:
        response = self.get_response(request)
        path = request.path_info
        if path.startswith(("/editor", "/app")) and "Content-Security-Policy" not in response:
            ancestors = getattr(request, "frame_ancestors", None) or "'self'"
            response["Content-Security-Policy"] = f"{self.CSP}; frame-ancestors {ancestors}"
            if "X-Frame-Options" in response:
                del response["X-Frame-Options"]
        return response
