"""
format_service.py — the formats a family can order for a photo, editable per school (client request: "edit the
formats and prices, add new photo formats and sizes, set their prices" from Settings).

Before this, the seven formats were fixed in code (school_service.FORMAT_PRICE_KEY) and only their prices were
settings. Now every school has a catalogue table:
  * the seven historical formats are rows too (`builtin`): their names, description, order, "popular" badge,
    on/off and what they deliver (kind) can be edited; their PRICE stays where it always was (school_settings `price_*`), so nothing that reads
    prices (and the existing price validation) has two sources of truth. Since 2026-10 they can be deleted like any
    product (client: "every format must be editable"): order lines carry their own name, kind and price, so nothing
    reads the row back. A deleted built-in keeps its row with `deleted_at` set, or `_ensure_builtins` would bring it
    back on the next read.
  * new formats (`fmt-{id}`): a size or support the client invents ("Tirage 13×18", "Poster 30×45", "Numérique
    + 3 tirages"…), with a kind that says what it delivers: `print` (physical, handed out in class), `digital`
    (gives the HD download after payment) or `pack` (both). An object (key ring, magnet…) is a `print`: it is
    handed out in class.
ONE list of products (client brief 2026-10-21, sheet 3): the same product at the same price for a classic photo or an
AI photo, so the three "magic-*" built-in rows are hidden (never deleted: old orders and their downloads refer to
them). Each product has an optional image (`has_image`, WebP under PRODUCTS_DIR). The old `school_products` table
(key rings, mugs…) was merged into this one by `migrate_legacy_products`; its rows stay, unused, as a backup.

The server still owns prices: an order line is checked against this catalogue (format_line), and the line stored
on the order carries what it delivers (`kind`, `digital`) so downloads and print counts never depend on a format
that was edited or removed afterwards.

What a product delivers (`kind`): `print` (handed out in class), `digital` (the HD download), `pack` (both, ONE
price, both delivered) or `choice` (client 2026-10-28: "printed with its price, digital with its price, both with
its price"): three prices, `price` (print), `price_digital` (file) and `price_both` (print + file). A `choice` product
is never ordered as such: `expand` turns it into its three variants, `{id}` (print), `{id}:num` (file) and `{id}:both`
(print + file), for the portal and for the order check, so every order line still says what it delivers.

A product may list what it CONTAINS (`components`, client 2026-10-28: "for a pack, its name and the products in it,
so the lab knows what to print"): [{format_id, qty}] of other products of the school, one level only (a component
has no components). The lab zip and the recap sheet expand the pack into them; the order line keeps a copy, so
editing the pack later never changes a paid order. A component deleted since is left out.

A product may have a print TEMPLATE (`template`, client 2026-11-15): a PNG with transparent holes, so the lab folder
gives the finished montage (calendar, ID photo sheet) instead of the bare photo. See template_service; the order line
keeps a copy of it, like its components.
"""
import json
import logging
from typing import Optional

from core import config
from core.security import sign, verify_signature
from core.db import TABLE_OPTIONS, ensure_column, get_db, table_exists
from core.timeutil import utcnow_iso
from services import school_service, template_service, translate_service

logger = logging.getLogger("meeconic.formats")

KINDS = ("print", "digital", "pack", "choice")
DIGITAL_SUFFIX, BOTH_SUFFIX = ":num", ":both"       # the file / print + file variants of a `choice` product
_DIGITAL_LABEL = {"fr": "version numérique", "en": "digital version", "es": "versión digital"}
_BOTH_LABEL = {"fr": "tirage + numérique", "en": "print + digital", "es": "copia + digital"}
# Longest product description (client 2026-10-28: 160 was too short for "what is in the pack"). Tables made before
# that are widened by init_format_table.
SUB_MAX = 500
MAX_COMPONENTS, MAX_COMPONENT_QTY = 10, 50

