"""Template thumbnails: PNG of the first sheet of the draft, rendered lazily and cached by draft hash."""

from __future__ import annotations

import logging

from snapfile.core.storage import store
from snapfile.projects.variables import example_data
from snapfile_render.errors import RenderError

from .models import Template

log = logging.getLogger("snapfile.app")
THUMB_WIDTH_PX = 640  # 2x of the 320 px dashboard card (03_frontend 3.4.6 a)


def thumbnail_png(t: Template) -> bytes | None:
    """Return the cached thumbnail for the current draft, rendering it on a cache miss."""
    from snapfile.render.plans import draft_plan
    from snapfile.render.service import render_for_project

    from .service import effective_variables

    rel = f"thumbs/{t.project_id}/{t.id}/{t.draft_hash[:16]}.png"
    st = store()
    if st.exists(rel):
        return st.read(rel)
    try:
        plan, _ = draft_plan(t)
        sheets = plan.get("sheets") or []
        if not sheets:
            return None
        width_pt = float(sheets[0]["w"]) or 595.0
        dpi = max(24, min(150, round(THUMB_WIDTH_PX * 72 / width_pt)))
        data = t.sample_data if isinstance(t.sample_data, dict) else example_data(effective_variables(t))
        result = render_for_project(
            t.project, plan, data, {"format": "png", "dpi": dpi, "pages": "1"}, timeout_s=10, deterministic=True
        )
    except RenderError as exc:
        log.info("thumbnail render failed", extra={"template": str(t.id), "code": exc.code})
        return None
    if not result.images:
        return None
    png = result.images[0].data
    st.write(rel, png)
    old = t.thumbnail_path
    Template.objects.filter(pk=t.pk).update(thumbnail_path=rel)
    if old and old != rel:
        st.delete(old)
    return png
