"""Print templates of a product (client 2026-11-15): a PNG with transparent zones, the lab folder of a paid order gets
the finished montage (calendar, ID photo sheet) as a print-ready JPEG; families never see it."""
import io
import uuid
import zipfile

import pytest
from PIL import Image

from core.db import get_db
from services import template_service


def _jpeg(size=(400, 600), color=(30, 90, 200)) -> bytes:
    buf = io.BytesIO()
    Image.new("RGB", size, color).save(buf, "JPEG")
    return buf.getvalue()


def _template(size=(600, 400), holes=((60, 50, 140, 180),), dpi=(300, 300)) -> bytes:
    """A white sheet with transparent holes (x, y, w, h), like the client's PNGs."""
    img = Image.new("RGBA", size, (255, 255, 255, 255))
    for x, y, w, h in holes:
        img.paste((0, 0, 0, 0), (x, y, x + w, y + h))
    buf = io.BytesIO()
    img.save(buf, "PNG", dpi=dpi)
    return buf.getvalue()


# ── The service ──────────────────────────────────────────────────────────────────

def test_holes_are_found_row_by_row_and_specks_ignored():
    holes = ((320, 40, 100, 120), (60, 40, 100, 120), (60, 220, 100, 120), (450, 30, 120, 330), (5, 5, 2, 2))
    img = Image.open(io.BytesIO(_template(holes=holes)))
    slots = template_service.detect_slots(img)
    assert len(slots) == 4                                          # the 2x2 speck is not a slot
    xs = [round(s[0] * 600) for s in slots]
    assert xs[:3] == [57, 317, 447] and xs[3] == 57                 # first row left to right, then the second row


def test_size_comes_from_the_png_dpi_or_300(isolated_products):
    t = template_service.save("s", _template(size=(2030, 1510), dpi=(254, 254)))   # the client's ID sheet
    assert (t["width_mm"], t["height_mm"]) == (203.0, 151.0)
    assert template_service.out_px(template_service.with_size(t, 203, 152)) == (2398, 1795)   # like their tool
    t = template_service.save("s", _template(dpi=(1, 1)))           # no usable dpi -> 300
    assert t["width_mm"] == round(600 / 300 * 25.4, 1)


def test_a_png_without_transparency_or_not_a_png_is_refused(isolated_products):
    full = io.BytesIO()
    Image.new("RGBA", (300, 200), (255, 255, 255, 255)).save(full, "PNG")
    with pytest.raises(template_service.TemplateError):
        template_service.save("s", full.getvalue())
    with pytest.raises(template_service.TemplateError):
        template_service.save("s", _jpeg())