# The historical formats: id → (kind, magic, price setting, names, descriptions, popular). Names are the ones
# the portal showed (translations.ts fmt_*), so nothing changes for families until the operator edits them.
BUILTINS = [
    ("print-10x15", "print", False, "price_print_10x15",
     ("Tirage papier 10×15", "10×15 Print", "Copia papel 10×15"),
     ("Format standard, remis en classe", "Standard format, delivered at school", "Formato estándar, entregado en clase"), True),
    ("print-20x30", "print", False, "price_print_20x30",
     ("Tirage papier 20×30", "20×30 Print", "Copia papel 20×30"),
     ("Grand format encadrable", "Large frameable format", "Formato grande enmarcable"), False),
    ("digital", "digital", False, "price_digital",
     ("Numérique HD", "Digital HD", "Digital HD"),
     ("Téléchargement haute définition", "High-definition download", "Descarga en alta definición"), False),
    ("pack", "pack", False, "price_pack",
     ("Pack complet", "Complete pack", "Pack completo"),
     ("Tirage 10×15 + numérique HD", "10×15 print + digital HD", "Copia 10×15 + digital HD"), False),
    ("magic-print", "print", True, "price_magic_print",
     ("Impression magique 10×15", "Magic 10×15 print", "Impresión mágica 10×15"),
     ("Tirage papier, remis en classe", "Paper print, delivered at school", "Copia papel, entregada en clase"), False),
    ("magic-digital", "digital", True, "price_magic_digital",
     ("Numérique magique HD", "Magic digital HD", "Digital mágico HD"),
     ("Téléchargement haute définition", "High-definition download", "Descarga en alta definición"), False),
    ("magic-pack", "pack", True, "price_magic_pack",
     ("Pack magique", "Magic pack", "Pack mágico"),
     ("Impression + numérique HD", "Print + digital HD", "Impresión + digital HD"), True),
]
_BUILTIN_PRICE_KEY = {b[0]: b[3] for b in BUILTINS}


class FormatError(ValueError):
    pass


def init_format_table() -> None:
    with get_db() as conn:
        conn.execute(f"""
        CREATE TABLE IF NOT EXISTS school_formats (
            id         INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
            school_id  VARCHAR(64)  NOT NULL,
            format_id  VARCHAR(40)  NOT NULL,
            builtin    TINYINT NOT NULL DEFAULT 0,
            kind       VARCHAR(10)  NOT NULL,
            magic      TINYINT NOT NULL DEFAULT 0,
            name_fr    VARCHAR(80)  NOT NULL,
            name_en    VARCHAR(80)  NOT NULL DEFAULT '',
            name_es    VARCHAR(80)  NOT NULL DEFAULT '',
            sub_fr     VARCHAR(500) NOT NULL DEFAULT '',
            sub_en     VARCHAR(500) NOT NULL DEFAULT '',
            sub_es     VARCHAR(500) NOT NULL DEFAULT '',
            price      DOUBLE,
            popular    TINYINT NOT NULL DEFAULT 0,
            active     TINYINT NOT NULL DEFAULT 1,
            sort_order INT NOT NULL DEFAULT 0,
            created_at VARCHAR(40),
            UNIQUE KEY uq_school_format (school_id, format_id)
        ) {TABLE_OPTIONS}""")
        # Example picture of the product (a counter: it is also the cache-buster of the image URL).
        ensure_column(conn, "school_formats", "has_image", "INT NOT NULL DEFAULT 0")
        ensure_column(conn, "school_formats", "deleted_at", "VARCHAR(40)")
        ensure_column(conn, "school_formats", "components", "TEXT")        # JSON [{format_id, qty}], see the docstring
        ensure_column(conn, "school_formats", "price_digital", "DOUBLE")    # a `choice` product's file price
        ensure_column(conn, "school_formats", "price_both", "DOUBLE")       # ... and its print + file price
        ensure_column(conn, "school_formats", "template", "TEXT")           # JSON, template_service.save(); NULL = none
        for col in ("sub_fr", "sub_en", "sub_es"):
            r = conn.execute("SELECT CHARACTER_MAXIMUM_LENGTH AS n FROM information_schema.COLUMNS WHERE "
                             "TABLE_SCHEMA=DATABASE() AND TABLE_NAME='school_formats' AND COLUMN_NAME=?", (col,)).fetchone()
            if r and (r["n"] or 0) < SUB_MAX:
                conn.execute(f"ALTER TABLE school_formats MODIFY {col} VARCHAR({SUB_MAX}) NOT NULL DEFAULT ''")
        conn.commit()


