"""End-to-end purchases with the client's real catalogue (2026-10-28): what the family downloads, what the lab gets,
what the recap and the dashboards count — for every kind of product on sale and their mixes.

The catalogue mirrors Settings > Sales > Products as the client set it, with the kinds corrected: a product with a
size is a print, the file is "La photo numérique HD", the pack holds prints (and here also the file, to check that a
digital product inside a pack is never sent to the lab). Orders go through the real portal route (price check and
the copy of what each line delivers), then are marked paid.
"""
import io
import uuid
import zipfile

import pytest
from PIL import Image

from core import storage
from core.db import get_db
from services import photo_service


def _jpeg(color) -> bytes:
    buf = io.BytesIO()
    Image.new("RGB", (64, 48), color).save(buf, "JPEG")
    return buf.getvalue()


@pytest.fixture
async def shop(client, admin_token):
    """A school with class CP/CE1 (two pupils), a Siblings photo, the client's catalogue, and the families' consent."""
    h = {"Authorization": f"Bearer {admin_token}"}
    sid = (await client.post("/api/admin/schools", json={"name": f"Escudier {uuid.uuid4().hex[:6]}"}, headers=h)).json()["school"]["id"]
    hs = {**h, "X-School": sid}
    cid = (await client.post("/api/admin/classes", json={"name": "CP/CE1"}, headers=hs)).json()["class"]["id"]
    for n, color in (("A.jpg", (200, 10, 10)), ("B.jpg", (10, 200, 10))):
        await client.post(f"/api/admin/classes/{cid}/photos", headers=hs, files={"file": (n, _jpeg(color), "image/jpeg")})
    assert (await client.post(f"/api/admin/classes/{cid}/validate", headers=hs)).status_code == 200
    cards = (await client.get("/api/admin/cards", headers=hs)).json()["cards"]
    codes = {c["filename"]: c["code"] for c in cards}
    for code in codes.values():
        assert (await client.post("/api/portal/consent", json={"family_code": code})).status_code == 200

    async def product(name, kind, price, **kw):
        r = await client.post("/api/admin/formats", headers=hs, json={"name_fr": name, "kind": kind, "price": price, **kw})
        assert r.status_code == 200, r.text
        return r.json()["format"]

    # the built-in rows are switched off: the catalogue is exactly the client's
    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})
    p = {
        "13x18": await product("Le portrait à poser (13 × 18)", "print", 9),
        "15x21": await product("Le portrait à offrir (15 × 21)", "print", 12, active=False),     # only in the pack
        "18x24": await product("Le grand portrait (18 × 24)", "print", 12),
        "magnet": await product("Le magnet frigo (10 × 15)", "print", 10),
        "hd": await product("La photo numérique HD", "digital", 20),
        "keyring": await product("Porte-clé", "print", 5),
        "calendar": await product("Le calendrier 2027 avec la photo de votre enfant", "print", 15),
    }
    p["pack"] = await product("Le pack Souvenir", "pack", 39, components=[
        {"format_id": p[k]["format_id"], "qty": 1} for k in ("13x18", "15x21", "18x24", "magnet", "hd", "keyring", "calendar")])
    p["pack_print"] = await product("Le pack Papier", "print", 25, components=[
        {"format_id": p["13x18"]["format_id"], "qty": 2}, {"format_id": p["hd"]["format_id"], "qty": 1}])
    return {"h": hs, "sid": sid, "codes": codes, "p": p, "client": client}


