"""One list of products for the school (brief 2026-10-21, sheet 3): picture, price, offered, order, translation."""
import io

import pytest
from PIL import Image

from conftest import DEMO_CODE, SCHOOL
from core.db import get_db
from services import format_service, translate_service


def _png(size=(300, 200), color=(10, 120, 200)) -> bytes:
    buf = io.BytesIO()
    Image.new("RGB", size, color).save(buf, "PNG")
    return buf.getvalue()


@pytest.fixture(autouse=True)
def _fake_translation(monkeypatch):
    """No network in the tests: a fake provider that marks what it did."""
    monkeypatch.setattr(translate_service, "_mymemory", lambda texts, lang: [f"[{lang}] {t}" for t in texts])
    translate_service._cache.clear()


async def _create(client, headers, **over):
    body = {"name_fr": "Porte-clés", "kind": "print", "price": 6.5}
    body.update(over)
    r = await client.post("/api/admin/formats", json=body, headers=headers)
    assert r.status_code == 200, r.text
    return r.json()["format"]


def _order(format_id, price, qty=1, **over):
    body = {
        "family_code": DEMO_CODE, "class_name": "CE1 A", "customer_email": "p@example.com",
        "items": [{"photo_filename": "portrait.jpg", "format_id": format_id, "format_label": "Porte-clés",
                   "quantity": qty, "unit_price": price, "is_magic": False}],
        "total": price * qty,
    }
    body.update(over)
    return body


async def test_a_product_is_typed_in_french_and_translated_by_itself(client, admin_headers):
    p = await _create(client, admin_headers, name_fr="Porte-clés photo", sub_fr="Métal, 3,5 × 4,5 cm")
    assert p["name_en"] == "[en] Porte-clés photo" and p["name_es"] == "[es] Porte-clés photo"
    assert p["sub_en"] == "[en] Métal, 3,5 × 4,5 cm" and "translation_unavailable" not in p
    assert p["kind"] == "print" and p["active"] is True and p["image_url"] is None


async def test_what_the_admin_typed_in_english_is_not_overwritten(client, admin_headers):
    p = await _create(client, admin_headers, name_fr="Aimant", name_en="Fridge magnet")
    assert p["name_en"] == "Fridge magnet" and p["name_es"] == "[es] Aimant"


async def test_without_a_translation_service_the_product_is_saved_in_french(client, admin_headers, monkeypatch):
    def down(texts, lang):
        raise TimeoutError("no network")
    monkeypatch.setattr(translate_service, "_mymemory", down)
    translate_service._cache.clear()
    p = await _create(client, admin_headers, name_fr="Tasse photo")
    assert p["translation_unavailable"] is True
    assert p["name_en"] == "Tasse photo" and p["name_es"] == "Tasse photo"     # shown in French
    gallery = (await client.get("/api/portal/photos", params={"code": DEMO_CODE})).json()
    assert next(f for f in gallery["formats"] if f["format_id"] == p["format_id"])["name_fr"] == "Tasse photo"


async def test_the_translate_endpoint_fills_the_form(client, admin_headers):
    r = await client.post("/api/admin/translate", json={"texts": ["Tirage 20×30", ""]}, headers=admin_headers)
    assert r.json() == {"available": True, "en": ["[en] Tirage 20×30", ""], "es": ["[es] Tirage 20×30", ""]}


async def test_product_image_lifecycle(client, admin_headers):
    p = await _create(client, admin_headers)
    up = await client.post(f"/api/admin/formats/{p['id']}/image", headers=admin_headers,
                           files={"file": ("x.png", _png(), "image/png")})
    assert up.status_code == 200, up.text
    url = up.json()["format"]["image_url"]
    assert url.startswith(f"/api/portal/format-image/{SCHOOL}/{p['id']}.webp")
    img = await client.get(url)
    assert img.status_code == 200 and Image.open(io.BytesIO(img.content)).format == "WEBP"
    gallery = (await client.get("/api/portal/photos", params={"code": DEMO_CODE})).json()
    assert next(f for f in gallery["formats"] if f["format_id"] == p["format_id"])["image_url"] == url
    await client.patch(f"/api/admin/formats/{p['id']}", json={"active": False}, headers=admin_headers)
    assert (await client.get(url)).status_code == 404            # a product that is not offered has no public picture
    # ... but Settings still shows it (2026-11-22: broken image in the Product tab), through a signed link only.
    mine = next(f for f in (await client.get("/api/admin/formats", headers=admin_headers)).json()["formats"] if f["id"] == p["id"])
    assert (await client.get(mine["image_admin_url"])).status_code == 200
    assert (await client.get(mine["image_admin_url"].replace("sig=", "sig=0"))).status_code == 404
    assert "image_admin_url" not in gallery["formats"][0]
    assert (await client.delete(f"/api/admin/formats/{p['id']}", headers=admin_headers)).status_code == 200


async def test_image_upload_rejects_non_images_and_other_schools(client, admin_headers, other_admin_headers):
    p = await _create(client, admin_headers, name_fr="Mug")
    bad = await client.post(f"/api/admin/formats/{p['id']}/image", headers=admin_headers,
                            files={"file": ("x.png", b"<svg onload=alert(1)/>", "image/png")})
    assert bad.status_code == 400
    foreign = await client.post(f"/api/admin/formats/{p['id']}/image", headers=other_admin_headers,
                                files={"file": ("x.png", _png(), "image/png")})
    assert foreign.status_code == 404
    assert (await client.delete(f"/api/admin/formats/{p['id']}", headers=other_admin_headers)).status_code == 404
    await client.delete(f"/api/admin/formats/{p['id']}", headers=admin_headers)