def _ensure_builtins(conn, school_id: str) -> None:
    """The historical formats exist as rows for every school (created the first time the catalogue is read)."""
    have = {r["format_id"] for r in conn.execute("SELECT format_id FROM school_formats WHERE school_id=? AND builtin=1",
                                                 (school_id,))}
    missing = [b[0] for b in BUILTINS if b[0] not in have]
    for i, (fid, kind, magic, _pk, names, subs, popular) in enumerate(BUILTINS):
        if fid not in missing:
            continue
        conn.execute(
            "INSERT IGNORE INTO school_formats (school_id, format_id, builtin, kind, magic, name_fr, name_en, name_es, "
            "sub_fr, sub_en, sub_es, price, popular, active, sort_order, created_at) "
            "VALUES (?,?,1,?,?,?,?,?,?,?,?,NULL,?,1,?,?)",
            (school_id, fid, kind, int(magic), *names, *subs, int(popular), (i + 1) * 10, utcnow_iso()))
    if missing:
        conn.commit()


def _row_to_dict(r, settings: dict) -> dict:
    price = float(settings[_BUILTIN_PRICE_KEY[r["format_id"]]]) if r["builtin"] else float(r["price"] or 0)
    return {
        "id": r["id"], "format_id": r["format_id"], "builtin": bool(r["builtin"]), "kind": r["kind"],
        "magic": bool(r["magic"]), "price": price, "popular": bool(r["popular"]), "active": bool(r["active"]),
        "sort_order": r["sort_order"],
        "name_fr": r["name_fr"], "name_en": r["name_en"] or r["name_fr"], "name_es": r["name_es"] or r["name_fr"],
        "sub_fr": r["sub_fr"], "sub_en": r["sub_en"] or r["sub_fr"], "sub_es": r["sub_es"] or r["sub_fr"],
        "physical": r["kind"] in ("print", "pack", "choice"), "digital": r["kind"] in ("digital", "pack", "choice"),
        "price_digital": float(r["price_digital"] or 0), "price_both": float(r["price_both"] or 0),
        "image_url": f"/api/portal/format-image/{r['school_id']}/{r['id']}.webp?v={r['has_image']}"
                     if r["has_image"] else None,
        # Settings shows the picture of EVERY product: the public URL above answers 404 while a product is not
        # offered, which left a broken image in the Product tab (2026-11-22). Signed; never in `portal_view`.
        "image_admin_url": _admin_image_url(r["school_id"], r["id"], r["has_image"]) if r["has_image"] else None,
        "components": _parse_components(r["components"]),
        # The montage template (template_service): kept whole here (order lines copy it); Settings gets `template_view`.
        "template": _parse_template(r["template"]),
        "template_view": template_service.admin_view(r["school_id"], _parse_template(r["template"])),
    }


def _parse_template(raw) -> Optional[dict]:
    try:
        t = json.loads(raw) if raw else None
        return t if isinstance(t, dict) and t.get("file") and t.get("slots") else None
    except ValueError:
        return None


def _parse_components(raw) -> list[dict]:
    try:
        return [{"format_id": str(c["format_id"]), "qty": int(c["qty"])} for c in json.loads(raw or "[]")]
    except (ValueError, TypeError, KeyError):
        return []


def _resolve(formats: list[dict]) -> None:
    """Each component gets the names and what it delivers of the product it points at (in place)."""
    by_id = {f["format_id"]: f for f in formats}
    for f in formats:
        f["components"] = [{**c, **{k: by_id[c["format_id"]][k] for k in ("name_fr", "name_en", "name_es", "physical", "digital", "template")}}
                           for c in f["components"] if c["format_id"] in by_id]


