"""Editable catalogue of formats and sizes (client request: create formats, set prices from Settings)."""
import json
import uuid

from conftest import DEMO_CODE, SCHOOL, OTHER_SCHOOL
from core.db import get_db


def _order(fmt_id, price, photo="portrait.jpg", magic=False):
    return {"family_code": DEMO_CODE, "customer_email": "a@example.com", "class_name": "CE1 A",
            "items": [{"photo_filename": photo, "format_id": fmt_id, "format_label": "x", "quantity": 1,
                       "unit_price": price, "is_magic": magic}], "total": price}


async def _new_format(client, headers, **kw):
    body = {"name_fr": f"Tirage 13×18 {uuid.uuid4().hex[:4]}", "kind": "print", "price": 11.0, **kw}
    r = await client.post("/api/admin/formats", headers=headers, json=body)
    assert r.status_code == 200, r.text
    return r.json()["format"]


async def test_the_historical_formats_are_in_the_catalogue_with_their_prices(client, admin_headers):
    fmts = (await client.get("/api/admin/formats", headers=admin_headers)).json()["formats"]
    ids = {f["format_id"]: f for f in fmts}
    assert {"print-10x15", "print-20x30", "digital", "pack"} <= set(ids)
    assert not any(i.startswith("magic-") for i in ids)          # one list for classic and AI photos (brief sheet 3)
    assert ids["digital"]["builtin"] and ids["digital"]["digital"] and not ids["digital"]["physical"]
    assert ids["pack"]["physical"] and ids["pack"]["digital"]


async def test_a_new_size_is_offered_to_families_and_can_be_ordered(client, admin_headers):
    fmt = await _new_format(client, admin_headers)
    portal = (await client.get("/api/portal/photos", params={"code": DEMO_CODE})).json()
    offered = {f["format_id"]: f for f in portal["formats"]}
    assert fmt["format_id"] in offered and offered[fmt["format_id"]]["price"] == 11.0
    r = await client.post("/api/portal/orders", json=_order(fmt["format_id"], 11.0))
    assert r.status_code == 200, r.text
    with get_db() as conn:
        items = json.loads(conn.execute("SELECT items_json FROM orders WHERE id=?", (r.json()["order_id"],)).fetchone()["items_json"])
    assert items[0]["kind"] == "print" and items[0]["digital"] is False and items[0]["format_names"]["fr"] == fmt["name_fr"]


async def test_the_server_refuses_a_wrong_price_an_inactive_format_or_a_magic_mismatch(client, admin_headers):
    fmt = await _new_format(client, admin_headers, price=12.5)
    assert (await client.post("/api/portal/orders", json=_order(fmt["format_id"], 1.0))).status_code == 400
    assert (await client.post("/api/portal/orders", json=_order(fmt["format_id"], 12.5, magic=True))).status_code == 400
    await client.patch(f"/api/admin/formats/{fmt['id']}", headers=admin_headers, json={"active": False})
    assert (await client.post("/api/portal/orders", json=_order(fmt["format_id"], 12.5))).status_code == 400
    portal = (await client.get("/api/portal/photos", params={"code": DEMO_CODE})).json()
    assert fmt["format_id"] not in {f["format_id"] for f in portal["formats"]}


async def test_a_new_digital_format_gives_the_download_once_paid(client, admin_headers):
    fmt = await _new_format(client, admin_headers, kind="digital", price=5.0, name_fr="Numérique web")
    r = await client.post("/api/portal/orders", json=_order(fmt["format_id"], 5.0))
    oid = r.json()["order_id"]
    with get_db() as conn:
        conn.execute("UPDATE orders SET payment_status='paid' WHERE id=?", (oid,))
        conn.commit()
    orders = (await client.get("/api/portal/orders", params={"code": DEMO_CODE})).json()["orders"]
    assert len(next(o for o in orders if o["id"] == oid)["downloads"]) == 1
    # deleting the format later does not take the purchase away
    assert (await client.delete(f"/api/admin/formats/{fmt['id']}", headers=admin_headers)).status_code == 200
    orders = (await client.get("/api/portal/orders", params={"code": DEMO_CODE})).json()["orders"]
    assert len(next(o for o in orders if o["id"] == oid)["downloads"]) == 1


