"""Non-API views: health, SSO handoff, signed downloads, SPA shell (TZ 2.9.3, 2.9.9, 2.11.5)."""

from __future__ import annotations

import hmac
import json
import mimetypes
import re
from functools import lru_cache
from pathlib import Path
from typing import Any
from urllib.parse import quote

from django.conf import settings
from django.db import connection
from django.db.models import F
from django.http import (
    FileResponse,
    Http404,
    HttpRequest,
    HttpResponse,
    HttpResponseBadRequest,
    HttpResponseRedirect,
    JsonResponse,
)
from django.middleware.csrf import get_token
from django.shortcuts import render
from django.utils import timezone
from django.utils.html import json_script
from django.views.decorators.http import require_GET

from snapfile.core import ids
from snapfile.core.errors import ApiError
from snapfile.core.storage import store
from snapfile_render import ENGINE_VERSION

# --------------------------------------------------------------------------------------------- health


def health_live(request: HttpRequest) -> JsonResponse:
    return JsonResponse({"status": "ok"})


def health_ready(request: HttpRequest) -> JsonResponse:
    checks: dict[str, Any] = {}
    ok = True
    try:
        with connection.cursor() as cur:
            cur.execute("SELECT 1")
        checks["db"] = "ok"
    except Exception as exc:  # pragma: no cover
        checks["db"] = f"error: {type(exc).__name__}"
        ok = False
    try:
        settings.SNAPFILE_TMP_DIR.mkdir(parents=True, exist_ok=True)
        probe = settings.SNAPFILE_TMP_DIR / ".ready"
        probe.write_text("ok")
        checks["var"] = "ok"
    except OSError:
        checks["var"] = "error"
        ok = False
    return JsonResponse({"status": "ok" if ok else "error", "checks": checks}, status=200 if ok else 503)


def health_details(request: HttpRequest) -> JsonResponse:
    token = request.GET.get("token") or request.headers.get("X-Metrics-Token", "")
    allowed = (settings.METRICS_TOKEN and hmac.compare_digest(token, settings.METRICS_TOKEN)) or (
        getattr(request, "user", None) is not None and request.user.is_authenticated
    )
    if not allowed:
        return JsonResponse({"error": {"code": "FORBIDDEN", "message": "Token required"}}, status=403)
    from .doctor import diagnostics

    return JsonResponse(diagnostics())


def health_warm(request: HttpRequest) -> JsonResponse:
    token = request.GET.get("token", "")
    if not settings.WARM_TOKEN or not hmac.compare_digest(token, settings.WARM_TOKEN):
        return JsonResponse({"error": {"code": "FORBIDDEN", "message": "Token required"}}, status=403)
    import time

    t0 = time.perf_counter()
    import pypdfium2  # noqa: F401

    from snapfile.doctemplates.models import TemplateVersion
    from snapfile.render.plans import version_plan

    n = 0
    for v in TemplateVersion.objects.filter(template__current_version_id=F("id")).order_by("-published_at")[:10]:
        version_plan(v)
        n += 1
    return JsonResponse({"plans": n, "ms": int((time.perf_counter() - t0) * 1000)})


# --------------------------------------------------------------------------------------------- SSO handoff


def _error_page(request: HttpRequest, code: str, message: str, status: int) -> HttpResponse:
    return render(
        request,
        "snapfile/error.html",
        {"code": code, "message": message, "request_id": getattr(request, "request_id", "")},
        status=status,
    )


@require_GET
def editor_handoff(request: HttpRequest) -> HttpResponse:
    """``/editor/handoff?t=hk_…``: redeem, set refresh cookie, redirect into the SPA with ``#at=<jwt>``."""
    from snapfile.auth_sso.sessions import (
        access_token,
        ensure_target_access,
        redeem_handoff,
        session_payload,
        set_refresh_cookie,
    )
    from snapfile.integration.auth import client_ip

    token = request.GET.get("t") or request.GET.get("token") or ""
    if not token:
        return _error_page(request, "TOKEN_MISSING", "The sign-in link is incomplete.", 400)
    try:
        session = redeem_handoff(token, client_ip(request))
        ensure_target_access(session)
    except ApiError as exc:
        return _error_page(request, exc.code, exc.message, exc.status)
    access, _ = access_token(session)
    payload = session_payload(session)
    pid = payload["project"]["id"]
    target = payload.get("target")
    path = f"/editor/p/{pid}/t/{target['templateId']}" if target else f"/editor/p/{pid}"
    resp = HttpResponseRedirect(f"{path}#at={access}")
    resp["Cache-Control"] = "no-store"
    resp["Referrer-Policy"] = "no-referrer"
    set_refresh_cookie(request, resp, session)
    return resp


# --------------------------------------------------------------------------------------------- downloads