def expand(formats: list[dict]) -> list[dict]:
    """The orderable list: a `choice` product becomes its print variant (same id), its file (`{id}:num`) and its
    print + file (`{id}:both`), each at its own price, the names saying which. `group` / `variant` let the portal show
    them as one product with three options."""
    out = []
    for f in formats:
        if f["kind"] != "choice":
            out.append(f)
            continue
        out.append({**f, "kind": "print", "physical": True, "digital": False, "group": f["format_id"], "variant": "print"})
        for suffix, kind, physical, price, variant, label in (
                (DIGITAL_SUFFIX, "digital", False, f["price_digital"], "digital", _DIGITAL_LABEL),
                (BOTH_SUFFIX, "pack", True, f["price_both"], "both", _BOTH_LABEL)):
            out.append({**f, "format_id": f["format_id"] + suffix, "kind": kind, "physical": physical, "digital": True,
                        "price": price, "components": [], **({} if physical else {"template": None, "template_view": None}), "group": f["format_id"], "variant": variant,
                        **{f"name_{lg}": f"{f[f'name_{lg}']} · {label[lg]}" for lg in ("fr", "en", "es")}})
    return out


def list_formats(school_id: str, active_only: bool = False) -> list[dict]:
    """The school's products in order. The hidden `magic-*` rows (one list for classic and AI photos) are not
    listed: nobody can offer or order them any more."""
    with get_db() as conn:
        _ensure_builtins(conn, school_id)
        settings = school_service.get_settings(school_id, conn)
        rows = conn.execute("SELECT * FROM school_formats WHERE school_id=? AND magic=0 AND deleted_at IS NULL "
                            "ORDER BY sort_order, id", (school_id,)).fetchall()
    out = [_row_to_dict(r, settings) for r in rows]
    _resolve(out)                                    # before the filter: a pack may contain a product not offered alone
    return [f for f in out if f["active"]] if active_only else out


def get_format(school_id: str, format_id: str) -> Optional[dict]:
    return next((f for f in list_formats(school_id) if f["format_id"] == format_id), None)


def _clean(body: dict, creating: bool) -> dict:
    out: dict = {}
    for lang in ("fr", "en", "es"):
        for field, mx in (("name", 80), ("sub", SUB_MAX)):
            k = f"{field}_{lang}"
            if k in body and body[k] is not None:
                out[k] = " ".join(str(body[k]).split())[:mx]
    if creating and not out.get("name_fr"):
        raise FormatError("The French name is required.")
    if "name_fr" in out and not out["name_fr"]:
        raise FormatError("The French name cannot be empty.")
    if "kind" in body and body["kind"] is not None:
        if body["kind"] not in KINDS:
            raise FormatError("kind must be print, digital or pack.")
        out["kind"] = body["kind"]
    elif creating:
        raise FormatError("kind is required (print, digital or pack).")
    for key in ("price", "price_digital", "price_both"):
        if key in body and body[key] is not None:
            try:
                price = round(float(body[key]), 2)
            except (TypeError, ValueError):
                raise FormatError("Invalid price.")
            if not 0 <= price <= 10000:
                raise FormatError("The price must be between 0 and 10000 €.")
            out[key] = price
    if creating and "price" not in out:
        raise FormatError("price is required.")
    if creating and out.get("kind") == "choice" and ("price_digital" not in out or "price_both" not in out):
        raise FormatError("A product sold as print, file or both needs the three prices.")
    for flag in ("popular", "active"):
        if flag in body and body[flag] is not None:
            out[flag] = int(bool(body[flag]))
    if "sort_order" in body and body["sort_order"] is not None:
        out["sort_order"] = max(0, min(100000, int(body["sort_order"])))
    if "components" in body and body["components"] is not None:
        out["components"] = body["components"]           # checked against the catalogue by _check_components
    return out


def _check_components(conn, school_id: str, own_format_id: Optional[str], comps) -> str:
    """The JSON to store, or FormatError. Same product twice = quantities added."""
    if not isinstance(comps, list) or len(comps) > MAX_COMPONENTS:
        raise FormatError(f"A pack lists at most {MAX_COMPONENTS} products.")
    rows = {r["format_id"]: r for r in conn.execute(
        "SELECT format_id, components FROM school_formats WHERE school_id=? AND deleted_at IS NULL AND magic=0", (school_id,))}
    merged: dict[str, int] = {}
    for c in comps:
        try:
            fid, qty = str(c["format_id"]), int(c["qty"])
        except (TypeError, KeyError, ValueError):
            raise FormatError("Each product of the pack needs a product and a quantity.")
        if fid not in rows or fid == own_format_id:
            raise FormatError("A pack can only contain other products of this school.")
        if _parse_components(rows[fid]["components"]):
            raise FormatError("A pack cannot contain another pack.")
        if not 1 <= qty <= MAX_COMPONENT_QTY:
            raise FormatError(f"The quantity must be between 1 and {MAX_COMPONENT_QTY}.")
        merged[fid] = merged.get(fid, 0) + qty
    if own_format_id and merged and conn.execute(
            "SELECT 1 FROM school_formats WHERE school_id=? AND deleted_at IS NULL AND components LIKE ?",
            (school_id, f'%"{own_format_id}"%')).fetchone():
        raise FormatError("This product is in a pack: it cannot be a pack itself.")
    return json.dumps([{"format_id": k, "qty": v} for k, v in merged.items()])