def test_the_photo_fills_the_slot_and_the_frame_is_raised():
    """A tall photo in a square slot: the overflow is cut, more at the bottom than at the top (heads stay)."""
    photo = Image.new("L", (100, 300))
    for y in range(300):
        photo.paste(y * 255 // 299, (0, y, 100, y + 1))
    out = template_service.place(photo.convert("RGB"), (0, 0, 100, 100))
    assert out.size == (100, 100)
    top = out.getpixel((50, 0))[0] * 299 // 255
    assert 60 <= top <= 80                                          # 35 % of the 200 px overflow cut at the top


def test_the_montage_is_the_print_size_with_the_photo_under_the_template(isolated_products):
    tpl = template_service.save("s", _template(holes=((60, 50, 140, 180), (300, 50, 140, 180))))
    out = Image.open(io.BytesIO(template_service.render("s", tpl, _jpeg(color=(200, 20, 20)))))
    assert out.format == "JPEG" and out.size == (600, 400) and round(out.info["dpi"][0]) == 300
    assert out.getpixel((130, 140))[0] > 150 and out.getpixel((370, 140))[0] > 150   # the photo in BOTH slots
    assert out.getpixel((5, 5)) == (255, 255, 255) or min(out.getpixel((5, 5))) > 245  # the template on top


# ── Through the app ──────────────────────────────────────────────────────────────

@pytest.fixture
def isolated_products(tmp_path, monkeypatch):
    from core import config
    monkeypatch.setattr(config, "PRODUCTS_DIR", tmp_path / "products")


@pytest.fixture
async def shop(client, admin_token):
    h = {"Authorization": f"Bearer {admin_token}"}
    sid = (await client.post("/api/admin/schools", json={"name": f"Tpl {uuid.uuid4().hex[:6]}"}, headers=h)).json()["school"]["id"]
    hs = {**h, "X-School": sid}
    cid = (await client.post("/api/admin/classes", json={"name": "CP"}, headers=hs)).json()["class"]["id"]
    await client.post(f"/api/admin/classes/{cid}/photos", headers=hs, files={"file": ("A.jpg", _jpeg(), "image/jpeg")})
    assert (await client.post(f"/api/admin/classes/{cid}/validate", headers=hs)).status_code == 200
    code = (await client.get("/api/admin/cards", headers=hs)).json()["cards"][0]["code"]
    assert (await client.post("/api/portal/consent", json={"family_code": code})).status_code == 200
    for f in (await client.get("/api/admin/formats", headers=hs)).json()["formats"]:
        await client.patch(f"/api/admin/formats/{f['id']}", headers=hs, json={"active": False})
    cal = (await client.post("/api/admin/formats", headers=hs,
                             json={"name_fr": "Calendrier 2027", "kind": "print", "price": 15})).json()["format"]
    plain = (await client.post("/api/admin/formats", headers=hs,
                               json={"name_fr": "Tirage 13×18", "kind": "print", "price": 9})).json()["format"]
    return {"c": client, "h": hs, "sid": sid, "code": code, "cal": cal, "plain": plain}


async def _upload(shop, png=None):
    return await shop["c"].post(f"/api/admin/formats/{shop['cal']['id']}/template", headers=shop["h"],
                                files={"file": ("cal.png", png or _template(), "image/png")})


async def _buy(shop, fmt, qty=1):
    c = shop["c"]
    r = await c.post("/api/portal/orders", json={
        "family_code": shop["code"], "customer_email": "p@example.com", "class_name": "CP", "total": fmt["price"] * qty,
        "items": [{"photo_filename": "A.jpg", "format_id": fmt["format_id"], "format_label": "x", "quantity": qty,
                   "unit_price": fmt["price"], "is_magic": False}]})
    assert r.status_code == 200, r.text
    oid = r.json()["order_id"]
    with get_db() as conn:
        conn.execute("UPDATE orders SET payment_status='paid' WHERE id=?", (oid,))
        conn.commit()
    return oid


async def _lab(shop, oid) -> dict[str, bytes]:
    z = await shop["c"].get(f"/api/admin/orders/{oid}/lab.zip", headers=shop["h"])
    assert z.status_code == 200, z.text
    zf = zipfile.ZipFile(io.BytesIO(z.content))
    return {n.split("/")[-1]: zf.read(n) for n in zf.namelist() if not n.endswith(".pdf")}


async def test_admin_uploads_a_template_and_settings_show_its_zones_and_size(shop):
    r = await _upload(shop)
    assert r.status_code == 200, r.text
    tv = r.json()["format"]["template_view"]
    assert len(tv["slots"]) == 1 and tv["out_px"] == [600, 400] and not tv["ratio_off"]
    assert (await shop["c"].get(tv["preview_url"])).status_code == 200
    assert (await shop["c"].get(tv["preview_url"].replace("sig=", "sig=0"))).status_code == 403
    r = await shop["c"].patch(f"/api/admin/formats/{shop['cal']['id']}/template", headers=shop["h"],
                              json={"width_mm": 100, "height_mm": 100})
    assert r.json()["format"]["template_view"]["ratio_off"] is True       # 3:2 PNG printed square: warned
    bad = await _upload(shop, _jpeg())
    assert bad.status_code == 400


async def test_only_the_admin_sets_a_template(shop, client, operator_headers):
    r = await client.post(f"/api/admin/formats/{shop['cal']['id']}/template", headers={**operator_headers, "X-School": shop["sid"]},
                          files={"file": ("cal.png", _template(), "image/png")})
    assert r.status_code == 403


async def test_families_never_get_the_template(shop):
    await _upload(shop)
    formats = (await shop["c"].get("/api/portal/photos", params={"code": shop["code"]})).json()["formats"]
    cal = next(f for f in formats if f["format_id"] == shop["cal"]["format_id"])
    assert "template" not in cal and "template_view" not in cal


async def test_the_lab_gets_the_finished_montage_and_a_plain_product_the_original(shop):
    await _upload(shop)
    files = await _lab(shop, await _buy(shop, shop["cal"], qty=2))
    (name, data), = files.items()
    assert name == f"{shop['code']}_CP_Calendrier_x2.jpg"
    im = Image.open(io.BytesIO(data))
    assert im.size == (600, 400) and round(im.info["dpi"][0]) == 300
    files = await _lab(shop, await _buy(shop, shop["plain"]))
    assert Image.open(io.BytesIO(next(iter(files.values())))).size == (400, 600)   # the original, untouched


async def test_a_paid_order_keeps_the_template_it_was_bought_with(shop):
    await _upload(shop)
    oid = await _buy(shop, shop["cal"])
    await shop["c"].delete(f"/api/admin/formats/{shop['cal']['id']}/template", headers=shop["h"])
    await _upload(shop, _template(size=(300, 300), holes=((10, 10, 100, 100),)))     # next year's design
    im = Image.open(io.BytesIO(next(iter((await _lab(shop, oid)).values()))))
    assert im.size == (600, 400)                                    # still the design it was paid with
    new = await _buy(shop, shop["cal"])
    assert Image.open(io.BytesIO(next(iter((await _lab(shop, new)).values())))).size == (300, 300)


async def test_a_pack_component_with_a_template_is_assembled_in_the_pack(shop):
    await _upload(shop)
    c, h = shop["c"], shop["h"]
    pack = (await c.post("/api/admin/formats", headers=h, json={
        "name_fr": "Pack Souvenir", "kind": "print", "price": 30,
        "components": [{"format_id": shop["cal"]["format_id"], "qty": 1}, {"format_id": shop["plain"]["format_id"], "qty": 2}]})).json()["format"]
    files = await _lab(shop, await _buy(shop, pack))
    sizes = {n.split("_", 2)[-1]: Image.open(io.BytesIO(d)).size for n, d in files.items()}
    assert sizes == {"Pack-Souvenir_Calendrier_x1.jpg": (600, 400), "Pack-Souvenir_13x18_x2.jpg": (400, 600)}


async def test_the_admin_can_try_a_photo_in_the_template(shop):
    await _upload(shop)
    r = await shop["c"].post(f"/api/admin/formats/{shop['cal']['id']}/template/test", headers=shop["h"],
                             files={"file": ("me.jpg", _jpeg(), "image/jpeg")})
    assert r.status_code == 200 and r.headers["content-type"] == "image/jpeg"
    assert Image.open(io.BytesIO(r.content)).size == (600, 400)
    r = await shop["c"].post(f"/api/admin/formats/{shop['plain']['id']}/template/test", headers=shop["h"],
                             files={"file": ("me.jpg", _jpeg(), "image/jpeg")})
    assert r.status_code == 400                                      # no template on that product


# ── Test orders: the admin sees the lab zip without paying (client 2026-11-15) ──────────────────────────────────────

async def test_a_test_order_gives_the_lab_zip_and_counts_nowhere(shop, client, operator_headers):
    await _upload(shop)
    c, h = shop["c"], shop["h"]
    body = {"family_code": shop["code"], "photo_filename": "A.jpg",
            "items": [{"format_id": shop["cal"]["format_id"], "quantity": 2}, {"format_id": shop["plain"]["format_id"]}]}
    r = await client.post("/api/admin/orders/test", json=body, headers={**operator_headers, "X-School": shop["sid"]})
    assert r.status_code == 403                                      # the admin only
    r = await c.post("/api/admin/orders/test", json=body, headers=h)
    assert r.status_code == 200, r.text
    oid = r.json()["order_id"]

    listed = (await c.get("/api/admin/orders", headers=h)).json()["orders"]
    assert [o["payment_status"] for o in listed if o["id"] == oid] == ["test"]
    files = await _lab(shop, oid)                                    # exactly what a paid order gives
    sizes = sorted(Image.open(io.BytesIO(d)).size for d in files.values())
    assert sizes == [(400, 600), (600, 400)]
    assert any(n.endswith("_Calendrier_x2.jpg") for n in files)
    z = zipfile.ZipFile(io.BytesIO((await c.get(f"/api/admin/orders/{oid}/lab.zip", headers=h)).content))
    assert all(n.startswith(f"TEST-order-{oid[:8].upper()}/") for n in z.namelist())   # never sent to print by mistake

    stats = (await c.get("/api/admin/stats", headers=h)).json()
    assert stats["orders_count"] == 0 and stats["revenue"] == 0      # no sale, no school share
    family = (await c.get("/api/portal/orders", params={"code": shop["code"]})).json()["orders"]
    assert family == []                                              # the family never sees it

    assert (await c.delete(f"/api/admin/orders/{oid}", headers=h)).status_code == 200
    paid = await _buy(shop, shop["plain"])
    assert (await c.delete(f"/api/admin/orders/{paid}", headers=h)).status_code == 409   # a real sale stays


async def test_a_test_order_refuses_a_photo_of_another_family(shop):
    r = await shop["c"].post("/api/admin/orders/test", headers=shop["h"], json={
        "family_code": shop["code"], "photo_filename": "nope.jpg", "items": [{"format_id": shop["cal"]["format_id"]}]})
    assert r.status_code == 400