async def _buy(shop, code, lines, *, expect=200):
    """lines = [(product key or format_id, photo, qty)] at the catalogue price; returns the paid order id."""
    portal = (await shop["client"].get("/api/portal/photos", params={"code": code})).json()["formats"]
    prices = {f["format_id"]: f["price"] for f in portal}
    items, total = [], 0.0
    for key, photo, qty in lines:
        fid = shop["p"][key]["format_id"] if key in shop["p"] else key
        price = prices.get(fid, shop["p"].get(key, {}).get("price", 1.0))
        items.append({"photo_filename": photo, "format_id": fid, "format_label": "x", "quantity": qty,
                      "unit_price": price, "is_magic": photo.startswith("ia_")})
        total += price * qty
    r = await shop["client"].post("/api/portal/orders", json={
        "family_code": code, "customer_email": "parent@example.com", "class_name": "CP/CE1", "items": items,
        "total": round(total, 2)})
    assert r.status_code == expect, r.text
    if expect != 200:
        return None
    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 _outcome(shop, code, oid):
    """(files the family can download, files the lab gets without the recap, prints counted, recap present)."""
    c, h = shop["client"], shop["h"]
    orders = (await c.get("/api/portal/orders", params={"code": code})).json()["orders"]
    downloads = sorted(d["filename"] for d in next(o for o in orders if o["id"] == oid)["downloads"])
    detail = (await c.get(f"/api/admin/orders/{oid}", headers=h)).json()["detail"]
    z = await c.get(f"/api/admin/orders/{oid}/lab.zip", headers=h)
    lab, recap = [], False
    if z.status_code == 200:
        names = zipfile.ZipFile(io.BytesIO(z.content)).namelist()
        recap = any(n.endswith(".pdf") for n in names)
        lab = sorted(n.split("/")[-1].split("_", 1)[-1] for n in names if not n.endswith(".pdf"))   # minus "{code}_"
    else:
        assert z.status_code == 404                                    # nothing to print
    return downloads, lab, detail["prints"], recap


async def test_the_portal_offers_exactly_the_offered_products(shop):
    names = {f["name_fr"] for f in (await shop["client"].get("/api/portal/photos", params={"code": shop["codes"]["A.jpg"]})).json()["formats"]}
    assert "Le portrait à offrir (15 × 21)" not in names                  # only inside the pack
    assert {"Le pack Souvenir", "La photo numérique HD", "Le grand portrait (18 × 24)", "Porte-clé"} <= names


@pytest.mark.parametrize("lines, downloads, lab, prints", [
    # one print, two copies: the lab gets one file x2, no download
    ([("13x18", "A.jpg", 2)], [], ["CP-CE1_13x18_x2.jpg"], 2),
    # the file alone: a download, nothing for the lab
    ([("hd", "A.jpg", 1)], ["A.jpg"], [], 0),
    # print + the file of the same photo
    ([("18x24", "A.jpg", 1), ("hd", "A.jpg", 1)], ["A.jpg"], ["CP-CE1_18x24_x1.jpg"], 1),
    # an object without a size: named after the product
    ([("keyring", "A.jpg", 3)], [], ["CP-CE1_Porte-cle_x3.jpg"], 3),
    # the pack: every PRINT inside goes to the lab (the file inside is not printed), and the family gets the file
    ([("pack", "A.jpg", 1)], ["A.jpg"], sorted([
        "CP-CE1_Le-pack-Souvenir_13x18_x1.jpg", "CP-CE1_Le-pack-Souvenir_15x21_x1.jpg",
        "CP-CE1_Le-pack-Souvenir_18x24_x1.jpg", "CP-CE1_Le-pack-Souvenir_Magnet-10x15_x1.jpg",
        "CP-CE1_Le-pack-Souvenir_Porte-cle_x1.jpg",
        "CP-CE1_Le-pack-Souvenir_Calendrier_x1.jpg"]), 6),
    # two packs: every quantity doubles
    ([("pack", "A.jpg", 2)], ["A.jpg"], sorted([
        "CP-CE1_Le-pack-Souvenir_13x18_x2.jpg", "CP-CE1_Le-pack-Souvenir_15x21_x2.jpg",
        "CP-CE1_Le-pack-Souvenir_18x24_x2.jpg", "CP-CE1_Le-pack-Souvenir_Magnet-10x15_x2.jpg",
        "CP-CE1_Le-pack-Souvenir_Porte-cle_x2.jpg",
        "CP-CE1_Le-pack-Souvenir_Calendrier_x2.jpg"]), 12),
    # a pack of kind "print": its prints go to the lab; it gives NO download, even with the file listed inside
    ([("pack_print", "A.jpg", 1)], [], ["CP-CE1_Le-pack-Papier_13x18_x2.jpg"], 2),
    # a mix: pack + extra print + the file on another photo of the same family is a different order (other code)
    ([("pack", "A.jpg", 1), ("magnet", "A.jpg", 2)], ["A.jpg"], sorted([
        "CP-CE1_Magnet-10x15_x2.jpg", "CP-CE1_Le-pack-Souvenir_13x18_x1.jpg", "CP-CE1_Le-pack-Souvenir_15x21_x1.jpg",
        "CP-CE1_Le-pack-Souvenir_18x24_x1.jpg", "CP-CE1_Le-pack-Souvenir_Magnet-10x15_x1.jpg",
        "CP-CE1_Le-pack-Souvenir_Porte-cle_x1.jpg",
        "CP-CE1_Le-pack-Souvenir_Calendrier_x1.jpg"]), 8),
])
async def test_what_each_purchase_delivers(shop, lines, downloads, lab, prints):
    code = shop["codes"]["A.jpg"]
    oid = await _buy(shop, code, lines)
    got_dl, got_lab, got_prints, recap = await _outcome(shop, code, oid)
    assert got_dl == downloads
    assert got_lab == lab
    assert got_prints == prints
    assert recap == bool(lab)                                          # the recap travels with the photos


