"""Brief sheet 7: order details, HD folder for the lab, recap sheet PDF, internal "Done" marker."""
import io
import json
import uuid
import zipfile

import pytest
from PIL import Image

from conftest import insert_order, item
from core.db import get_db


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 2B (two validated cards) and a sibling photo; returns codes by file name."""
    h = {"Authorization": f"Bearer {admin_token}"}
    sid = (await client.post("/api/admin/schools", json={"name": f"Orders {uuid.uuid4().hex[:6]}"}, headers=h)).json()["school"]["id"]
    headers = {**h, "X-School": sid}
    cid = (await client.post("/api/admin/classes", json={"name": "2B"}, headers=headers)).json()["class"]["id"]
    for n, color in (("DSC_1.jpg", (1, 1, 1)), ("DSC_2.jpg", (2, 2, 2))):
        await client.post(f"/api/admin/classes/{cid}/photos", headers=headers, files={"file": (n, _jpeg(color), "image/jpeg")})
    await client.post(f"/api/admin/classes/{cid}/validate", headers=headers)
    classes = (await client.get("/api/admin/classes", headers=headers)).json()["classes"]
    sib = next(c["id"] for c in classes if c["kind"] == "siblings")
    await client.post(f"/api/admin/classes/{sib}/photos", headers=headers, files={"file": ("TOGETHER.jpg", _jpeg((3, 3, 3)), "image/jpeg")})
    cards = (await client.get("/api/admin/cards", headers=headers)).json()["cards"]
    return {"h": headers, "sid": sid, "codes": {c["filename"]: c["code"] for c in cards}}


def _line(photo, name, qty=1, price=9.0, kind="print", fid="print-13x18"):
    it = item(fmt=fid, photo=photo, price=price, qty=qty, label=name)
    it.update(kind=kind, physical=kind in ("print", "pack"), digital=kind in ("digital", "pack"),
              format_names={"fr": name, "en": name, "es": name})
    return it


async def _merged_order(client, shop):
    """The family of DSC_1 + DSC_2 + the sibling photo, one order with prints in two formats and a digital file."""
    c = shop["codes"]
    r = await client.post("/api/admin/families/merge", headers=shop["h"],
                          json={"codes": [c["DSC_1.jpg"], c["DSC_2.jpg"], c["TOGETHER.jpg"]], "confirm": True})
    assert r.status_code == 200, r.text
    oid = str(uuid.uuid4())
    insert_order(oid, c["DSC_1.jpg"], shop["sid"], [
        _line("DSC_1.jpg", "Tirage papier 13×18", qty=2),
        _line("DSC_2.jpg", "Tirage papier 15×21", qty=1, price=12.0, fid="print-15x21"),
        _line("TOGETHER.jpg", "Tirage papier 13×18", qty=1),
        _line("DSC_1.jpg", "Photo numérique", qty=1, price=5.0, kind="digital", fid="digital"),
    ])
    return oid, c["DSC_1.jpg"]


async def test_the_order_opens_with_every_photo_format_and_print_count(client, shop):
    oid, code = await _merged_order(client, shop)
    r = await client.get(f"/api/admin/orders/{oid}", headers=shop["h"])
    assert r.status_code == 200, r.text
    d = r.json()["detail"]
    assert d["prints"] == 4 and d["photos"] == 3                 # 2 + 1 + 1 prints; the digital file is not printed
    by = [(l["photo_filename"], l["name"], l["quantity"], l["card"]) for l in d["lines"]]
    assert ("DSC_1.jpg", "Tirage papier 13×18", 2, "2B · Student 1") in by
    assert ("TOGETHER.jpg", "Tirage papier 13×18", 1, "Fratries · Photo 1") in by
    assert all(l["thumb_url"] and not l["missing"] for l in d["lines"])
    assert (await client.get(d["lines"][0]["thumb_url"])).status_code == 200
    assert r.json()["short_id"] == oid[:8].upper() and r.json()["validated_at"] is None
    assert (await client.get(f"/api/admin/orders/{oid}", headers={**shop["h"], "X-School": "ecole-test"})).status_code == 404


async def test_the_lab_folder_has_one_readable_file_per_print_line(client, shop):
    oid, code = await _merged_order(client, shop)
    r = await client.get(f"/api/admin/orders/{oid}/lab.zip", headers=shop["h"])
    assert r.status_code == 200 and r.headers["content-type"] == "application/zip"
    z = zipfile.ZipFile(io.BytesIO(r.content))
    folder = f"order-{oid[:8].upper()}"
    recap = f"{folder}/recap-{oid[:8].upper()}.pdf"                   # the complete order: photos + recap sheet
    assert sorted(z.namelist()) == sorted([
        f"{folder}/{code}_2B_13x18_x2.jpg", f"{folder}/{code}_2B_15x21_x1.jpg", f"{folder}/{code}_Fratries_13x18_x1.jpg",
        recap])
    assert z.read(recap).startswith(b"%PDF")
    # the files are the HD originals, byte for byte
    assert Image.open(io.BytesIO(z.read(f"{folder}/{code}_2B_13x18_x2.jpg"))).size == (64, 48)
    ev = (await client.get("/api/admin/audit?action=order.download", headers=shop["h"])).json()["events"]
    assert ev and ev[0]["details"]["files"] == 3


async def test_the_same_photo_twice_in_the_same_format_gets_two_distinct_names(client, shop):
    c = shop["codes"]["DSC_1.jpg"]
    oid = str(uuid.uuid4())
    insert_order(oid, c, shop["sid"], [_line("DSC_1.jpg", "Tirage 13×18", qty=1), _line("DSC_1.jpg", "Tirage 13×18", qty=1)])
    z = zipfile.ZipFile(io.BytesIO((await client.get(f"/api/admin/orders/{oid}/lab.zip", headers=shop["h"])).content))
    assert len({n for n in z.namelist() if not n.endswith(".pdf")}) == 2


async def test_an_unpaid_or_cancelled_order_is_not_prepared_and_a_digital_only_one_has_nothing_to_send(client, shop):
    c = shop["codes"]["DSC_1.jpg"]
    unpaid = str(uuid.uuid4())
    insert_order(unpaid, c, shop["sid"], [_line("DSC_1.jpg", "Tirage 13×18")], payment_status="unpaid")
    assert (await client.get(f"/api/admin/orders/{unpaid}/lab.zip", headers=shop["h"])).status_code == 409
    assert (await client.post(f"/api/admin/orders/{unpaid}/validate", headers=shop["h"])).status_code == 409
    digital = str(uuid.uuid4())
    insert_order(digital, c, shop["sid"], [_line("DSC_1.jpg", "Photo numérique", kind="digital", fid="digital")])
    assert (await client.get(f"/api/admin/orders/{digital}/lab.zip", headers=shop["h"])).status_code == 404


async def test_a_photo_deleted_since_is_reported_missing_not_fatal(client, shop):
    from services import photo_service
    oid, code = await _merged_order(client, shop)
    assert photo_service.delete_child_photos(shop["sid"], "2B/Student 2") == 1
    d = (await client.get(f"/api/admin/orders/{oid}", headers=shop["h"])).json()["detail"]
    assert [l["photo_filename"] for l in d["lines"] if l["missing"]] == ["DSC_2.jpg"]
    z = await client.get(f"/api/admin/orders/{oid}/lab.zip", headers=shop["h"])
    assert z.status_code == 200 and z.headers["x-missing-files"] == "1"
    assert len([n for n in zipfile.ZipFile(io.BytesIO(z.content)).namelist() if not n.endswith(".pdf")]) == 2   # the rest still goes
    ev = (await client.get("/api/admin/audit?action=order.download", headers=shop["h"])).json()["events"]
    assert ev[0]["details"]["missing"] == ["DSC_2.jpg"]


async def test_the_recap_sheet_is_a_pdf_with_only_the_print_lines(client, shop):
    oid, code = await _merged_order(client, shop)
    r = await client.get(f"/api/admin/orders/{oid}/recap.pdf", headers=shop["h"])
    assert r.status_code == 200 and r.headers["content-type"] == "application/pdf" and r.content.startswith(b"%PDF")
    for lang in ("en", "es"):
        assert (await client.get(f"/api/admin/orders/{oid}/recap.pdf", headers=shop["h"], params={"lang": lang})).status_code == 200


def test_the_recap_sheet_paginates_and_counts_the_prints():
    from services import order_service
    row = {"id": str(uuid.uuid4()), "family_code": "235-ABC-DEF"}
    ls = [{"physical": True, "quantity": 2, "class_name": "2B", "name": "Tirage 13×18"} for _ in range(45)]
    pdf = order_service.recap_pdf("Ecole Test", row, ls, ["2B"])
    assert pdf.count(b"/Type /Page\n") + pdf.count(b"/Type /Page ") + pdf.count(b"/Type/Page") >= 3     # 20 rows a page
    assert order_service.recap_pdf("Ecole Test", row, [], []).startswith(b"%PDF")


def test_format_tokens_read_like_the_lab_expects():
    from services.order_service import format_token
    assert format_token("Tirage papier 13×18") == "13x18"
    assert format_token("Poster 30 x 45 cm") == "30x45"
    assert format_token("Porte-clés photo métal") == "Porte-cles-photo-metal"
    assert format_token("") == "product"


async def test_validating_an_order_is_an_internal_marker_that_sends_no_e_mail(client, shop, monkeypatch):
    from services import email_service
    sent = []

    async def spy(*a, **k):
        sent.append(a)
        return True
    monkeypatch.setattr(email_service, "send_order_printed", spy)
    monkeypatch.setattr(email_service, "send_order_confirmation", spy)
    oid, code = await _merged_order(client, shop)
    v = await client.post(f"/api/admin/orders/{oid}/validate", headers=shop["h"])
    assert v.status_code == 200 and v.json()["validated_at"]
    assert sent == []                                                          # no e-mail, ever, from this marker
    with get_db() as conn:
        row = conn.execute("SELECT batch_status, printed_notified_at, validated_by FROM orders WHERE id=?", (oid,)).fetchone()
    assert row["batch_status"] == "to_print" and row["printed_notified_at"] is None and row["validated_by"] == "admin"
    # listed as Done, filterable, and reversible
    done = (await client.get("/api/admin/orders", headers=shop["h"], params={"validated": "done"})).json()["orders"]
    todo = (await client.get("/api/admin/orders", headers=shop["h"], params={"validated": "todo"})).json()["orders"]
    assert [o["id"] for o in done] == [oid] and todo == []
    assert (await client.delete(f"/api/admin/orders/{oid}/validate", headers=shop["h"])).json()["validated_at"] is None
    assert [o["id"] for o in (await client.get("/api/admin/orders", headers=shop["h"], params={"validated": "todo"})).json()["orders"]] == [oid]
    ev = (await client.get("/api/admin/audit?action=order.", headers=shop["h"])).json()["events"]
    assert {"order.validate", "order.unvalidate"} <= {e["action"] for e in ev}


async def test_the_printed_step_still_tells_the_family_once_independently_of_validation(client, shop, monkeypatch):
    from services import email_service
    sent = []

    async def spy(to, *a, **k):
        sent.append(to)
        return True
    monkeypatch.setattr(email_service, "send_order_printed", spy)
    oid, code = await _merged_order(client, shop)
    await client.post(f"/api/admin/orders/{oid}/validate", headers=shop["h"])
    r = await client.patch(f"/api/admin/orders/{oid}", headers=shop["h"], json={"batch_status": "printed"})
    assert r.json()["notified"] is True and sent == ["client@example.com"]


async def test_the_operator_prepares_orders_too(client, shop, operator_headers):
    oid, code = await _merged_order(client, shop)
    mine = {**operator_headers, "X-School": shop["sid"]}
    for url in (f"/api/admin/orders/{oid}", f"/api/admin/orders/{oid}/lab.zip", f"/api/admin/orders/{oid}/recap.pdf"):
        assert (await client.get(url, headers=mine)).status_code == 200, url
    assert (await client.post(f"/api/admin/orders/{oid}/validate", headers=mine)).status_code == 200
    with get_db() as conn:
        assert conn.execute("SELECT validated_by FROM orders WHERE id=?", (oid,)).fetchone()["validated_by"] == "operator"


async def test_directors_cannot_open_orders(client, shop, director_headers):
    oid, code = await _merged_order(client, shop)
    for method, url in (("GET", f"/api/admin/orders/{oid}"), ("POST", f"/api/admin/orders/{oid}/validate")):
        assert (await client.request(method, url, headers=director_headers)).status_code in (401, 403)