async def test_a_builtin_price_edit_goes_to_its_setting_and_its_kind_can_change(client, admin_headers):
    fmts = (await client.get("/api/admin/formats", headers=admin_headers)).json()["formats"]
    big = next(f for f in fmts if f["format_id"] == "print-20x30")
    old = big["price"]
    try:
        r = await client.patch(f"/api/admin/formats/{big['id']}", headers=admin_headers,
                               json={"price": 15.5, "name_fr": "Poster 20×30"})
        assert r.status_code == 200 and r.json()["format"]["price"] == 15.5
        portal = (await client.get("/api/portal/photos", params={"code": DEMO_CODE})).json()
        assert portal["pricing"]["print_20x30"] == 15.5
        assert next(f for f in portal["formats"] if f["format_id"] == "print-20x30")["name_fr"] == "Poster 20×30"
        # what it delivers is editable too (2026-10-28: a "pack" made as a print gave no digital photo)
        r = await client.patch(f"/api/admin/formats/{big['id']}", headers=admin_headers, json={"kind": "pack"})
        assert r.status_code == 200 and r.json()["format"]["digital"] and r.json()["format"]["physical"]
        oid = (await client.post("/api/portal/orders", json=_order("print-20x30", 15.5))).json()["order_id"]
        with get_db() as conn:
            conn.execute("UPDATE orders SET payment_status='paid' WHERE id=?", (oid,))
            conn.commit()
        orders = (await client.get("/api/portal/orders", params={"code": DEMO_CODE})).json()["orders"]
        assert len(next(o for o in orders if o["id"] == oid)["downloads"]) == 1     # the HD file comes with it now
    finally:
        await client.patch(f"/api/admin/formats/{big['id']}", headers=admin_headers,
                           json={"price": old, "name_fr": "Tirage papier 20×30", "kind": "print"})


async def test_formats_are_per_school_and_a_director_only_reads_them(client, admin_headers, other_admin_headers,
                                                                     director_headers):
    fmt = await _new_format(client, admin_headers)
    other = (await client.get("/api/admin/formats", headers=other_admin_headers)).json()["formats"]
    assert fmt["format_id"] not in {f["format_id"] for f in other}
    assert (await client.patch(f"/api/admin/formats/{fmt['id']}", headers=other_admin_headers,
                               json={"price": 1})).status_code == 404
    assert (await client.get("/api/admin/formats", headers=director_headers)).status_code == 200
    assert (await client.post("/api/admin/formats", headers=director_headers,
                              json={"name_fr": "x", "kind": "print", "price": 1})).status_code == 403
    bad = await client.post("/api/admin/formats", headers=admin_headers, json={"name_fr": "x", "kind": "hologram", "price": 1})
    assert bad.status_code == 400
    assert OTHER_SCHOOL != SCHOOL


async def test_a_builtin_product_can_be_deleted_and_stays_deleted(client, admin_headers):
    """Client 2026-10: every format is editable, the original ones too. The row is only marked, or the next read
    would create it again."""
    fmts = (await client.get("/api/admin/formats", headers=admin_headers)).json()["formats"]
    big = next(f for f in fmts if f["format_id"] == "print-20x30")
    try:
        assert (await client.delete(f"/api/admin/formats/{big['id']}", headers=admin_headers)).status_code == 200
        for _ in range(2):                                              # the second read must not bring it back
            again = (await client.get("/api/admin/formats", headers=admin_headers)).json()["formats"]
            assert "print-20x30" not in {f["format_id"] for f in again}
        portal = (await client.get("/api/portal/photos", params={"code": DEMO_CODE})).json()
        assert "print-20x30" not in {f["format_id"] for f in portal["formats"]}
        assert (await client.post("/api/portal/orders", json=_order("print-20x30", big["price"]))).status_code == 400
        assert (await client.patch(f"/api/admin/formats/{big['id']}", headers=admin_headers,
                                   json={"price": 1})).status_code == 404
        assert (await client.delete(f"/api/admin/formats/{big['id']}", headers=admin_headers)).status_code == 404
    finally:
        with get_db() as conn:
            conn.execute("UPDATE school_formats SET deleted_at=NULL, active=1 WHERE id=?", (big["id"],))
            conn.commit()


async def test_a_description_can_be_long_and_old_tables_are_widened(client, admin_headers):
    """Client 2026-10-28: 160 characters were too few to describe a pack."""
    from services import format_service
    with get_db() as conn:                                      # a table made before the change
        conn.execute("ALTER TABLE school_formats MODIFY sub_fr VARCHAR(160) NOT NULL DEFAULT ''")
        conn.commit()
    format_service.init_format_table()
    text = "Un grand portrait 18x24, deux portraits 13x18 et un magnet. " * 8          # ~490 characters
    fmt = await _new_format(client, admin_headers, sub_fr=text[:500])
    assert fmt["sub_fr"] == " ".join(text[:500].split())
    assert len(fmt["sub_fr"]) > 400