@require_GET
def signed_file(request: HttpRequest, file_id: str) -> HttpResponse:
    from snapfile.jobs.models import RenderFile
    from snapfile.render.signing import verify

    try:
        expires = int(request.GET.get("expires", "0"))
    except ValueError:
        return HttpResponseBadRequest("bad expires")
    disposition = request.GET.get("disposition", "attachment")
    if disposition not in ("attachment", "inline") or not verify(
        file_id, expires, disposition, request.GET.get("sig", "")
    ):
        return JsonResponse(
            {"error": {"code": "SIGNATURE_INVALID", "message": "Link is invalid or expired"}}, status=403
        )
    try:
        uid = ids.decode("fil", file_id)
    except ids.InvalidId as exc:
        raise Http404 from exc
    f = RenderFile.objects.filter(pk=uid).first()
    if f is None:
        raise Http404
    if f.deleted_at is not None or f.expires_at < timezone.now():
        return JsonResponse({"error": {"code": "GONE", "message": "File expired"}}, status=410)
    path = store().path(f.path)
    if not path.exists():
        return JsonResponse({"error": {"code": "GONE", "message": "File removed"}}, status=410)
    RenderFile.objects.filter(pk=f.pk).update(download_count=F("download_count") + 1)
    resp = FileResponse(open(path, "rb"), content_type=f.mime)  # noqa: SIM115
    ascii_name = f.filename.encode("ascii", "ignore").decode() or "file"
    resp["Content-Disposition"] = f"{disposition}; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(f.filename)}"
    resp["Cache-Control"] = "private, max-age=0, no-store"
    resp["X-Robots-Tag"] = "noindex"
    resp["Content-Length"] = str(f.size_bytes)
    return resp


# --------------------------------------------------------------------------------------------- SPA


_CONFIG_RE = re.compile(r'<script[^>]*id=["\']snapfile-config["\'][^>]*>.*?</script>', re.S)


@lru_cache(maxsize=1)
def _index_html(mtime: float) -> str:
    return (settings.FRONTEND_DIST / "index.html").read_text(encoding="utf-8")


def spa_config(request: HttpRequest, base: str) -> dict[str, Any]:
    from snapfile.core.superadmin import superadmin_enabled

    return {
        "basePath": base,
        "apiBase": "/internal/v1",
        "apiBaseAlias": "/api/editor/v1",
        "adminApiBase": "/admin/v1",
        "publicApiBase": "/api/v1",
        "assetBase": base,
        "locale": "en",
        "locales": ["en", "ru"],
        "csrfToken": get_token(request),
        "buildId": ENGINE_VERSION,
        "engineVersion": ENGINE_VERSION,
        "features": {
            "superAdmin": superadmin_enabled(),
            "pwa": False,
            "touchEditing": False,
            "allowHttpWebhooks": bool(settings.ALLOW_HTTP_FETCH),
        },
        "limits": {
            "maxUploadMb": settings.ASSET_MAX_MB,
            "maxFontMb": settings.FONT_MAX_MB,
            "maxNodes": 5000,
            "maxDraftMb": 10,
        },
        "auth": {
            "refreshPath": "/internal/v1/auth/refresh",
            "exchangePath": "/internal/v1/auth/exchange",
            "accessTokenTtl": settings.EDITOR_JWT_TTL,
        },
    }


def spa(request: HttpRequest, base: str = "/editor/", path: str = "") -> HttpResponse:
    """Catch-all for ``/editor/*`` and ``/app/*``: serves dist files that exist, otherwise index.html."""
    dist: Path = settings.FRONTEND_DIST
    if path and ".." not in path:
        candidate = (dist / path).resolve()
        if candidate.is_file() and dist.resolve() in candidate.parents:
            ctype, _ = mimetypes.guess_type(str(candidate))
            resp = FileResponse(open(candidate, "rb"), content_type=ctype or "application/octet-stream")  # noqa: SIM115
            if "/assets/" in f"/{path}":
                resp["Cache-Control"] = "public, max-age=31536000, immutable"
            return resp
    config = spa_config(request, base)
    index = dist / "index.html"
    if not index.is_file():
        resp = render(
            request,
            "snapfile/spa_stub.html",
            {
                "config_json": json_script(config, "snapfile-config"),
                "dist": str(dist),
                "config": json.dumps(config, indent=2),
            },
        )
        resp["Cache-Control"] = "no-cache, private"
        return resp
    html = _index_html(index.stat().st_mtime)
    tag = str(json_script(config, "snapfile-config"))
    if _CONFIG_RE.search(html):
        html = _CONFIG_RE.sub(lambda _m: tag, html, count=1)
    elif "</head>" in html:
        html = html.replace("</head>", f"{tag}\n</head>", 1)
    else:
        html = tag + html
    resp = HttpResponse(html, content_type="text/html; charset=utf-8")
    resp["Cache-Control"] = "no-cache, private"
    return resp