def create_format(school_id: str, body: dict) -> dict:
    """A product typed in French. Whatever EN / ES text was not given is translated now; if no translation service
    answers the product is saved anyway (shown in French) and `translation_unavailable` says so."""
    data = _clean(body, creating=True)
    unavailable = False
    gaps = [(f"{field}_{lang}", data.get(f"{field}_fr", ""), lang)
            for field in ("name", "sub") for lang in translate_service.TARGETS
            if data.get(f"{field}_fr") and not data.get(f"{field}_{lang}")]
    if gaps:
        done = translate_service.translate([g[1] for g in gaps])
        if done is None:
            unavailable = True
        else:
            for i, (key, _src, lang) in enumerate(gaps):
                data[key] = done[lang][i][:80 if key.startswith("name") else SUB_MAX]
    with get_db() as conn:
        _ensure_builtins(conn, school_id)
        top = conn.execute("SELECT MAX(sort_order) AS m FROM school_formats WHERE school_id=?", (school_id,)).fetchone()["m"] or 0
        cur = conn.execute(
            "INSERT INTO school_formats (school_id, format_id, builtin, kind, magic, name_fr, name_en, name_es, sub_fr, "
            "sub_en, sub_es, price, popular, active, sort_order, created_at, price_digital, price_both) "
            "VALUES (?,?,0,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
            (school_id, f"tmp-{utcnow_iso()}", data["kind"], 0, data["name_fr"],
             data.get("name_en", ""), data.get("name_es", ""), data.get("sub_fr", ""), data.get("sub_en", ""),
             data.get("sub_es", ""), data["price"], data.get("popular", 0), data.get("active", 1),
             data.get("sort_order", top + 10), utcnow_iso(), data.get("price_digital"), data.get("price_both")))
        fid = f"fmt-{cur.lastrowid}"
        conn.execute("UPDATE school_formats SET format_id=? WHERE id=?", (fid, cur.lastrowid))
        if data.get("components"):
            conn.execute("UPDATE school_formats SET components=? WHERE id=?",
                         (_check_components(conn, school_id, fid, data["components"]), cur.lastrowid))
        conn.commit()
    fmt = get_format(school_id, fid)
    if unavailable:
        fmt["translation_unavailable"] = True
    return fmt


def update_format(school_id: str, row_id: int, body: dict) -> dict:
    data = _clean(body, creating=False)
    with get_db() as conn:
        row = conn.execute("SELECT * FROM school_formats WHERE id=? AND school_id=? AND deleted_at IS NULL",
                           (row_id, school_id)).fetchone()
        if not row:
            raise LookupError("Format not found.")
        if row["builtin"]:
            # What it delivers (`kind`) is editable like on any product since 2026-10-28: an order line stores its own
            # `digital`/`physical`, so the change only reaches new orders. The price goes to the school setting it
            # always lived in.
            price = data.pop("price", None)
            if price is not None:
                school_service.update_settings(school_id, {_BUILTIN_PRICE_KEY[row["format_id"]]: price})
        if "components" in data:
            data["components"] = _check_components(conn, school_id, row["format_id"], data["components"])
        if data:
            sets = ", ".join(f"{k}=?" for k in data)
            conn.execute(f"UPDATE school_formats SET {sets} WHERE id=?", (*data.values(), row_id))
            conn.commit()
        fid = row["format_id"]
    return get_format(school_id, fid)


