"""The Cards tab explorer (2026-10-24): deleting a class that has cards, cut / copy / paste of photos and children,
downloading originals, and the school's own logo on its 10x15 sheet."""
import io
import uuid
import zipfile

from PIL import Image

from conftest import insert_order, item
from core.db import get_db
from services import photo_service
from test_sheet5_6_upload_cards import _class, _jpeg, _two_classes_and_siblings, _up, school  # noqa: F401 (fixture)


async def _cards(client, school):
    return {c["filename"]: c for c in (await client.get("/api/admin/cards", headers=school)).json()["cards"]}


async def _class_id(client, school, name):
    cls = (await client.get("/api/admin/classes", headers=school)).json()["classes"]
    return next(c["id"] for c in cls if c["class_name"] == name)


async def test_a_class_with_cards_is_deleted_after_confirmation_and_its_photos_go_to_the_trash(client, school):
    codes = await _two_classes_and_siblings(client, school)
    # b1 (2B) and a1 (3A) are siblings: once joined, deleting 2B must not take a1's family away.
    await client.post("/api/admin/families/merge", headers=school, json={"codes": [codes["a1.jpg"], codes["b1.jpg"]], "confirm": True})
    cid = await _class_id(client, school, "2B")
    refused = await client.delete(f"/api/admin/classes/{cid}", headers=school)
    assert refused.status_code == 409 and "confirm" in refused.json()["detail"]

    r = await client.delete(f"/api/admin/classes/{cid}", headers=school, params={"confirm": "true"})
    assert r.status_code == 200, r.text
    assert r.json()["photos_moved_to_trash"] == 2 and r.json()["codes_removed"] == 1      # b2's code; a1's family stays
    left = await _cards(client, school)
    assert set(left) == {"a1.jpg", "together.jpg"} and left["a1.jpg"]["code"] == codes["a1.jpg"]
    with get_db() as conn:
        assert conn.execute("SELECT 1 FROM families WHERE code=?", (codes["b2.jpg"],)).fetchone() is None
        assert conn.execute("SELECT 1 FROM students s JOIN families f ON f.code=s.family_code "
                            "WHERE f.school_id=? AND s.class_name='2B'", (school["X-School"],)).fetchone() is None
    sid = school["X-School"]
    assert any(e["kind"] == "class" and e["file_count"] == 2 for e in photo_service.list_trash(sid))
    assert not any(c["class_name"] == "2B" for c in (await client.get("/api/admin/classes", headers=school)).json()["classes"])
    ev = (await client.get("/api/admin/audit?action=class.delete", headers=school)).json()["events"]
    assert ev and ev[0]["details"]["files_to_trash"] == 2
    # the same name can be created and loaded again from scratch
    again = await _class(client, school, "2B")
    assert (await _up(client, school, again, "b1.jpg", _jpeg((11, 0, 0)))).json()["status"] == "uploaded"


async def test_a_class_whose_family_paid_is_never_deleted(client, school):
    codes = await _two_classes_and_siblings(client, school)
    insert_order(f"o-{uuid.uuid4().hex[:8]}", codes["b2.jpg"], school["X-School"], [item(photo="b2.jpg")], payment_status="paid")
    cid = await _class_id(client, school, "2B")
    r = await client.delete(f"/api/admin/classes/{cid}", headers=school, params={"confirm": "true"})
    assert r.status_code == 409 and "paid" in r.json()["detail"]
    assert set(await _cards(client, school)) >= {"b1.jpg", "b2.jpg"}