async def test_products_are_reordered_with_one_call(client, admin_headers):
    a, b = await _create(client, admin_headers, name_fr="A-ordre"), await _create(client, admin_headers, name_fr="B-ordre")
    ids = [f["id"] for f in (await client.get("/api/admin/formats", headers=admin_headers)).json()["formats"]]
    swapped = [b["id"], a["id"]] + [i for i in ids if i not in (a["id"], b["id"])]
    r = await client.put("/api/admin/formats-order", json={"ids": swapped}, headers=admin_headers)
    assert [f["id"] for f in r.json()["formats"]][:2] == [b["id"], a["id"]]
    assert (await client.put("/api/admin/formats-order", json={"ids": [999999]}, headers=admin_headers)).status_code == 400
    for p in (a, b):
        await client.delete(f"/api/admin/formats/{p['id']}", headers=admin_headers)


async def test_classic_and_ai_photos_share_the_same_products_and_prices(client, admin_headers):
    """The 'for AI photos' flag is gone: the magic built-ins are hidden, one list serves both kinds of photo."""
    fmts = (await client.get("/api/admin/formats", headers=admin_headers)).json()["formats"]
    assert not any(f["format_id"].startswith("magic-") for f in fmts)
    portal = (await client.get("/api/portal/photos", params={"code": DEMO_CODE})).json()
    assert not any(f["format_id"].startswith("magic-") for f in portal["formats"]) and "products" not in portal
    p = await _create(client, admin_headers, name_fr="Tirage 13×18", price=8)
    r = await client.post("/api/portal/orders", json=_order(p["format_id"], 8.0))
    assert r.status_code == 200, r.text
    # an AI photo is ordered with the very same product and price; a classic photo cannot claim to be one
    assert (await client.post("/api/portal/orders", json=_order(p["format_id"], 8.0, items=[
        {"photo_filename": "portrait.jpg", "format_id": p["format_id"], "format_label": "x", "quantity": 1,
         "unit_price": 8.0, "is_magic": True}]))).status_code == 400
    await client.delete(f"/api/admin/formats/{p['id']}", headers=admin_headers)


async def test_the_server_price_wins_and_a_hidden_or_foreign_product_cannot_be_ordered(client, admin_headers, other_admin_headers):
    p = await _create(client, admin_headers, name_fr="Tasse", price=12)
    hidden = await _create(client, admin_headers, name_fr="Caché", price=3, active=False)
    theirs = await _create(client, other_admin_headers, name_fr="Autre", price=5)
    assert (await client.post("/api/portal/orders", json=_order(p["format_id"], 12.0, qty=2))).status_code == 200
    assert (await client.post("/api/portal/orders", json=_order(p["format_id"], 1.0))).status_code == 400
    assert (await client.post("/api/portal/orders", json=_order(hidden["format_id"], 3.0))).status_code == 400
    assert (await client.post("/api/portal/orders", json=_order(theirs["format_id"], 5.0))).status_code == 400
    assert (await client.post("/api/portal/orders", json=_order("product-99999", 1.0))).status_code == 400
    for h, f in ((admin_headers, p), (admin_headers, hidden), (other_admin_headers, theirs)):
        await client.delete(f"/api/admin/formats/{f['id']}", headers=h)


async def test_the_operator_reads_the_products_but_cannot_change_them(client, operator_headers, admin_headers):
    p = await _create(client, admin_headers, name_fr="Lecture seule")
    assert any(f["id"] == p["id"] for f in (await client.get("/api/admin/formats", headers=operator_headers)).json()["formats"])
    for method, url, body in (("POST", "/api/admin/formats", {"name_fr": "X", "kind": "print", "price": 1}),
                              ("PATCH", f"/api/admin/formats/{p['id']}", {"price": 1}),
                              ("DELETE", f"/api/admin/formats/{p['id']}", None),
                              ("PUT", "/api/admin/formats-order", {"ids": [p["id"]]}),
                              ("POST", "/api/admin/translate", {"texts": ["x"]})):
        assert (await client.request(method, url, json=body, headers=operator_headers)).status_code == 403, url
    await client.delete(f"/api/admin/formats/{p['id']}", headers=admin_headers)


async def test_products_of_the_old_catalogue_are_merged_once_with_their_picture(client, admin_headers):
    from core import config
    legacy_img = config.PRODUCTS_DIR / SCHOOL / "777.webp"
    legacy_img.parent.mkdir(parents=True, exist_ok=True)
    Image.new("RGB", (40, 40), (1, 2, 3)).save(legacy_img, "WEBP")
    with get_db() as conn:
        conn.execute(
            "INSERT INTO school_products (id, school_id, name_fr, name_en, name_es, price, physical, active, has_image, "
            "sort_order, created_at) VALUES (777,?,?,?,?,?,1,1,1,0,'2026-10-01T00:00:00')",
            (SCHOOL, "Ancien porte-clés", "Old key ring", "", 6.0))
        conn.commit()
    assert format_service.migrate_legacy_products() == 1
    assert format_service.migrate_legacy_products() == 0                  # once only
    fmts = (await client.get("/api/admin/formats", headers=admin_headers)).json()["formats"]
    moved = next(f for f in fmts if f["name_fr"] == "Ancien porte-clés")
    assert moved["price"] == 6.0 and moved["name_en"] == "Old key ring" and moved["image_url"]
    assert (await client.get(moved["image_url"])).status_code == 200
    await client.delete(f"/api/admin/formats/{moved['id']}", headers=admin_headers)
    with get_db() as conn:
        conn.execute("DELETE FROM school_products WHERE id=777")
        conn.commit()
