"""
template_service.py — a product's print template: a PNG with transparent holes where the child's photo goes
(client 2026-11-15: "download the order photos with the montage already made — ID photo sheets, calendars — as
print-ready JPEGs at the right size, without making them by hand").

The idea and the rules come from the client's own tool (ateliermeeconic.com), which they used by hand until now:
  * the holes are found from the PNG's transparency, no zones to draw: each transparent blob is a slot (its bounding
    box), slots are read row by row, left to right;
  * the SAME photo fills every slot (an ID sheet = 6 × 35x45 mm + 1 × 10x15 of the same child) — the "one photo per
    zone" mode of the tool (key-ring sheet of 8 children) is not wanted for now (Dario 2026-11-15);
  * a slot is FILLED (cover, never a white band); the overflow is cut at the sides, and at the top and bottom with the
    frame raised a little (`TOP_BIAS`) so a head is never cut — faces are never detected (minors, project rule);
  * the template is drawn ON TOP of the photo, so a rounded or shaped frame masks the photo by itself;
  * the print size is the product's, in mm, at `DPI` (filled from the PNG's own dpi when it has one, editable): the
    client's ID sheet PNG is 2030x1510 at 254 dpi = 20.3x15.1 cm, their tool prints it at 2398x1795 (300 dpi).

Files: re-encoded PNG under PRODUCTS_DIR/{school}/templates/{sha}.png, named after their content and NEVER deleted:
an order line keeps a copy of the template it was paid with (file, size, slots), so replacing or removing a product's
template never changes the montage of an order already paid (same rule as prices and formats). They are a few MB
each and are uploaded a few times a year.
The family never sees a montage (Dario 2026-11-15: the gallery shows the product's example picture, they imagine
the rest); only the lab folder of a paid order (admin.py lab.zip) and the admin's test render make one.
"""
import hashlib
import io
import logging
from functools import lru_cache
from pathlib import Path
from typing import Optional

import numpy as np
from PIL import Image, ImageOps

from core import config
from core.security import sign, verify_signature

log = logging.getLogger("meeconic.templates")

DPI = 300                          # print resolution of a montage (the client's tool and every lab use 300)
TOP_BIAS = 0.35                    # share of the vertical overflow cut at the TOP (0.5 = centred): the frame is raised
MAX_UPLOAD_BYTES = 30 * 1024 * 1024
MAX_SIDE_PX = 12000                # 1 m at 300 dpi: anything bigger is a mistake, and memory is finite
MAX_SLOTS = 24
_ALPHA_HOLE = 128                  # a pixel at most half opaque belongs to a hole
_EDGE_PX = 3                       # slots grow by this much so the photo also runs under the anti-aliased edge
MM_MIN, MM_MAX = 20.0, 1000.0
PREVIEW_PX = 1000                  # the template shown in Settings (the real file can be 30 MB of pixels)