def delete_format(school_id: str, row_id: int) -> None:
    """Any product can be deleted. Paid orders keep the name, kind and price on their own lines, so the history
    and the recap stay complete. A built-in one is only marked deleted (see the module docstring)."""
    with get_db() as conn:
        row = conn.execute("SELECT * FROM school_formats WHERE id=? AND school_id=? AND deleted_at IS NULL",
                           (row_id, school_id)).fetchone()
        if not row:
            raise LookupError("Product not found.")
        if row["builtin"]:
            conn.execute("UPDATE school_formats SET deleted_at=?, active=0, has_image=0 WHERE id=?", (utcnow_iso(), row_id))
        else:
            conn.execute("DELETE FROM school_formats WHERE id=?", (row_id,))
        conn.commit()
    try:
        image_path(school_id, row_id).unlink(missing_ok=True)
    except OSError:
        pass


def reorder(school_id: str, row_ids: list[int]) -> None:
    """Display order = the order of `row_ids` (the ↑ ↓ buttons). Products not listed keep their place after them."""
    with get_db() as conn:
        _ensure_builtins(conn, school_id)
        mine = {r["id"] for r in conn.execute("SELECT id FROM school_formats WHERE school_id=? AND deleted_at IS NULL",
                                              (school_id,))}
        if not row_ids or any(i not in mine for i in row_ids) or len(set(row_ids)) != len(row_ids):
            raise FormatError("Unknown product in the list.")
        for pos, rid in enumerate(row_ids):
            conn.execute("UPDATE school_formats SET sort_order=? WHERE id=?", ((pos + 1) * 10, rid))
        conn.commit()


# ── Product image ────────────────────────────────────────────────────────────────

def image_path(school_id: str, row_id: int):
    return config.PRODUCTS_DIR / school_id / f"f{int(row_id)}.webp"


def save_image(school_id: str, row_id: int, webp: bytes) -> dict:
    with get_db() as conn:
        if not conn.execute("SELECT 1 FROM school_formats WHERE id=? AND school_id=? AND deleted_at IS NULL",
                            (row_id, school_id)).fetchone():
            raise LookupError("Product not found.")
    path = image_path(school_id, row_id)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(webp)
    with get_db() as conn:
        conn.execute("UPDATE school_formats SET has_image=has_image+1 WHERE id=?", (row_id,))
        conn.commit()
        row = conn.execute("SELECT format_id FROM school_formats WHERE id=?", (row_id,)).fetchone()
    return get_format(school_id, row["format_id"])


def _admin_image_url(school_id: str, row_id: int, version: int) -> str:
    exp, sig = sign(f"format-image:{school_id}/{int(row_id)}", 3600)
    return f"/api/media/format-image/{school_id}/{int(row_id)}.webp?v={version}&exp={exp}&sig={sig}"


def admin_image(school_id: str, row_id: int, exp: int, sig: str):
    """The picture of a product, offered or not, for a signed Settings link; None if the link or the file is bad."""
    if not verify_signature(f"format-image:{school_id}/{int(row_id)}", exp, sig):
        return None
    with get_db() as conn:
        row = conn.execute("SELECT 1 FROM school_formats WHERE id=? AND school_id=? AND deleted_at IS NULL AND has_image>0",
                           (row_id, school_id)).fetchone()
    path = image_path(school_id, row_id)
    return path if row and path.is_file() else None


def public_image(school_id: str, row_id: int):
    """The file of an OFFERED product's picture (a hidden product's picture is not public), or None."""
    with get_db() as conn:
        row = conn.execute("SELECT 1 FROM school_formats WHERE id=? AND school_id=? AND active=1 AND has_image>0",
                           (row_id, school_id)).fetchone()
    path = image_path(school_id, row_id)
    return path if row and path.is_file() else None


# ── Montage template ─────────────────────────────────────────────────────────────

def _set_template(school_id: str, row_id: int, tpl: Optional[dict]) -> dict:
    with get_db() as conn:
        row = conn.execute("SELECT format_id FROM school_formats WHERE id=? AND school_id=? AND deleted_at IS NULL",
                           (row_id, school_id)).fetchone()
        if not row:
            raise LookupError("Product not found.")
        conn.execute("UPDATE school_formats SET template=? WHERE id=?", (json.dumps(tpl) if tpl else None, row_id))
        conn.commit()
    return get_format(school_id, row["format_id"])


