"""Internal API: asset library and fonts (TZ I30-I40)."""

from __future__ import annotations

import json
from typing import Any

from django.conf import settings
from django.db.models import Q
from django.http import FileResponse, HttpRequest, HttpResponse
from ninja import File, Form, Router, Schema, Status
from ninja.files import UploadedFile

from snapfile.auth_sso.auth import EditorJwtAuth, require
from snapfile.core import ids
from snapfile.core.audit import audit
from snapfile.core.errors import ApiError
from snapfile.core.http import FetchError
from snapfile.core.http import request as http_request
from snapfile.core.pagination import paginate
from snapfile.core.storage import store
from snapfile.doctemplates.models import Template, TemplateVersion

from .fonts import font_dict, upload_font
from .images import asset_dict, upload_image
from .models import Asset, Font

router = Router(auth=EditorJwtAuth(), tags=["internal: assets & fonts"])
IMMUTABLE = "public, max-age=31536000, immutable"


class AssetPatch(Schema):
    name: str | None = None
    folder: str | None = None


class FromUrlIn(Schema):
    url: str
    name: str | None = None
    folder: str | None = None


def _asset(request: HttpRequest, asset_id: str) -> Asset:
    try:
        uid = ids.decode("ast", asset_id)
    except ids.InvalidId as exc:
        raise ApiError(404, "NOT_FOUND", "Asset not found") from exc
    a = Asset.objects.filter(project=request.project, pk=uid, deleted_at__isnull=True).first()  # type: ignore[attr-defined]
    if a is None:
        raise ApiError(404, "NOT_FOUND", "Asset not found")
    return a


def _font(request: HttpRequest, font_id: str) -> Font:
    try:
        uid = ids.decode("fnt", font_id)
    except ids.InvalidId as exc:
        raise ApiError(404, "NOT_FOUND", "Font not found") from exc
    f = Font.objects.filter(
        Q(project=request.project) | Q(project__isnull=True),
        pk=uid,  # type: ignore[attr-defined]
        deleted_at__isnull=True,
    ).first()
    if f is None:
        raise ApiError(404, "NOT_FOUND", "Font not found")
    return f


def _in_use(project: Any, needle: str) -> bool:
    """Referenced by any draft or published version of the project (simple text scan, small projects)."""
    for doc in Template.objects.filter(project=project, deleted_at__isnull=True).values_list(
        "draft_document", flat=True
    ):
        if needle in json.dumps(doc):
            return True
    for doc in TemplateVersion.objects.filter(project=project).values_list("document", flat=True):
        if needle in json.dumps(doc):
            return True
    return False


# --------------------------------------------------------------------------------------------- assets


@router.get("assets", summary="I30. Asset library")
def list_assets(
    request: HttpRequest,
    folder: str | None = None,
    kind: str | None = None,
    q: str | None = None,
    limit: int = 100,
    cursor: str | None = None,
) -> Any:
    qs = Asset.objects.filter(project=request.project, deleted_at__isnull=True)  # type: ignore[attr-defined]
    if folder is not None:
        qs = qs.filter(folder=folder or None)
    if kind:
        qs = qs.filter(kind=kind)
    if q:
        qs = qs.filter(name__icontains=q)
    rows, nxt = paginate(qs, limit, cursor)
    return {"data": [asset_dict(a) for a in rows], "next_cursor": nxt}


@router.post("assets", response={201: dict}, summary="I31. Upload images (multipart files[], up to 20)")
def upload_assets(request: HttpRequest, files: list[UploadedFile] = File(...), folder: str | None = Form(None)) -> Any:
    principal = require(request, "upload")
    if len(files) > 20:
        raise ApiError(422, "VALIDATION_FAILED", "At most 20 files per request")
    out = []
    for f in files:
        data = f.read()
        asset, dedup = upload_image(
            request.project,
            f.name or "image",
            data,
            folder,  # type: ignore[attr-defined]
            principal.snapshot(),
            settings.ASSET_MAX_MB,
        )
        if not dedup:
            audit(
                "asset.upload",
                principal.actor,
                project_id=asset.project_id,
                subject_type="asset",
                subject_id=asset.id,
                changes={"name": asset.name, "size": asset.size_bytes},
                request=request,
            )
        out.append(asset_dict(asset, dedup))
    return Status(201, {"data": out})


