"""Font service (TZ 2.6.4): bundled system fonts, uploads, and the per-project FontLibrary."""

from __future__ import annotations

import hashlib
import json
import threading
from pathlib import Path
from typing import Any

from django.db import IntegrityError, transaction
from django.db.models import Q

from snapfile.core import ids
from snapfile.core.errors import ApiError
from snapfile.core.storage import store
from snapfile.projects.models import Project
from snapfile_render.errors import RenderError
from snapfile_render.fontprep import prepare_font
from snapfile_render.providers import FontFace, FontLibrary, bundled_font_files

from .models import Font

_LIB_CACHE: dict[str, FontLibrary] = {}
_LIB_LOCK = threading.Lock()


def _save_font(
    project: Project | None, data: bytes, actor: dict[str, Any] | None, license_note: str | None = None
) -> Font:
    sha = hashlib.sha256(data).hexdigest()
    existing = Font.objects.filter(project=project, sha256=sha, deleted_at__isnull=True).first()
    if existing:
        return existing
    try:
        prepared = prepare_font(data)
    except RenderError as exc:
        status = 422 if exc.code != "FONT_TOO_LARGE" else 413
        raise ApiError(status, exc.code, exc.message) from exc
    info = prepared.info
    base = f"system/fonts/{sha}" if project is None else f"projects/{project.id}/fonts/{sha}"
    ext = {"otf": "otf", "woff": "woff", "woff2": "woff2"}.get(info["format"], "ttf")
    st = store()
    st.write(f"{base}/original.{ext}", data)
    st.write(f"{base}/pdf.ttf", prepared.pdf_ttf)
    st.write(f"{base}/web.woff2", prepared.woff2)
    st.write(f"{base}/metrics.json", json.dumps(prepared.metrics, separators=(",", ":")).encode())
    try:
        with transaction.atomic():
            return Font.objects.create(
                project=project,
                family=info["family"][:128],
                weight=info["weight"],
                style=info["style"],
                postscript_name=(info["postscript_name"] or info["family"])[:128],
                format=info["format"],
                converted=info["converted"],
                sha256=sha,
                size_bytes=len(data),
                path=f"{base}/original.{ext}",
                web_path=f"{base}/web.woff2",
                metrics_path=f"{base}/metrics.json",
                pdf_font_path=f"{base}/pdf.ttf",
                units_per_em=info["units_per_em"],
                ascender=info["ascender"],
                descender=info["descender"],
                line_gap=info["line_gap"],
                cap_height=info["cap_height"],
                x_height=info["x_height"],
                glyph_count=info["glyph_count"],
                unicode_ranges=info["unicode_ranges"],
                embeddable=info["embeddable"],
                license_note=license_note,
                created_by=actor,
            )
    except IntegrityError as exc:
        raise ApiError(
            409, "FONT_EXISTS", f"{info['family']} {info['weight']} {info['style']} already exists in this project"
        ) from exc


def ensure_system_fonts() -> list[Font]:
    """Register bundled OFL fonts (Inter) as system fonts (project = NULL). Idempotent."""
    out = []
    for path in bundled_font_files():
        note = "SIL Open Font License 1.1 (bundled)"
        out.append(_save_font(None, Path(path).read_bytes(), {"id": "system", "name": "system"}, note))
    return out


def reprepare_fonts() -> int:
    """Rebuild pdf.ttf, web.woff2 and metrics.json of every font after the prepared glyph ranges change."""
    st = store()
    count = 0
    for font in Font.objects.filter(deleted_at__isnull=True):
        prepared = prepare_font(st.read(font.path))
        st.write(font.pdf_font_path, prepared.pdf_ttf)
        st.write(font.web_path, prepared.woff2)
        st.write(font.metrics_path, json.dumps(prepared.metrics, separators=(",", ":")).encode())
        font.glyph_count = prepared.info["glyph_count"]
        font.unicode_ranges = prepared.info["unicode_ranges"]
        font.save(update_fields=["glyph_count", "unicode_ranges"])
        count += 1
    return count


def upload_font(project: Project, data: bytes, actor: dict[str, Any] | None) -> Font:
    return _save_font(project, data, actor)


def fonts_for(project: Project | None) -> list[Font]:
    q = Q(project__isnull=True)
    if project is not None:
        q |= Q(project=project)
    return list(Font.objects.filter(q, deleted_at__isnull=True).order_by("family", "weight", "style"))


def font_library(project: Project | None) -> FontLibrary:
    rows = fonts_for(project)
    if not any(r.project_id is None for r in rows):
        ensure_system_fonts()
        rows = fonts_for(project)
    key = hashlib.sha1(
        "|".join(f"{r.id}:{r.sha256}:{r.family}:{r.weight}:{r.style}" for r in rows).encode()
    ).hexdigest()
    lib = _LIB_CACHE.get(key)
    if lib is not None:
        return lib
    st = store()
    faces = [
        FontFace(
            key=r.id.hex,
            family=r.family,
            weight=r.weight,
            style=r.style,
            metrics_path=str(st.path(r.metrics_path)),
            pdf_path=str(st.path(r.pdf_font_path)),
            ids=(ids.encode("fnt", r.id) or "", str(r.id), r.id.hex),
        )
        for r in rows
    ]
    lib = FontLibrary(faces, default_family="Inter")
    with _LIB_LOCK:
        if len(_LIB_CACHE) > 64:
            _LIB_CACHE.clear()
        _LIB_CACHE[key] = lib
    return lib


def font_dict(f: Font) -> dict[str, Any]:
    fid = ids.encode("fnt", f.id)
    return {
        "id": fid,
        "family": f.family,
        "weight": f.weight,
        "style": f.style,
        "postscript_name": f.postscript_name,
        "format": f.format,
        "converted": f.converted,
        "system": f.project_id is None,
        "glyph_count": f.glyph_count,
        "unicode_ranges": f.unicode_ranges,
        "units_per_em": f.units_per_em,
        "file_url": f"/internal/v1/fonts/{fid}/file",
        "metrics_url": f"/internal/v1/fonts/{fid}/metrics",
        "license_note": f.license_note,
        "created_at": f.created_at.isoformat(),
    }
