"""LD010 — PWA shell views.

Serve the web app manifest and the service worker at root scope (``/``).
A service worker can only register pages within its own URL path, so
``/service-worker.js`` must be served from the site root rather than the
default ``/static/js/`` path.

The actual file contents live under ``static/`` for editor convenience and
to inherit WhiteNoise compression in production; these views read those
files and return them with the correct Content-Type + Service-Worker-Allowed
headers.
"""
from __future__ import annotations

from pathlib import Path

from django.conf import settings
from django.http import FileResponse, Http404
from django.views.generic import View


def _static_file(rel_path: str) -> Path:
    return Path(settings.BASE_DIR) / "static" / rel_path


class ManifestView(View):
    """Serve manifest.webmanifest at /manifest.webmanifest."""

    def get(self, request, *args, **kwargs):
        path = _static_file("manifest.webmanifest")
        if not path.exists():
            raise Http404("manifest missing")
        response = FileResponse(path.open("rb"), content_type="application/manifest+json")
        response["Cache-Control"] = "public, max-age=600"
        return response


class ServiceWorkerView(View):
    """Serve service-worker.js at /service-worker.js with root scope."""

    def get(self, request, *args, **kwargs):
        path = _static_file("js/service-worker.js")
        if not path.exists():
            raise Http404("service worker missing")
        response = FileResponse(path.open("rb"), content_type="application/javascript")
        # Allow root-scope registration even though the file is technically
        # under a subdirectory; required by the SW spec.
        response["Service-Worker-Allowed"] = "/"
        # Service workers should not be cached aggressively — new deploys must
        # take effect on the next page load.
        response["Cache-Control"] = "no-cache, max-age=0"
        return response