@router.post("assets/from-url", response={201: dict}, summary="I32. Upload an image by URL (SSRF-protected)")
def upload_from_url(request: HttpRequest, body: FromUrlIn) -> Any:
    principal = require(request, "upload")
    try:
        res = http_request("GET", body.url, timeout=5.0, max_bytes=settings.ASSET_MAX_MB * 1024 * 1024)
    except FetchError as exc:
        raise ApiError(422, "IMAGE_FETCH_FAILED", str(exc)) from exc
    if res.status != 200:
        raise ApiError(422, "IMAGE_FETCH_FAILED", f"Remote server answered {res.status}")
    name = body.name or body.url.rsplit("/", 1)[-1][:120] or "image"
    asset, dedup = upload_image(
        request.project,
        name,
        res.data,
        body.folder,
        principal.snapshot(),  # type: ignore[attr-defined]
        settings.ASSET_MAX_MB,
        source_url=body.url[:1024],
    )
    return Status(201, {"asset": asset_dict(asset, dedup)})


class ClipboardIn(Schema):
    assets: list[str] = []
    fonts: list[str] = []


class ImportIn(Schema):
    token: str


CLIPBOARD_SALT = "snapfile.clipboard"
CLIPBOARD_TTL = 7 * 24 * 3600


def _decode_many(kind: str, values: list[str]) -> list[Any]:
    out = []
    for v in values[:500]:
        try:
            out.append(ids.decode(kind, v))
        except ids.InvalidId:
            continue
    return out


@router.post("assets/clipboard", summary="Copy layers: a signed token for the images and fonts they use")
def clipboard_token(request: HttpRequest, body: ClipboardIn) -> Any:
    """Layers copied in one project and pasted in another bring their files along: the token names this project's
    assets and fonts, POST assets/import in the other project copies them there. Signed, valid for a week."""
    from django.core import signing

    project = request.project  # type: ignore[attr-defined]
    a = Asset.objects.filter(project=project, pk__in=_decode_many("ast", body.assets), deleted_at__isnull=True)
    f = Font.objects.filter(project=project, pk__in=_decode_many("fnt", body.fonts), deleted_at__isnull=True)
    payload = {"p": project.id.hex, "a": [x.id.hex for x in a], "f": [x.id.hex for x in f]}
    return {"token": signing.dumps(payload, salt=CLIPBOARD_SALT, compress=True)}


@router.post("assets/import", summary="Paste layers: copy the images and fonts of a clipboard token into this project")
def clipboard_import(request: HttpRequest, body: ImportIn) -> Any:
    from django.core import signing

    principal = require(request, "upload")
    project = request.project  # type: ignore[attr-defined]
    try:
        payload = signing.loads(body.token, salt=CLIPBOARD_SALT, max_age=CLIPBOARD_TTL)
    except signing.BadSignature as exc:
        raise ApiError(422, "CLIPBOARD_EXPIRED", "Copy the layers again") from exc
    assets: dict[str, Any] = {}
    fonts: dict[str, Any] = {}
    same = payload.get("p") == project.id.hex
    st = store()
    for src in Asset.objects.filter(project_id=payload.get("p"), pk__in=payload.get("a", []), deleted_at__isnull=True):
        old = ids.encode("ast", src.id) or ""
        if same:
            assets[old] = asset_dict(src)
            continue
        try:
            data = st.path(src.path).read_bytes()
        except OSError:
            continue
        copy, dedup = upload_image(
            project, src.name, data, src.folder, principal.snapshot(), settings.ASSET_MAX_MB, source_url=src.source_url
        )
        assets[old] = asset_dict(copy, dedup)
    for src in Font.objects.filter(project_id=payload.get("p"), pk__in=payload.get("f", []), deleted_at__isnull=True):
        old = ids.encode("fnt", src.id) or ""
        if same:
            fonts[old] = font_dict(src)
            continue
        try:
            data = st.path(src.path).read_bytes()
        except OSError:
            continue
        fonts[old] = font_dict(upload_font(project, data, principal.snapshot()))
    if not same and (assets or fonts):
        audit(
            "clipboard.import",
            principal.actor,
            project_id=project.id,
            subject_type="project",
            subject_id=project.id,
            changes={"assets": len(assets), "fonts": len(fonts)},
            request=request,
        )
    return {"assets": assets, "fonts": fonts}


@router.patch("assets/{asset_id}", summary="I33. Rename / move to folder")
def patch_asset(request: HttpRequest, asset_id: str, body: AssetPatch) -> Any:
    require(request, "upload")
    a = _asset(request, asset_id)
    if body.name is not None:
        a.name = body.name[:255]
    if body.folder is not None:
        a.folder = body.folder or None
    a.save(update_fields=["name", "folder", "updated_at"])
    return {"asset": asset_dict(a)}


