"""Classes typed in the back-office and family codes attached to them — the schools may not send names."""
import io
import zipfile

from PIL import Image


async def _new_school(client, admin_token, name):
    r = await client.post("/api/admin/schools", json={"name": name},
                          headers={"Authorization": f"Bearer {admin_token}"})
    assert r.status_code == 200, r.text
    sid = r.json()["school"]["id"]
    return {"Authorization": f"Bearer {admin_token}", "X-School": sid}


async def _add_classes(client, headers, *names, count=None):
    out = []
    for n in names:
        r = await client.post("/api/admin/classes", json={"name": n, "student_count": count}, headers=headers)
        assert r.status_code == 200, r.text
        out.append(r.json()["class"])
    return out


async def test_there_is_no_student_import_anymore(client, admin_headers):
    r = await client.post("/api/admin/students/import", json={"csv_text": "prenom;nom;classe\na;b;c"},
                          headers=admin_headers)
    assert r.status_code in (404, 405)


async def test_classes_are_created_listed_and_scoped_to_the_school(client, admin_token, admin_headers):
    headers = await _new_school(client, admin_token, "Classes Ecole")
    await _add_classes(client, headers, "CP A", "CE1 B", count=24)
    listed = (await client.get("/api/admin/classes", headers=headers)).json()["classes"]
    # school order, not alphabetical; the special Siblings folder comes last (brief sheet 5)
    assert [c["class_name"] for c in listed if c["kind"] == "class"] == ["CP A", "CE1 B"]
    assert [c["kind"] for c in listed][-1] == "siblings"
    assert listed[0]["student_count"] == 24 and listed[0]["families"] == 0
    other = (await client.get("/api/admin/classes", headers=admin_headers)).json()["classes"]
    assert "CP A" not in {c["class_name"] for c in other}


async def test_duplicate_class_is_rejected_and_role_is_required(client, admin_token):
    headers = await _new_school(client, admin_token, "Dup Classes")
    await _add_classes(client, headers, "CM1")
    assert (await client.post("/api/admin/classes", json={"name": " CM1 "}, headers=headers)).status_code == 409
    assert (await client.post("/api/admin/classes", json={"name": "CM2"})).status_code == 401


async def test_family_is_attached_to_existing_classes_only(client, admin_token):
    headers = await _new_school(client, admin_token, "Attach Ecole")
    await _add_classes(client, headers, "CE1", "CM2")
    unknown = await client.post("/api/admin/families", json={"classes": ["CE9"]}, headers=headers)
    assert unknown.status_code == 400 and "CE9" in unknown.json()["detail"]
    ok = await client.post("/api/admin/families", json={"classes": ["CE1", "CM2"], "email": "a@b.fr"}, headers=headers)
    assert ok.status_code == 200, ok.text
    fam = ok.json()["family"]
    assert fam["classes"] == ["CE1", "CM2"] and fam["is_sibling"] is True
    assert "family_name" not in fam and "students" not in fam              # no name anywhere

    listed = (await client.get("/api/admin/families?q=CM2", headers=headers)).json()
    assert listed["total"] == 1 and listed["families"][0]["code"] == fam["code"]


async def test_each_family_gets_its_own_code_even_in_the_same_class(client, admin_token):
    headers = await _new_school(client, admin_token, "Own Codes")
    await _add_classes(client, headers, "CE2")
    a = (await client.post("/api/admin/families", json={"classes": ["CE2"]}, headers=headers)).json()["family"]
    b = (await client.post("/api/admin/families", json={"classes": ["CE2"]}, headers=headers)).json()["family"]
    assert a["code"] != b["code"]


async def test_family_can_be_reattached_and_validates_email(client, admin_token):
    headers = await _new_school(client, admin_token, "Reattach Ecole")
    await _add_classes(client, headers, "CP", "CE1")
    fam = (await client.post("/api/admin/families", json={"classes": ["CP"]}, headers=headers)).json()["family"]
    r = await client.patch(f"/api/admin/families/{fam['code']}", json={"classes": ["CE1"], "email": "x@y.fr"},
                           headers=headers)
    assert r.status_code == 200 and r.json()["family"]["classes"] == ["CE1"]
    bad = await client.patch(f"/api/admin/families/{fam['code']}", json={"email": "nope"}, headers=headers)
    assert bad.status_code == 400
    assert (await client.patch("/api/admin/families/NOPE-000", json={"classes": ["CE1"]},
                               headers=headers)).status_code == 404


