from django.urls import include, path, re_path
from django.http import HttpResponse, HttpResponseNotFound
from pathlib import Path

DIST_DIR = Path(__file__).resolve().parent.parent / "frontend" / "dist"

CONTENT_TYPES = {
    ".html": "text/html",
    ".js": "application/javascript",
    ".css": "text/css",
    ".svg": "image/svg+xml",
    ".png": "image/png",
    ".ico": "image/x-icon",
    ".woff2": "font/woff2",
    ".json": "application/json",
}


def serve_dist(request, path="index.html"):
    file_path = (DIST_DIR / path).resolve()

    if not str(file_path).startswith(str(DIST_DIR)) or not file_path.is_file():
        return HttpResponseNotFound()

    ct = CONTENT_TYPES.get(file_path.suffix, "application/octet-stream")
    return HttpResponse(file_path.read_bytes(), content_type=ct)


urlpatterns = [
    path("api/mizan/", include("mizan.urls")),
    re_path(r"^(?P<path>assets/.+)$", serve_dist),
    path("favicon.ico", serve_dist, {"path": "favicon.ico"}),
    path("", serve_dist),
]