@router.delete("assets/{asset_id}", response={204: None}, summary="I34. Delete (409 ASSET_IN_USE when referenced)")
def delete_asset(request: HttpRequest, asset_id: str, force: bool = False) -> Any:
    principal = require(request, "upload")
    a = _asset(request, asset_id)
    aid = ids.encode("ast", a.id) or ""
    if _in_use(a.project, aid) and not (force and principal.role == "admin"):
        raise ApiError(409, "ASSET_IN_USE", "Asset is used by templates")
    from django.utils import timezone

    a.deleted_at = timezone.now()
    a.save(update_fields=["deleted_at", "updated_at"])
    audit(
        "asset.delete", principal.actor, project_id=a.project_id, subject_type="asset", subject_id=a.id, request=request
    )
    return Status(204, None)


@router.get("assets/{asset_id}/file", summary="I35. Asset file (original or thumb)")
def asset_file(request: HttpRequest, asset_id: str, variant: str = "original") -> HttpResponse:
    a = _asset(request, asset_id)
    rel = (a.variants or {}).get(variant) if variant != "original" else a.path
    rel = rel or a.path
    path = store().path(rel)
    if not path.exists():
        raise ApiError(404, "NOT_FOUND", "File missing")
    mime = a.mime if rel == a.path else ("image/png" if rel.endswith(".png") else "image/jpeg")
    resp = FileResponse(open(path, "rb"), content_type=mime)  # noqa: SIM115 - FileResponse closes it
    resp["Cache-Control"] = IMMUTABLE
    resp["ETag"] = f'"{a.sha256}-{variant}"'
    if mime == "image/svg+xml":
        # opened directly in a tab an SVG is a document: no scripts, no requests out
        resp["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox"
    return resp


# --------------------------------------------------------------------------------------------- fonts


@router.get("fonts", summary="I36. Project + system fonts")
def list_fonts(request: HttpRequest) -> Any:
    from .fonts import fonts_for

    return {"data": [font_dict(f) for f in fonts_for(request.project)]}  # type: ignore[attr-defined]


@router.post("fonts", response={201: dict}, summary="I37. Upload TTF/OTF/WOFF/WOFF2 (OTF->TTF, metrics.json)")
def upload_fonts(request: HttpRequest, files: list[UploadedFile] = File(...)) -> Any:
    principal = require(request, "upload")
    out = []
    for f in files:
        data = f.read()
        if len(data) > settings.FONT_MAX_MB * 1024 * 1024:
            raise ApiError(413, "FILE_TOO_LARGE", f"Font exceeds {settings.FONT_MAX_MB} MB")
        font = upload_font(request.project, data, principal.snapshot())  # type: ignore[attr-defined]
        audit(
            "font.upload",
            principal.actor,
            project_id=font.project_id,
            subject_type="font",
            subject_id=font.id,
            changes={"family": font.family, "weight": font.weight},
            request=request,
        )
        out.append(font_dict(font))
    return Status(201, {"data": out})


@router.delete("fonts/{font_id}", response={204: None}, summary="I38. Delete a project font (admin)")
def delete_font(request: HttpRequest, font_id: str) -> Any:
    principal = require(request, "admin")
    f = _font(request, font_id)
    if f.project_id is None:
        raise ApiError(403, "FORBIDDEN", "System fonts cannot be deleted")
    if _in_use(f.project, ids.encode("fnt", f.id) or ""):
        raise ApiError(409, "FONT_IN_USE", "Font is used by templates")
    from django.utils import timezone

    f.deleted_at = timezone.now()
    f.save(update_fields=["deleted_at", "updated_at"])
    audit(
        "font.delete", principal.actor, project_id=f.project_id, subject_type="font", subject_id=f.id, request=request
    )
    return Status(204, None)


@router.get("fonts/{font_id}/file", summary="I39. Font file for the editor (WOFF2 or TTF)")
def font_file(request: HttpRequest, font_id: str, format: str = "woff2") -> HttpResponse:
    f = _font(request, font_id)
    rel = f.pdf_font_path if format == "ttf" else f.web_path
    resp = FileResponse(
        open(store().path(rel), "rb"),  # noqa: SIM115
        content_type="font/ttf" if format == "ttf" else "font/woff2",
    )
    resp["Cache-Control"] = IMMUTABLE
    resp["ETag"] = f'"{f.sha256}-{format}"'
    return resp


@router.get("fonts/{font_id}/metrics", summary="I40. metrics.json (spec/text-layout.md section 4)")
def font_metrics(request: HttpRequest, font_id: str) -> HttpResponse:
    f = _font(request, font_id)
    resp = HttpResponse(store().read(f.metrics_path), content_type="application/json")
    resp["Cache-Control"] = IMMUTABLE
    resp["ETag"] = f'"{f.sha256}-metrics"'
    return resp