async def test_renaming_a_class_moves_its_families_and_deleting_needs_it_empty(client, admin_token):
    headers = await _new_school(client, admin_token, "Rename Ecole")
    cls = (await _add_classes(client, headers, "CP A"))[0]
    fam = (await client.post("/api/admin/families", json={"classes": ["CP A"]}, headers=headers)).json()["family"]

    assert (await client.delete(f"/api/admin/classes/{cls['id']}", headers=headers)).status_code == 409
    r = await client.patch(f"/api/admin/classes/{cls['id']}", json={"name": "CP 1"}, headers=headers)
    assert r.status_code == 200 and r.json()["class_name"] == "CP 1"
    listed = (await client.get("/api/admin/families", headers=headers)).json()["families"]
    assert listed[0]["code"] == fam["code"] and listed[0]["classes"] == ["CP 1"]

    await client.patch(f"/api/admin/families/{fam['code']}", json={"classes": ["CP 1"]}, headers=headers)
    other = (await _add_classes(client, headers, "CE1"))[0]
    assert (await client.delete(f"/api/admin/classes/{other['id']}", headers=headers)).status_code == 200


async def test_classes_of_another_school_cannot_be_touched(client, admin_token, admin_headers):
    headers = await _new_school(client, admin_token, "Isolated Classes")
    cls = (await _add_classes(client, headers, "CM2"))[0]
    assert (await client.patch(f"/api/admin/classes/{cls['id']}", json={"name": "X"},
                               headers=admin_headers)).status_code == 404
    assert (await client.delete(f"/api/admin/classes/{cls['id']}", headers=admin_headers)).status_code == 404


async def test_family_card_is_a_signed_10x15_png_with_no_name(client, admin_token):
    headers = await _new_school(client, admin_token, "Cards Ecole")
    await _add_classes(client, headers, "CE2")
    fam = (await client.post("/api/admin/families", json={"classes": ["CE2"]}, headers=headers)).json()["family"]
    listed = (await client.get("/api/admin/families", headers=headers)).json()["families"][0]
    assert listed["card_url"].startswith(f"/api/media/card/{headers['X-School']}/{fam['code']}.png?")

    r = await client.get(listed["card_url"] + "&lang=es")
    assert r.status_code == 200 and r.headers["content-type"] == "image/png"
    im = Image.open(io.BytesIO(r.content))
    assert im.size == (1200, 1800)
    assert round(im.info["dpi"][0]) == 305                      # 100 mm wide at 1:1 (10x15 cm)

    tampered = listed["card_url"].replace("sig=", "sig=0")
    assert (await client.get(tampered)).status_code == 403
    other = listed["card_url"].replace(headers["X-School"], "ecole-test")
    assert (await client.get(other)).status_code == 403          # signature is tied to the school


async def test_cards_zip_groups_by_class_and_requires_operator(client, admin_token):
    headers = await _new_school(client, admin_token, "Zip Ecole")
    await _add_classes(client, headers, "CP", "CE1")
    for cls in ("CP", "CP", "CE1"):
        await client.post("/api/admin/families", json={"classes": [cls]}, headers=headers)
    r = await client.get("/api/admin/cards.zip", headers=headers)
    assert r.status_code == 200 and r.headers["content-type"] == "application/zip"
    names = zipfile.ZipFile(io.BytesIO(r.content)).namelist()
    assert len(names) == 3 and all(n.endswith(".png") and "/" in n for n in names)
    assert (await client.get("/api/admin/cards.zip")).status_code == 401
    empty = await _new_school(client, admin_token, "Empty Zip Ecole")
    assert (await client.get("/api/admin/cards.zip", headers=empty)).status_code == 404


def test_card_shows_the_childs_photos_and_survives_long_class_names_and_unknown_language(tmp_path):
    from services import card_service
    photos = []
    for i, color in enumerate(((200, 90, 90), (90, 200, 90), (90, 90, 200), (200, 200, 90), (1, 1, 1))):
        p = tmp_path / f"p{i}.jpg"
        Image.new("RGB", (1600, 1200), color).save(p, "JPEG")
        photos.append(p)
    kw = dict(code="MAR-P8Y-D23", classes=["CM2 A très longue " * 4, "CE1"],
              school_name="École " + "Très Longue " * 6, portal_url="https://photos.example.com/")
    with_photos = card_service.render_card(**kw, lang="zz", photos=photos)
    without = card_service.render_card(**kw, lang="fr")
    assert with_photos.startswith(b"\x89PNG") and without.startswith(b"\x89PNG")
    assert with_photos != without
    broken = card_service.render_card(**kw, photos=[tmp_path / "missing.jpg"])   # a bad file never kills the sheet
    assert broken.startswith(b"\x89PNG")


def test_card_prints_the_order_deadline_in_red_in_the_family_language():
    from services import card_service
    assert card_service._date_text("2026-12-04", "fr") == "4 décembre 2026"
    assert card_service._date_text("2026-12-04", "es") == "4 de diciembre de 2026"
    assert card_service._date_text("2026-13-04", "fr") == card_service._date_text("", "fr") == ""
    kw = dict(code="MAR-P8Y-D23", classes=["CP A"], school_name="École", portal_url="https://photos.example.com")
    band = (0, round(1340 * card_service.SY), card_service.CARD_W, round(1430 * card_service.SY))

    def reds(png):
        crop = Image.open(io.BytesIO(png)).convert("RGB").crop(band)
        return sum(1 for r, g, b in crop.getdata() if r > 180 and g < 90 and b < 90)
    assert reds(card_service.render_card(**kw, deadline="2026-12-04")) > 500
    assert reds(card_service.render_card(**kw)) == 0            # no date: the line to write it by hand