def save_template(school_id: str, row_id: int, raw: bytes) -> dict:
    """A new PNG for the product (template_service.TemplateError if refused). Orders already paid keep theirs."""
    with get_db() as conn:
        if not conn.execute("SELECT 1 FROM school_formats WHERE id=? AND school_id=? AND deleted_at IS NULL",
                            (row_id, school_id)).fetchone():
            raise LookupError("Product not found.")
    return _set_template(school_id, row_id, template_service.save(school_id, raw))


def resize_template(school_id: str, row_id: int, width_mm, height_mm) -> dict:
    with get_db() as conn:
        row = conn.execute("SELECT template FROM school_formats WHERE id=? AND school_id=? AND deleted_at IS NULL",
                           (row_id, school_id)).fetchone()
    if not row:
        raise LookupError("Product not found.")
    tpl = _parse_template(row["template"])
    if not tpl:
        raise template_service.TemplateError("This product has no template.")
    return _set_template(school_id, row_id, template_service.with_size(tpl, width_mm, height_mm))


def clear_template(school_id: str, row_id: int) -> dict:
    """Back to "no template": the bare photo goes to the lab. The file stays (paid orders may point at it)."""
    return _set_template(school_id, row_id, None)


def template_of(school_id: str, row_id: int) -> Optional[dict]:
    with get_db() as conn:
        row = conn.execute("SELECT template FROM school_formats WHERE id=? AND school_id=? AND deleted_at IS NULL",
                           (row_id, school_id)).fetchone()
    if not row:
        raise LookupError("Product not found.")
    return _parse_template(row["template"])


# ── The old catalogue of extra products, merged into this one ────────────────────

def migrate_legacy_products() -> int:
    """Products made before the single list (`school_products`: key rings, mugs…) become rows here, picture
    included. Once: the old row remembers where it went. Their old orders keep their own lines."""
    import shutil
    moved = 0
    with get_db() as conn:
        if not table_exists(conn, "school_products"):
            return 0
        ensure_column(conn, "school_products", "migrated_to", "INT")
        rows = conn.execute("SELECT * FROM school_products WHERE migrated_to IS NULL").fetchall()
        for r in rows:
            cur = conn.execute(
                "INSERT INTO school_formats (school_id, format_id, builtin, kind, magic, name_fr, name_en, name_es, "
                "price, popular, active, sort_order, created_at, has_image) VALUES (?,?,0,'print',0,?,?,?,?,0,?,?,?,0)",
                (r["school_id"], f"tmp-{r['id']}-{utcnow_iso()}", r["name_fr"], r["name_en"], r["name_es"], r["price"],
                 r["active"], 1000 + (r["sort_order"] or 0), r["created_at"]))
            new_id = cur.lastrowid
            conn.execute("UPDATE school_formats SET format_id=? WHERE id=?", (f"fmt-{new_id}", new_id))
            old_img = config.PRODUCTS_DIR / r["school_id"] / f"{int(r['id'])}.webp"
            if r["has_image"] and old_img.is_file():
                shutil.copyfile(old_img, image_path(r["school_id"], new_id))
                conn.execute("UPDATE school_formats SET has_image=1 WHERE id=?", (new_id,))
            conn.execute("UPDATE school_products SET migrated_to=? WHERE id=?", (new_id, r["id"]))
            moved += 1
        conn.commit()
    if moved:
        logger.info("Catalogue: %d product(s) merged into the single list", moved)
    return moved


def portal_view(school_id: str) -> list[dict]:
    """Offered products for the family's gallery, in order — the same list for classic and AI photos. A `choice`
    product comes as its two variants (see `expand`)."""
    return [{**{k: f[k] for k in ("format_id", "kind", "price", "popular", "physical", "digital", "name_fr",
                                  "name_en", "name_es", "sub_fr", "sub_en", "sub_es", "image_url")},
             **({"group": f["group"], "variant": f["variant"]} if "group" in f else {})}
            for f in expand(list_formats(school_id, active_only=True))]