async def test_a_pack_lists_its_products_and_the_lab_gets_one_file_per_product(client, admin_headers):
    """Client 2026-10-28: the pack's name AND the products in it, so the lab knows what to print and how many."""
    import io, zipfile
    small = await _new_format(client, admin_headers, name_fr="Portrait à poser 13×18")
    big = await _new_format(client, admin_headers, name_fr="Grand portrait 18×24", active=False)    # only in the pack
    pack = await _new_format(client, admin_headers, name_fr="Le pack Souvenir", kind="pack", price=39.0,
                             components=[{"format_id": small["format_id"], "qty": 2}, {"format_id": big["format_id"], "qty": 1}])
    assert [(c["format_id"], c["qty"], c["name_fr"]) for c in pack["components"]] == [
        (small["format_id"], 2, "Portrait à poser 13×18"), (big["format_id"], 1, "Grand portrait 18×24")]
    # nonsense is refused: itself, a pack in a pack, a stranger, a zero
    bad = [[{"format_id": pack["format_id"], "qty": 1}], [{"format_id": "fmt-999999", "qty": 1}],
           [{"format_id": small["format_id"], "qty": 0}]]
    for comps in bad:
        r = await client.patch(f"/api/admin/formats/{pack['id']}", headers=admin_headers, json={"components": comps})
        assert r.status_code == 400, comps
    r = await client.post("/api/admin/formats", headers=admin_headers, json={
        "name_fr": "Pack de packs", "kind": "pack", "price": 1, "components": [{"format_id": pack["format_id"], "qty": 1}]})
    assert r.status_code == 400
    r = await client.patch(f"/api/admin/formats/{small['id']}", headers=admin_headers,
                           json={"components": [{"format_id": big["format_id"], "qty": 1}]})
    assert r.status_code == 400                                     # it is in a pack: it cannot become one

    # a paid order of 2 packs: 4 portraits 13x18 + 2 big ones, each its own file, the recap inside
    oid = (await client.post("/api/portal/orders", json={**_order(pack["format_id"], 39.0),
        "items": [{**_order(pack["format_id"], 39.0)["items"][0], "quantity": 2}], "total": 78.0})).json()["order_id"]
    with get_db() as conn:
        conn.execute("UPDATE orders SET payment_status='paid' WHERE id=?", (oid,))
        conn.commit()
    detail = (await client.get(f"/api/admin/orders/{oid}", headers=admin_headers)).json()["detail"]
    assert detail["prints"] == 6
    assert [(c["name"], c["qty"]) for c in detail["lines"][0]["components"]] == [
        ("Portrait à poser 13×18", 2), ("Grand portrait 18×24", 1)]
    z = zipfile.ZipFile(io.BytesIO((await client.get(f"/api/admin/orders/{oid}/lab.zip", headers=admin_headers)).content))
    photos = sorted(n.split("/")[-1] for n in z.namelist() if not n.endswith(".pdf"))
    assert len(photos) == 2 and photos[0].endswith("_Le-pack-Souvenir_13x18_x4.jpg")         and photos[1].endswith("_Le-pack-Souvenir_18x24_x2.jpg")

    # editing the pack afterwards does not change the paid order
    await client.patch(f"/api/admin/formats/{pack['id']}", headers=admin_headers,
                       json={"components": [{"format_id": small["format_id"], "qty": 5}]})
    again = (await client.get(f"/api/admin/orders/{oid}", headers=admin_headers)).json()["detail"]
    assert again["prints"] == 6


async def test_print_file_or_both_each_with_its_own_price(client, admin_headers):
    """Client 2026-10-28: "printed with its price, digital with its price, both with its price" — three prices."""
    import io, zipfile
    fmt = await _new_format(client, admin_headers, name_fr="Le grand portrait (18 × 24)", kind="choice",
                            price=12.0, price_digital=8.0, price_both=17.0)
    assert (fmt["kind"], fmt["price"], fmt["price_digital"], fmt["price_both"]) == ("choice", 12.0, 8.0, 17.0)
    for missing in ({"price_digital": 3}, {"price_both": 3}):                # the three prices are required
        assert (await client.post("/api/admin/formats", headers=admin_headers,
                                  json={"name_fr": "x", "kind": "choice", "price": 3, **missing})).status_code == 400
    portal = (await client.get("/api/portal/photos", params={"code": DEMO_CODE})).json()["formats"]
    variants = [f for f in portal if f.get("group") == fmt["format_id"]]
    fid = fmt["format_id"]
    assert [(v["format_id"], v["variant"], v["price"], v["physical"], v["digital"]) for v in variants] == [
        (fid, "print", 12.0, True, False), (fid + ":num", "digital", 8.0, False, True), (fid + ":both", "both", 17.0, True, True)]
    assert variants[2]["name_fr"] == "Le grand portrait (18 × 24) · tirage + numérique"

    # "both" at its own price: the lab gets the print, the family the download
    item = {**_order(fid, 17.0)["items"][0], "format_id": fid + ":both"}
    oid = (await client.post("/api/portal/orders", json={**_order(fid, 17.0), "items": [item]})).json()["order_id"]
    assert (await client.post("/api/portal/orders", json={**_order(fid, 20.0), "items": [
        {**item, "unit_price": 20.0}]})).status_code == 400                   # the server owns the price
    with get_db() as conn:
        conn.execute("UPDATE orders SET payment_status='paid' WHERE id=?", (oid,))
        conn.commit()
    orders = (await client.get("/api/portal/orders", params={"code": DEMO_CODE})).json()["orders"]
    assert len(next(o for o in orders if o["id"] == oid)["downloads"]) == 1
    assert (await client.get(f"/api/admin/orders/{oid}", headers=admin_headers)).json()["detail"]["prints"] == 1
    z = zipfile.ZipFile(io.BytesIO((await client.get(f"/api/admin/orders/{oid}/lab.zip", headers=admin_headers)).content))
    assert [n.split("/")[-1].split("_", 2)[-1] for n in z.namelist() if not n.endswith(".pdf")] == ["18x24_x1.jpg"]