Image.MAX_IMAGE_PIXELS = max(Image.MAX_IMAGE_PIXELS or 0, MAX_SIDE_PX * MAX_SIDE_PX // 2)


class TemplateError(ValueError):
    pass


# ── Slots ────────────────────────────────────────────────────────────────────────

def detect_slots(img: Image.Image) -> list[list[float]]:
    """The transparent holes of `img` as [x, y, w, h] fractions of its size, row by row then left to right.
    Specks (a stray transparent pixel, a hole in a letter) are ignored: a slot covers at least 0.1 % of the sheet and
    1 % of each side."""
    import cv2
    w, h = img.size
    alpha = np.asarray(img.getchannel("A")) if "A" in img.getbands() else np.full((h, w), 255, np.uint8)
    holes = (alpha < _ALPHA_HOLE).astype(np.uint8)
    n, _labels, stats, _c = cv2.connectedComponentsWithStats(holes, connectivity=4)
    min_area, min_w, min_h = w * h * 0.001, w * 0.01, h * 0.01
    boxes = []
    for x, y, bw, bh, area in stats[1:]:
        if area < min_area or bw < min_w or bh < min_h:
            continue
        x0, y0 = max(0, x - _EDGE_PX), max(0, y - _EDGE_PX)
        x1, y1 = min(w, x + bw + _EDGE_PX), min(h, y + bh + _EDGE_PX)
        boxes.append((x0, y0, x1 - x0, y1 - y0))
    # Rows: boxes whose centres are within 4 % of the height of the first one of a row share it (like the tool).
    rows: list[list[tuple]] = []
    for b in sorted(boxes, key=lambda b: b[1] + b[3] / 2):
        cy = b[1] + b[3] / 2
        row = next((r for r in rows if abs(r[0][1] + r[0][3] / 2 - cy) < h * 0.04), None)
        (row.append(b) if row is not None else rows.append([b]))
    ordered = [b for r in rows for b in sorted(r, key=lambda b: b[0])]
    return [[round(x / w, 6), round(y / h, 6), round(bw / w, 6), round(bh / h, 6)] for x, y, bw, bh in ordered]


# ── Files ────────────────────────────────────────────────────────────────────────

def _dir(school_id: str) -> Path:
    return config.PRODUCTS_DIR / school_id / "templates"


def file_path(school_id: str, name: str) -> Optional[Path]:
    """The stored PNG for a template `file` name, or None for a name that is not one of ours."""
    if not (name.endswith(".png") and len(name) == 28 and all(c in "0123456789abcdef" for c in name[:24])):
        return None
    return _dir(school_id) / name


def save(school_id: str, raw: bytes) -> dict:
    """Check and store an uploaded template. Returns the template dict to keep on the product:
    {file, px: [w, h], width_mm, height_mm, slots}. TemplateError says why a file is refused."""
    if not raw or len(raw) > MAX_UPLOAD_BYTES:
        raise TemplateError(f"The template must be a PNG of at most {MAX_UPLOAD_BYTES // 1048576} MB.")
    try:
        with Image.open(io.BytesIO(raw)) as im:
            if im.format != "PNG":
                raise TemplateError("The template must be a PNG file (with transparent zones for the photo).")
            if max(im.size) > MAX_SIDE_PX:
                raise TemplateError(f"The template is too large (at most {MAX_SIDE_PX} pixels per side).")
            dpi = im.info.get("dpi")
            img = im.convert("RGBA")
    except TemplateError:
        raise
    except Exception:
        raise TemplateError("Not a readable PNG file.")
    slots = detect_slots(img)
    if not slots:
        raise TemplateError("No transparent zone found in this PNG: the photo has nowhere to go.")
    if len(slots) > MAX_SLOTS:
        raise TemplateError(f"Too many transparent zones ({len(slots)}, at most {MAX_SLOTS}).")
    # Re-encoded: only a PNG we wrote is ever stored or served (no text chunks, no other format smuggled through).
    buf = io.BytesIO()
    img.save(buf, "PNG", optimize=False, compress_level=6)
    data = buf.getvalue()
    name = hashlib.sha256(data).hexdigest()[:24] + ".png"
    path = _dir(school_id) / name
    if not path.is_file():
        path.parent.mkdir(parents=True, exist_ok=True)
        tmp = path.with_suffix(".tmp")
        tmp.write_bytes(data)
        tmp.replace(path)
    # Its size: from its own dpi when it says one (the client's files do), else as if it was made at 300 dpi.
    try:
        d = float(dpi[0]) if dpi else 0.0
    except (TypeError, ValueError, IndexError):
        d = 0.0
    d = d if 72 <= d <= 1200 else DPI
    w, h = img.size
    return {"file": name, "px": [w, h], "width_mm": round(w / d * 25.4, 1), "height_mm": round(h / d * 25.4, 1),
            "slots": slots}


def with_size(tpl: dict, width_mm, height_mm) -> dict:
    """The template printed at another size (the admin's cm fields)."""
    try:
        w, h = round(float(width_mm), 1), round(float(height_mm), 1)
    except (TypeError, ValueError):
        raise TemplateError("Invalid size.")
    if not (MM_MIN <= w <= MM_MAX and MM_MIN <= h <= MM_MAX):
        raise TemplateError(f"The size must be between {MM_MIN / 10:g} and {MM_MAX / 10:g} cm.")
    return {**tpl, "width_mm": w, "height_mm": h}


def out_px(tpl: dict) -> tuple[int, int]:
    return (max(1, round(tpl["width_mm"] / 25.4 * DPI)), max(1, round(tpl["height_mm"] / 25.4 * DPI)))


def ratio_off(tpl: dict) -> bool:
    """The print size does not have the PNG's proportions (> 1.5 %): the design would be stretched."""
    pw, ph = tpl["px"]
    a, b = pw / ph, tpl["width_mm"] / tpl["height_mm"]
    return abs(a - b) / b > 0.015


def admin_view(school_id: str, tpl: Optional[dict]) -> Optional[dict]:
    """What Settings shows of a product's template (the families never get it, see format_service.portal_view)."""
    if not tpl:
        return None
    exp, sig = sign(f"template:{school_id}/{tpl['file']}", 3600)
    w, h = out_px(tpl)
    return {"width_mm": tpl["width_mm"], "height_mm": tpl["height_mm"], "slots": tpl["slots"], "out_px": [w, h],
            "ratio_off": ratio_off(tpl),
            "preview_url": f"/api/media/template/{school_id}/{tpl['file']}?exp={exp}&sig={sig}"}


def check_signature(school_id: str, name: str, exp: int, sig: str) -> bool:
    return verify_signature(f"template:{school_id}/{name}", exp, sig)


def preview_png(school_id: str, name: str) -> Optional[bytes]:
    path = file_path(school_id, name)
    if path is None or not path.is_file():
        return None
    with Image.open(path) as im:
        im.thumbnail((PREVIEW_PX, PREVIEW_PX))
        buf = io.BytesIO()
        im.save(buf, "PNG")
    return buf.getvalue()


# ── The montage ──────────────────────────────────────────────────────────────────

@lru_cache(maxsize=3)
def _sheet(path: str, mtime: float, w: int, h: int) -> Image.Image:
    """The template at the print size (the same few templates come back for every line of a lab folder)."""
    with Image.open(path) as im:
        img = im.convert("RGBA")
    return img if img.size == (w, h) else img.resize((w, h), Image.LANCZOS)


def _to_srgb(photo: Image.Image) -> Image.Image:
    """RGB in sRGB: a CMYK file or one with another colour profile would print with shifted colours otherwise."""
    icc = photo.info.get("icc_profile")
    if icc:
        try:
            from PIL import ImageCms
            src = ImageCms.ImageCmsProfile(io.BytesIO(icc))
            mode = "RGB" if photo.mode != "CMYK" else "CMYK"
            return ImageCms.profileToProfile(photo.convert(mode), src, ImageCms.createProfile("sRGB"), outputMode="RGB")
        except Exception:                                  # a broken profile: the pixels as they are
            pass
    return photo.convert("RGB")


def place(photo: Image.Image, box: tuple[int, int, int, int]) -> Image.Image:
    """The photo scaled to FILL a slot of box (w, h) and cut to it: centred across, raised a little (TOP_BIAS)."""
    _x, _y, sw, sh = box
    pw, ph = photo.size
    scale = max(sw / pw, sh / ph)
    nw, nh = max(sw, round(pw * scale)), max(sh, round(ph * scale))
    left = (nw - sw) // 2
    top = round((nh - sh) * TOP_BIAS)
    return photo.resize((nw, nh), Image.LANCZOS, box=None).crop((left, top, left + sw, top + sh))


def render(school_id: str, tpl: dict, photo_bytes: bytes) -> bytes:
    """The finished montage as a print-ready JPEG: white paper, the photo in every slot, the template on top,
    at the print size in pixels with its dpi written in the file."""
    path = file_path(school_id, tpl.get("file", ""))
    if path is None or not path.is_file():
        raise TemplateError("The template file of this product is missing.")
    w, h = out_px(tpl)
    with Image.open(io.BytesIO(photo_bytes)) as src:
        # A big JPEG decodes faster at a reduced scale; square request: its EXIF rotation is applied after.
        src.draft("RGB", (max(w, h), max(w, h)))
        photo = _to_srgb(ImageOps.exif_transpose(src))
    canvas = Image.new("RGBA", (w, h), (255, 255, 255, 255))
    done: dict[tuple[int, int], Image.Image] = {}
    for fx, fy, fw, fh in tpl["slots"]:
        x, y = round(fx * w), round(fy * h)
        sw, sh = max(1, round(fw * w)), max(1, round(fh * h))
        if (sw, sh) not in done:                           # six identical ID slots: one resize
            done[(sw, sh)] = place(photo, (x, y, sw, sh)).convert("RGBA")
        canvas.paste(done[(sw, sh)], (x, y))
    canvas.alpha_composite(_sheet(str(path), path.stat().st_mtime, w, h))
    buf = io.BytesIO()
    canvas.convert("RGB").save(buf, "JPEG", quality=95, subsampling=0, dpi=(DPI, DPI), optimize=True)
    return buf.getvalue()