async def test_a_photo_is_cut_or_copied_from_a_child_to_another(client, school):
    await _two_classes_and_siblings(client, school)
    g = await _cards(client, school)
    b1, b2 = g["b1.jpg"], g["b2.jpg"]
    copy = await client.post("/api/admin/photos/transfer", headers=school,
                             json={"folder": b1["folder"], "filename": "b1.jpg", "target_folder": b2["folder"], "mode": "copy"})
    assert copy.status_code == 200 and copy.json() == {"code": b2["code"], "folder": b2["folder"], "filename": "b1.jpg"}

    async def by_folder():
        return {c["folder"]: c for c in (await client.get("/api/admin/cards", headers=school)).json()["cards"]}
    g = await by_folder()
    assert g[b1["folder"]]["photos"] == 1 and g[b2["folder"]]["photos"] == 2   # the source keeps its photo
    moved = await client.post("/api/admin/photos/transfer", headers=school,
                              json={"folder": b1["folder"], "filename": "b1.jpg", "target_folder": b2["folder"]})
    assert moved.status_code == 200 and moved.json()["filename"] == "b1_1.jpg"  # unique in the target family
    g = await by_folder()
    assert b1["folder"] not in g and g[b2["folder"]]["photos"] == 3           # no original left in the source
    bad = await client.post("/api/admin/photos/transfer", headers=school,
                            json={"folder": b1["folder"], "filename": "../x.jpg", "target_folder": b2["folder"]})
    assert bad.status_code == 400
    gone = await client.post("/api/admin/photos/transfer", headers=school,
                             json={"folder": "2B/Student 99", "filename": "b1.jpg", "target_folder": b2["folder"]})
    assert gone.status_code == 404
    ev = (await client.get("/api/admin/audit?action=photo.copy", headers=school)).json()["events"]
    assert ev and ev[0]["details"]["to"] == b2["folder"]


async def test_a_child_is_moved_to_another_class_and_keeps_its_code(client, school):
    await _two_classes_and_siblings(client, school)
    b2 = (await _cards(client, school))["b2.jpg"]
    r = await client.post("/api/admin/photos/child/move", headers=school, json={"folder": b2["folder"], "class_name": "3A"})
    assert r.status_code == 200 and r.json() == {"code": b2["code"], "folder": "3A/Student 2", "seq": 2}
    now = (await _cards(client, school))["b2.jpg"]
    assert now["code"] == b2["code"] and now["label"] == "3A · Student 2"
    fam = next(f for f in (await client.get("/api/admin/families", headers=school)).json()["families"] if f["code"] == b2["code"])
    assert fam["classes"] == ["3A"]
    same = await client.post("/api/admin/photos/child/move", headers=school, json={"folder": "3A/Student 2", "class_name": "3A"})
    assert same.status_code == 400
    sib = await client.post("/api/admin/photos/child/move", headers=school, json={"folder": "3A/Student 2", "class_name": "Fratries"})
    assert sib.status_code == 409


async def test_originals_of_a_child_or_a_class_download_as_a_zip(client, school):
    await _two_classes_and_siblings(client, school)
    b1 = (await _cards(client, school))["b1.jpg"]
    one = await client.get("/api/admin/photos/originals.zip", headers=school, params={"folder": b1["folder"]})
    assert one.status_code == 200 and zipfile.ZipFile(io.BytesIO(one.content)).namelist() == [f"{b1['folder']}/b1.jpg"]
    cls = await client.get("/api/admin/photos/originals.zip", headers=school, params={"class_name": "2B"})
    assert sorted(zipfile.ZipFile(io.BytesIO(cls.content)).namelist()) == ["2B/Student 1/b1.jpg", "2B/Student 2/b2.jpg"]
    assert (await client.get("/api/admin/photos/originals.zip", headers=school, params={"class_name": "nope"})).status_code == 404


async def test_the_school_logo_is_printed_on_its_sheets(client, school):
    await _two_classes_and_siblings(client, school)
    card_url = (await _cards(client, school))["b1.jpg"]["card_url"]
    before = (await client.get(card_url)).content
    assert (await client.get("/api/admin/school-crest.png", headers=school)).status_code == 404
    buf = io.BytesIO()
    Image.new("RGBA", (300, 300), (220, 40, 40, 255)).save(buf, "PNG")
    up = await client.post("/api/admin/school-crest", headers=school, files={"file": ("crest.png", buf.getvalue(), "image/png")})
    assert up.status_code == 200
    after = Image.open(io.BytesIO((await client.get(card_url)).content)).convert("RGB")
    assert (await client.get(card_url)).content != before
    # leaflet box 85,21 → 239,181 on 1135x1600: its centre on the 1200x1800 sheet is red
    assert after.getpixel((round(162 * 1200 / 1135), round(101 * 1800 / 1600))) == (220, 40, 40)
    assert (await client.post("/api/admin/school-crest", headers=school,
                              files={"file": ("x.png", b"not an image", "image/png")})).status_code == 400
    assert (await client.delete("/api/admin/school-crest", headers=school)).status_code == 200
    assert (await client.get(card_url)).content == before