async def test_setup_checklist_reports_progress(client, admin_headers):
    r = await client.get("/api/admin/setup", headers=admin_headers)
    assert r.status_code == 200
    body = r.json()
    ids = [s["id"] for s in body["steps"]]
    assert ids[0] == "school_name" and "stripe" in ids
    assert body["total"] == len(ids) and 0 <= body["done"] <= body["total"]


async def test_deleting_a_family_frees_its_class_and_never_touches_paid_orders(client, admin_token):
    from core.db import get_db
    from conftest import insert_order, item
    import uuid
    headers = await _new_school(client, admin_token, "Delete Family Ecole")
    cls = (await _add_classes(client, headers, "3A"))[0]
    a = (await client.post("/api/admin/families", json={"classes": ["3A"]}, headers=headers)).json()["family"]
    b = (await client.post("/api/admin/families", json={"classes": ["3A"]}, headers=headers)).json()["family"]
    sid = headers["X-School"]
    insert_order(str(uuid.uuid4()), b["code"], sid, [item()], payment_status="paid")
    insert_order(str(uuid.uuid4()), a["code"], sid, [item()], payment_status="unpaid")

    # the class is held by its codes
    assert (await client.delete(f"/api/admin/classes/{cls['id']}", headers=headers)).status_code == 409
    # a code with a paid sale stays; one with only unpaid/expired orders can go
    assert (await client.delete(f"/api/admin/families/{b['code']}", headers=headers)).status_code == 409
    gone = await client.delete(f"/api/admin/families/{a['code']}", headers=headers)
    assert gone.status_code == 200 and gone.json()["success"] is True
    with get_db() as conn:
        assert conn.execute("SELECT 1 FROM families WHERE code=?", (a["code"],)).fetchone() is None
        assert conn.execute("SELECT 1 FROM orders WHERE family_code=?", (a["code"],)).fetchone() is None
    assert (await client.delete(f"/api/admin/families/{a['code']}", headers=headers)).status_code == 404


async def test_a_family_of_another_school_cannot_be_deleted(client, admin_token, admin_headers):
    headers = await _new_school(client, admin_token, "Other Delete Ecole")
    await _add_classes(client, headers, "CM1")
    fam = (await client.post("/api/admin/families", json={"classes": ["CM1"]}, headers=headers)).json()["family"]
    assert (await client.delete(f"/api/admin/families/{fam['code']}", headers=admin_headers)).status_code == 404
    assert (await client.delete(f"/api/admin/families/{fam['code']}")).status_code == 401


async def test_sheets_come_out_in_the_order_the_children_were_photographed(client, admin_token):
    import io
    import time
    import zipfile
    headers = await _new_school(client, admin_token, "Order Ecole")
    await _add_classes(client, headers, "3A")
    codes = []
    for _ in range(3):
        codes.append((await client.post("/api/admin/families", json={"classes": ["3A"]}, headers=headers))
                     .json()["family"]["code"])
        time.sleep(0.02)
    listed = [f["code"] for f in (await client.get("/api/admin/families", headers=headers)).json()["families"]]
    assert listed == codes
    names = sorted(zipfile.ZipFile(io.BytesIO((await client.get("/api/admin/cards.zip", headers=headers)).content)).namelist())
    assert [n.split("/")[1].split("_")[0] for n in names] == ["001", "002", "003"]
    assert [n.split("_", 1)[1].removesuffix(".png") for n in names] == codes


def test_card_layout_holds_with_the_longest_texts_and_shows_the_students_in_the_family_language(tmp_path, caplog):
    import io
    from services import card_service
    kw = dict(code="MAR-P8Y-D23", classes=["CM2 A"], school_name="École élémentaire privée Sainte-Marie des Batignolles Paris",
              portal_url="https://photos.example.com",
              students=["CE1 B · Student 12", "CM2 A · Student 7", "CP A · Student 3"])
    photos = []
    for i in range(4):
        p = tmp_path / f"p{i}.jpg"
        Image.new("RGB", (1600, 1200), (60 * i, 90, 160)).save(p, "JPEG")
        photos.append(p)
    caplog.set_level("WARNING", logger="meeconic.card")
    for lang in ("fr", "en", "es"):
        png = card_service.render_card(**kw, lang=lang, photos=photos)
        assert Image.open(io.BytesIO(png)).size == (card_service.CARD_W, card_service.CARD_H)
    assert "overlap" not in caplog.text                      # chips never reach the first step
    assert card_service.TEXTS["fr"]["student"] == "Élève" and card_service.TEXTS["es"]["student"] == "Alumno"