async def test_an_ai_photo_is_sold_like_any_photo(shop):
    code = shop["codes"]["A.jpg"]
    folder = photo_service.family_dirs(shop["sid"], code)[0][1]
    storage.write_bytes(folder / "ia_1061_1.jpg", _jpeg((90, 90, 200)))   # a generated "dream job" photo
    photo_service.invalidate_families_cache(shop["sid"])
    oid = await _buy(shop, code, [("18x24", "ia_1061_1.jpg", 1), ("hd", "ia_1061_1.jpg", 1)])
    dl, lab, prints, _ = await _outcome(shop, code, oid)
    assert dl == ["ia_1061_1.jpg"] and lab == ["CP-CE1_18x24_x1.jpg"] and prints == 1


async def test_the_server_refuses_what_is_not_on_sale_or_not_at_its_price(shop):
    code = shop["codes"]["A.jpg"]
    await _buy(shop, code, [("15x21", "A.jpg", 1)], expect=400)          # only inside the pack, not alone
    c = shop["client"]
    item = {"photo_filename": "A.jpg", "format_id": shop["p"]["pack"]["format_id"], "format_label": "x",
            "quantity": 1, "unit_price": 1.0, "is_magic": False}
    r = await c.post("/api/portal/orders", json={"family_code": code, "customer_email": "p@example.com",
                                                  "class_name": "CP/CE1", "items": [item], "total": 1.0})
    assert r.status_code == 400                                        # a price typed in the browser
    r = await c.post("/api/portal/orders", json={"family_code": code, "customer_email": "p@example.com", "class_name": "CP/CE1",
                                                  "items": [{**item, "unit_price": 39.0, "photo_filename": "B.jpg"}], "total": 39.0})
    assert r.status_code == 400                                        # another family's photo


async def test_a_paid_order_never_changes_when_the_catalogue_does(shop):
    code = shop["codes"]["A.jpg"]
    oid = await _buy(shop, code, [("pack", "A.jpg", 1), ("18x24", "A.jpg", 1)])
    before = await _outcome(shop, code, oid)
    c, h, p = shop["client"], shop["h"], shop["p"]
    await c.patch(f"/api/admin/formats/{p['pack']['id']}", headers=h,
                  json={"kind": "print", "components": [{"format_id": p["magnet"]["format_id"], "qty": 4}]})
    await c.patch(f"/api/admin/formats/{p['18x24']['id']}", headers=h, json={"kind": "digital", "name_fr": "Renamed"})
    assert (await c.delete(f"/api/admin/formats/{p['keyring']['id']}", headers=h)).status_code == 200
    assert await _outcome(shop, code, oid) == before


async def test_dashboards_count_what_is_handed_out(shop):
    """The class's prints to hand out count what the lab prints (a pack = its prints), like the order's "to print"."""
    code = shop["codes"]["A.jpg"]
    await _buy(shop, code, [("pack", "A.jpg", 1), ("13x18", "A.jpg", 2), ("hd", "A.jpg", 1)])
    classes = (await shop["client"].get("/api/admin/classes", headers=shop["h"])).json()["classes"]
    cp = next(c for c in classes if c["class_name"] == "CP/CE1")
    assert cp["prints"] == 6 + 2 and cp["buyers"] == 1 and cp["orders"] == 1
