"""Brief sheets 5 and 6: manual loading class by class, the Siblings folder, merge with confirmation and undo."""
import io
import uuid

import pytest
from PIL import Image

from conftest import OTHER_SCHOOL, SCHOOL
from core.db import get_db
from services import photo_service, upload_service


def _jpeg(color=(10, 90, 160), size=(64, 48)) -> bytes:
    buf = io.BytesIO()
    Image.new("RGB", size, color).save(buf, "JPEG")
    return buf.getvalue()


@pytest.fixture
async def school(client, admin_token):
    """A fresh school with the operator signed in."""
    h = {"Authorization": f"Bearer {admin_token}"}
    sid = (await client.post("/api/admin/schools", json={"name": f"Upload {uuid.uuid4().hex[:6]}"}, headers=h)).json()["school"]["id"]
    return {**h, "X-School": sid}


async def _class(client, headers, name):
    r = await client.post("/api/admin/classes", json={"name": name}, headers=headers)
    assert r.status_code == 200, r.text
    return r.json()["class"]["id"]


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


async def _up(client, headers, class_id, name, data=None, content_type="image/jpeg"):
    return await client.post(f"/api/admin/classes/{class_id}/photos", headers=headers,
                             files={"file": (name, data if data is not None else _jpeg(), content_type)})


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


async def test_a_class_goes_from_empty_to_in_progress_to_validated(client, school):
    cid = await _class(client, school, "3A")
    assert (await _status(client, school, "3A"))["status"] == "empty"
    for i, color in enumerate(((1, 1, 1), (2, 2, 2), (3, 3, 3)), start=1):
        r = await _up(client, school, cid, f"DSC_{i:04d}.jpg", _jpeg(color))
        assert r.status_code == 200 and r.json() == {"status": "uploaded", "filename": f"DSC_{i:04d}.jpg",
                                                      "upload_id": r.json()["upload_id"], "state": "staged"}
    st = await _status(client, school, "3A")
    assert st["status"] == "in_progress" and st["photos"] == 3 and st["staged"] == 3
    # nothing is a card yet: no family, no folder, nothing sold
    assert (await client.get("/api/admin/cards", headers=school)).json()["cards"] == []

    v = await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    assert v.status_code == 200 and v.json()["cards"] == 3 and v.json()["validated"] is True
    assert (await _status(client, school, "3A"))["status"] == "validated"
    cards = (await client.get("/api/admin/cards", headers=school, params={"class_name": "3A"})).json()["cards"]
    # numbered in file-name order, labelled by class and number, never a name
    assert [(c["label"], c["filename"]) for c in cards] == [
        ("3A · Student 1", "DSC_0001.jpg"), ("3A · Student 2", "DSC_0002.jpg"), ("3A · Student 3", "DSC_0003.jpg")]
    assert len({c["code"] for c in cards}) == 3 and all(c["state"] == "unlinked" for c in cards)
    prefix = (await client.get("/api/admin/settings", headers=school)).json()["settings"]["qr_code_prefix"]
    assert all(c["code"].startswith(prefix + "-") for c in cards)


async def test_files_are_numbered_naturally_not_alphabetically(client, school):
    cid = await _class(client, school, "4B")
    for i, n in enumerate((10, 2, 1)):
        await _up(client, school, cid, f"IMG_{n}.jpg", _jpeg((i * 40, 0, 0)))
    await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    cards = (await client.get("/api/admin/cards", headers=school, params={"class_name": "4B"})).json()["cards"]
    assert [c["filename"] for c in cards] == ["IMG_1.jpg", "IMG_2.jpg", "IMG_10.jpg"]


async def test_a_duplicate_is_ignored_and_a_bad_file_is_refused_with_its_reason(client, school):
    cid = await _class(client, school, "5C")
    assert (await _up(client, school, cid, "a.jpg", _jpeg((9, 9, 9)))).json()["status"] == "uploaded"
    dup = await _up(client, school, cid, "copy-of-a.jpg", _jpeg((9, 9, 9)))
    assert dup.status_code == 200 and dup.json() == {"status": "duplicate", "filename": "copy-of-a.jpg", "same_as": "a.jpg"}
    assert (await _status(client, school, "5C"))["photos"] == 1
    for name, data, ctype, text in (("notes.txt", b"hello", "text/plain", "Not a photo"),
                                    ("fake.jpg", b"<html>not an image</html>", "image/jpeg", "readable picture"),
                                    ("empty.jpg", b"", "image/jpeg", "Empty")):
        r = await _up(client, school, cid, name, data, ctype)
        assert r.status_code == 422 and text in r.json()["detail"], (name, r.text)
    assert (await _status(client, school, "5C"))["photos"] == 1             # the bad ones left nothing behind


async def test_a_file_that_is_too_large_is_refused(client, school, monkeypatch):
    from core import config
    monkeypatch.setattr(config, "UPLOAD_MAX_MB", 0)
    cid = await _class(client, school, "6D")
    r = await _up(client, school, cid, "big.jpg")
    assert r.status_code == 413 and "too large" in r.json()["detail"]


async def test_a_waiting_photo_can_be_removed_before_validation_and_the_same_file_loaded_again(client, school):
    cid = await _class(client, school, "2E")
    up = (await _up(client, school, cid, "x.jpg", _jpeg((7, 7, 7)))).json()
    waiting = (await client.get(f"/api/admin/classes/{cid}/photos", headers=school)).json()["waiting"]
    assert [w["filename"] for w in waiting] == ["x.jpg"]
    assert (await client.delete(f"/api/admin/classes/{cid}/photos/{up['upload_id']}", headers=school)).status_code == 200
    assert (await _up(client, school, cid, "x.jpg", _jpeg((7, 7, 7)))).json()["status"] == "uploaded"
    assert (await client.delete(f"/api/admin/classes/{cid}/photos/999999", headers=school)).status_code == 404
    ev = (await client.get("/api/admin/audit?action=class.photo_removed", headers=school)).json()["events"]
    assert ev and ev[0]["details"]["filename"] == "x.jpg"


async def test_a_class_with_waiting_photos_cannot_be_deleted_and_an_empty_one_cannot_be_validated(client, school):
    cid = await _class(client, school, "1F")
    assert (await client.post(f"/api/admin/classes/{cid}/validate", headers=school)).status_code == 409
    await _up(client, school, cid, "a.jpg")
    assert (await client.delete(f"/api/admin/classes/{cid}", headers=school)).status_code == 409


async def test_a_photo_added_after_validation_becomes_the_next_card_and_is_journaled(client, school):
    cid = await _class(client, school, "3G")
    await _up(client, school, cid, "a.jpg", _jpeg((1, 2, 3)))
    await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    late = await _up(client, school, cid, "absent-pupil.jpg", _jpeg((4, 5, 6)))
    assert late.status_code == 200 and late.json()["state"] == "filed"
    assert late.json()["label"] == "3G · Student 2" and late.json()["code"]
    cards = (await client.get("/api/admin/cards", headers=school, params={"class_name": "3G"})).json()["cards"]
    assert [c["label"] for c in cards] == ["3G · Student 1", "3G · Student 2"]
    ev = (await client.get("/api/admin/audit?action=class.photo_added", headers=school)).json()["events"]
    assert ev and ev[0]["details"]["label"] == "3G · Student 2"
    # a duplicate of an already filed photo is still caught
    assert (await _up(client, school, cid, "again.jpg", _jpeg((1, 2, 3)))).json()["status"] == "duplicate"


async def test_a_deleted_card_photo_can_be_loaded_again(client, school):
    cid = await _class(client, school, "3H")
    await _up(client, school, cid, "a.jpg", _jpeg((8, 8, 8)))
    await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    code = (await client.get("/api/admin/cards", headers=school)).json()["cards"][0]["code"]
    sid = school["X-School"]
    assert photo_service.delete_family_photos(sid, code) == 1
    assert (await _up(client, school, cid, "a.jpg", _jpeg((8, 8, 8)))).json()["status"] == "uploaded"


async def test_siblings_photos_are_cards_at_once_and_flagged(client, school):
    sib = await _siblings_id(client, school)
    r = await _up(client, school, sib, "DSC_9001.jpg", _jpeg((50, 60, 70)))
    assert r.json()["state"] == "filed" and r.json()["label"] == "Fratries · Photo 1"
    assert (await _status(client, school, "Fratries"))["status"] == "special"
    only = (await client.get("/api/admin/cards", headers=school, params={"siblings": "true"})).json()
    assert [c["sibling_photo"] for c in only["cards"]] == [True] and only["classes"][0]["sibling_photos"] is True
    # the Siblings folder cannot be renamed, deleted or validated, and is not a class families can pick
    assert (await client.patch(f"/api/admin/classes/{sib}", json={"name": "Autre"}, headers=school)).status_code == 409
    assert (await client.delete(f"/api/admin/classes/{sib}", headers=school)).status_code == 409
    assert (await client.post(f"/api/admin/classes/{sib}/validate", headers=school)).status_code == 409
    code = only["cards"][0]["code"]
    assert "Fratries" not in (await client.get("/api/portal/classes", params={"code": code})).json()["classes"]
    assert "Fratries" not in [c["class_name"] for c in (await client.get(
        "/api/director/dashboard", headers=school)).json()["classes"]]


async def test_the_class_pages_stay_inside_the_school(client, school, admin_headers):
    cid = await _class(client, school, "9Z")
    assert (await _up(client, admin_headers, cid, "a.jpg")).status_code == 404       # another school's class id
    assert (await client.post(f"/api/admin/classes/{cid}/validate", headers=admin_headers)).status_code == 404


async def test_the_operator_loads_photos_but_a_director_cannot(client, school, operator_headers, director_headers):
    cid = await _class(client, school, "8Y")
    mine = {**operator_headers, "X-School": school["X-School"]}
    assert (await _up(client, mine, cid, "a.jpg")).status_code == 200
    assert (await _up(client, director_headers, cid, "b.jpg")).status_code in (401, 403)


# ── Sheet 6: unlinked cards, merging, only children ─────────────────────────────────────────────────

async def _two_classes_and_siblings(client, school):
    """2B Student 1 and 3A Student 1 are brother and sister, and one sibling photo shows both."""
    c1, c2 = await _class(client, school, "2B"), await _class(client, school, "3A")
    sib = await _siblings_id(client, school)
    await _up(client, school, c1, "b1.jpg", _jpeg((11, 0, 0)))
    await _up(client, school, c1, "b2.jpg", _jpeg((12, 0, 0)))
    await _up(client, school, c2, "a1.jpg", _jpeg((0, 13, 0)))
    for cid in (c1, c2):
        await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    await _up(client, school, sib, "together.jpg", _jpeg((0, 0, 14)))
    cards = (await client.get("/api/admin/cards", headers=school)).json()["cards"]
    return {c["filename"]: c["code"] for c in cards}


async def test_the_grid_filters_by_several_classes_and_counts_unlinked_cards(client, school):
    codes = await _two_classes_and_siblings(client, school)
    g = (await client.get("/api/admin/cards", headers=school, params=[("class_name", "2B"), ("class_name", "3A")])).json()
    assert sorted(c["filename"] for c in g["cards"]) == ["a1.jpg", "b1.jpg", "b2.jpg"]
    assert g["unlinked"] == 3 and g["unlinked_total"] == 4 and g["total"] == 4
    assert {c["class_name"] for c in g["classes"]} == {"2B", "3A", "Fratries"}
    assert (await client.get("/api/admin/cards", headers=school, params={"state": "family"})).json()["cards"] == []
    assert len(codes) == 4


async def test_merging_needs_a_confirmation_then_makes_one_family_with_one_code(client, school):
    codes = await _two_classes_and_siblings(client, school)
    trio = [codes["b1.jpg"], codes["a1.jpg"], codes["together.jpg"]]
    refused = await client.post("/api/admin/families/merge", headers=school, json={"codes": trio})
    assert refused.status_code == 400
    assert (await client.get("/api/admin/cards", headers=school)).json()["unlinked_total"] == 4     # nothing moved
    r = await client.post("/api/admin/families/merge", headers=school, json={"codes": trio, "confirm": True})
    assert r.status_code == 200, r.text
    assert r.json()["family"]["code"] == codes["b1.jpg"]                      # the first card's code is kept
    assert sorted(r.json()["family"]["classes"]) == ["2B", "3A"]               # the sibling photo adds no class
    g = (await client.get("/api/admin/cards", headers=school)).json()
    kept = [c for c in g["cards"] if c["code"] == codes["b1.jpg"]]
    assert len(kept) == 3 and all(c["state"] == "family" and c["family_size"] == 3 for c in kept)
    assert sorted(c["original_code"] for c in kept if c["original_code"]) == sorted([codes["a1.jpg"], codes["together.jpg"]])
    assert g["unlinked"] == 1                                                  # b2 only
    # the old codes open the same gallery
    for old in (codes["a1.jpg"], codes["together.jpg"]):
        gal = (await client.get("/api/portal/photos", params={"code": old})).json()
        assert gal["family_code"] == codes["b1.jpg"]
    ev = (await client.get("/api/admin/audit?action=family.merge", headers=school)).json()["events"]
    assert ev and ev[0]["details"]["kept"] == codes["b1.jpg"] and len(ev[0]["details"]["merged"]) == 2


async def test_a_merge_can_be_undone_and_restores_the_original_cards(client, school):
    codes = await _two_classes_and_siblings(client, school)
    r = await client.post("/api/admin/families/merge", headers=school,
                          json={"codes": [codes["b1.jpg"], codes["a1.jpg"]], "confirm": True})
    mid = r.json()["merge_ids"][0]
    u = await client.post("/api/admin/families/unmerge", headers=school, json={"merge_id": mid})
    assert u.status_code == 200 and u.json() == {"kept": codes["b1.jpg"], "restored": codes["a1.jpg"], "merge_id": mid}
    g = (await client.get("/api/admin/cards", headers=school)).json()
    by = {c["filename"]: c for c in g["cards"]}
    assert by["a1.jpg"]["code"] == codes["a1.jpg"] and by["b1.jpg"]["code"] == codes["b1.jpg"]
    assert all(c["state"] == "unlinked" and c["merge_id"] is None for c in g["cards"])
    with get_db() as conn:
        classes = {c: [r["class_name"] for r in conn.execute("SELECT class_name FROM students WHERE family_code=?", (c,))]
                   for c in (codes["b1.jpg"], codes["a1.jpg"])}
        alias = conn.execute("SELECT merged_into FROM families WHERE code=?", (codes["a1.jpg"],)).fetchone()["merged_into"]
    assert classes == {codes["b1.jpg"]: ["2B"], codes["a1.jpg"]: ["3A"]} and alias is None
    gal = (await client.get("/api/portal/photos", params={"code": codes["a1.jpg"]})).json()
    assert gal["family_code"] == codes["a1.jpg"]                                # the old card opens its own gallery again
    assert (await client.post("/api/admin/families/unmerge", headers=school, json={"merge_id": mid})).status_code == 409
    ev = (await client.get("/api/admin/audit?action=family.unmerge", headers=school)).json()["events"]
    assert ev and ev[0]["details"]["restored"] == codes["a1.jpg"]
    # and the same two cards can be merged again
    assert (await client.post("/api/admin/families/merge", headers=school,
                              json={"codes": [codes["b1.jpg"], codes["a1.jpg"]], "confirm": True})).status_code == 200


async def test_undoing_one_card_of_a_three_card_family_keeps_the_others_together(client, school):
    codes = await _two_classes_and_siblings(client, school)
    r = await client.post("/api/admin/families/merge", headers=school, json={
        "codes": [codes["b1.jpg"], codes["a1.jpg"], codes["together.jpg"]], "confirm": True})
    first, second = r.json()["merge_ids"]
    # the siblings photo was merged last: undoing the FIRST merge while a later one exists is refused only if it
    # would break the later one; here the second merge's cards are independent of the first one's classes
    assert (await client.post("/api/admin/families/unmerge", headers=school, json={"merge_id": second})).status_code == 200
    g = {c["filename"]: c for c in (await client.get("/api/admin/cards", headers=school)).json()["cards"]}
    assert g["together.jpg"]["code"] == codes["together.jpg"] and g["a1.jpg"]["code"] == codes["b1.jpg"]
    assert (await client.post("/api/admin/families/unmerge", headers=school, json={"merge_id": first})).status_code == 200
    g = {c["filename"]: c for c in (await client.get("/api/admin/cards", headers=school)).json()["cards"]}
    assert g["a1.jpg"]["code"] == codes["a1.jpg"] and all(c["state"] == "unlinked" for c in g.values())


async def test_a_merge_cannot_be_undone_once_the_family_ordered(client, school):
    codes = await _two_classes_and_siblings(client, school)
    r = await client.post("/api/admin/families/merge", headers=school,
                          json={"codes": [codes["b1.jpg"], codes["a1.jpg"]], "confirm": True})
    from conftest import insert_order, item
    sid = school["X-School"]
    insert_order(f"o-{uuid.uuid4().hex[:8]}", codes["b1.jpg"], sid, [item("b1.jpg", "print-10x15", 9.0)])
    u = await client.post("/api/admin/families/unmerge", headers=school, json={"merge_id": r.json()["merge_ids"][0]})
    assert u.status_code == 409 and "ordered since" in u.json()["detail"]


async def test_create_cards_for_only_children_confirms_the_rest_in_one_click(client, school):
    codes = await _two_classes_and_siblings(client, school)
    await client.post("/api/admin/families/merge", headers=school,
                      json={"codes": [codes["b1.jpg"], codes["a1.jpg"], codes["together.jpg"]], "confirm": True})
    r = await client.post("/api/admin/cards/singles", headers=school, json={})
    assert r.json() == {"count": 1, "codes": [codes["b2.jpg"]]}                # only b2 is left, and it is an only child
    g = (await client.get("/api/admin/cards", headers=school)).json()
    assert g["unlinked_total"] == 0 and {c["filename"]: c["state"] for c in g["cards"]}["b2.jpg"] == "single"
    assert (await client.post("/api/admin/cards/singles", headers=school, json={})).json()["count"] == 0   # once
    import zipfile
    z = await client.get("/api/admin/cards.zip", headers=school, params={"only": "singles"})
    names = zipfile.ZipFile(io.BytesIO(z.content)).namelist()
    assert len(names) == 1 and names[0].endswith(f"_{codes['b2.jpg']}.png")
    full = await client.get("/api/admin/cards.zip", headers=school)
    # one sheet per family: the 3-card family and the only child (a lone sibling photo never gets a sheet)
    assert len(zipfile.ZipFile(io.BytesIO(full.content)).namelist()) == 2


async def test_only_children_of_the_selected_classes_and_never_a_lone_sibling_photo(client, school):
    codes = await _two_classes_and_siblings(client, school)
    r = await client.post("/api/admin/cards/singles", headers=school, json={"class_name": ["3A"]})
    assert r.json() == {"count": 1, "codes": [codes["a1.jpg"]]}
    rest = (await client.post("/api/admin/cards/singles", headers=school, json={})).json()
    assert sorted(rest["codes"]) == sorted([codes["b1.jpg"], codes["b2.jpg"]]) and codes["together.jpg"] not in rest["codes"]
    g = (await client.get("/api/admin/cards", headers=school)).json()
    assert g["unlinked_total"] == 1                                            # the sibling photo, still to be matched


async def test_the_sheet_of_a_merged_family_names_every_child_and_the_sibling_photo(client, school):
    codes = await _two_classes_and_siblings(client, school)
    await client.post("/api/admin/families/merge", headers=school,
                      json={"codes": [codes["b1.jpg"], codes["a1.jpg"], codes["together.jpg"]], "confirm": True})
    kept = next(c for c in (await client.get("/api/admin/cards", headers=school)).json()["cards"] if c["code"] == codes["b1.jpg"])
    sheet = await client.get(kept["card_url"])
    assert sheet.status_code == 200 and sheet.headers["content-type"] == "image/png"
    sid = school["X-School"]
    sib = upload_service.siblings_names(sid)
    labels = [upload_service.card_label(r["class_name"], r["seq"], r["class_name"] in sib)
              for r in photo_service.folder_rows(sid, codes["b1.jpg"])]
    assert sorted(labels) == ["2B · Student 1", "3A · Student 1", "Fratries · Photo 1"]


async def test_staff_only_and_school_isolation_for_the_grid(client, school, director_headers):
    assert (await client.get("/api/admin/cards", headers=director_headers)).status_code in (401, 403)
    assert (await client.post("/api/admin/families/unmerge", headers=school, json={"merge_id": 1})).status_code in (404, 409)
    assert (await client.get("/api/admin/cards", headers={**school, "X-School": OTHER_SCHOOL})).json()["cards"] == []


def test_a_waiting_photo_is_outside_the_school_folder_and_follows_the_school_retention(client):
    """Staged photos live in photos/.staging/{school}/…: they are not read as a child, and the RGPD purge finds the
    school's retention for them."""
    from services import cleanup_service
    from pathlib import Path
    assert cleanup_service._locate(Path(".staging/ecole-test/3A/12_a.jpg")) == ("ecole-test", None)
    assert photo_service.STAGING_DIRNAME not in {p.name for p in photo_service.photographer_dirs(photo_service.photos_root())}


# ── A child may have several photos (client, 2026-10-22) ────────────────────────────────────────────

async def _waiting(client, headers, cid):
    return (await client.get(f"/api/admin/classes/{cid}/photos", headers=headers)).json()["waiting"]


async def test_several_photos_of_a_child_become_one_card(client, school):
    cid = await _class(client, school, "5G")
    for i in range(1, 7):
        await _up(client, school, cid, f"DSC_{i:04d}.jpg", _jpeg((i * 20, 5, 5)))
    r = await client.put(f"/api/admin/classes/{cid}/grouping", headers=school, json={"per_child": 3})
    assert [w["child_no"] for w in r.json()["waiting"]] == [1, 1, 1, 2, 2, 2]
    v = await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    assert v.json()["cards"] == 2 and v.json()["photos"] == 6 and v.json()["validated"] is True
    cards = (await client.get("/api/admin/cards", headers=school, params={"class_name": "5G"})).json()["cards"]
    assert [(c["label"], c["photos"], c["filename"]) for c in cards] == [
        ("5G · Student 1", 3, "DSC_0001.jpg"), ("5G · Student 2", 3, "DSC_0004.jpg")]
    # the family's gallery shows all three
    code = cards[0]["code"]
    sid = school["X-School"]
    assert len(photo_service.list_family_files(sid, code)) == 3
    assert (await _status(client, school, "5G"))["photos"] == 6 and (await _status(client, school, "5G"))["cards"] == 2


async def test_photos_are_grouped_by_hand_and_a_lone_photo_stays_a_child(client, school):
    cid = await _class(client, school, "5H")
    up = [(await _up(client, school, cid, f"P{i}.jpg", _jpeg((i * 30, 9, 9)))).json()["upload_id"] for i in range(1, 5)]
    r = await client.put(f"/api/admin/classes/{cid}/grouping", headers=school, json={"assign": {str(up[0]): 7, str(up[2]): 7}})
    assert {w["filename"]: w["child_no"] for w in r.json()["waiting"]} == {"P1.jpg": 7, "P2.jpg": None, "P3.jpg": 7, "P4.jpg": None}
    v = await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    assert v.json()["cards"] == 3 and v.json()["photos"] == 4
    cards = (await client.get("/api/admin/cards", headers=school, params={"class_name": "5H"})).json()["cards"]
    assert [(c["filename"], c["photos"]) for c in cards] == [("P1.jpg", 2), ("P2.jpg", 1), ("P4.jpg", 1)]
    # ungroup is "per_child": 1 ... bad input is refused
    assert (await client.put(f"/api/admin/classes/{cid}/grouping", headers=school, json={"per_child": 2})).status_code == 409   # validated


async def test_grouping_input_is_checked(client, school):
    cid = await _class(client, school, "5J")
    await _up(client, school, cid, "a.jpg", _jpeg((1, 1, 1)))
    assert (await client.put(f"/api/admin/classes/{cid}/grouping", headers=school, json={"assign": {"999999": 1}})).status_code == 409
    w = (await _waiting(client, school, cid))[0]
    assert (await client.put(f"/api/admin/classes/{cid}/grouping", headers=school, json={"assign": {str(w["id"]): 0}})).status_code == 409
    r = await client.put(f"/api/admin/classes/{cid}/grouping", headers=school, json={"per_child": 2})
    assert r.json()["waiting"][0]["child_no"] == 1
    assert (await client.put(f"/api/admin/classes/{cid}/grouping", headers=school, json={"per_child": 1})).json()["waiting"][0]["child_no"] is None
    sib = await _siblings_id(client, school)
    assert (await client.put(f"/api/admin/classes/{sib}/grouping", headers=school, json={"per_child": 2})).status_code == 409


async def test_a_second_photo_can_be_added_to_a_child_already_filed(client, school):
    cid = await _class(client, school, "5K")
    await _up(client, school, cid, "first.jpg", _jpeg((10, 10, 10)))
    await _up(client, school, cid, "other.jpg", _jpeg((20, 20, 20)))
    await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    r = await client.post(f"/api/admin/classes/{cid}/photos", params={"student": 2}, headers=school,
                          files={"file": ("extra.jpg", _jpeg((30, 30, 30)), "image/jpeg")})
    assert r.status_code == 200 and r.json()["label"] == "5K · Student 2", r.text
    cards = (await client.get("/api/admin/cards", headers=school, params={"class_name": "5K"})).json()["cards"]
    assert [(c["label"], c["photos"]) for c in cards] == [("5K · Student 1", 1), ("5K · Student 2", 2)]
    assert r.json()["code"] == cards[1]["code"]                              # no new family was made
    bad = await client.post(f"/api/admin/classes/{cid}/photos", params={"student": 9}, headers=school,
                            files={"file": ("x.jpg", _jpeg((40, 40, 40)), "image/jpeg")})
    assert bad.status_code == 422 and "no Student 9" in bad.json()["detail"].replace("There is ", "")
    ev = (await client.get("/api/admin/audit?action=class.photo_added", headers=school)).json()["events"]
    assert ev[0]["details"]["added_to_student"] == 2


async def test_orders_of_a_multi_photo_child_trace_back_to_its_card(client, school):
    cid = await _class(client, school, "5L")
    for n in ("a.jpg", "b.jpg"):
        await _up(client, school, cid, n, _jpeg((len(n) * 40, 1, int(n[0] == "a") * 99)))
    await client.put(f"/api/admin/classes/{cid}/grouping", headers=school, json={"per_child": 2})
    await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    from services import order_service
    card = (await client.get("/api/admin/cards", headers=school, params={"class_name": "5L"})).json()["cards"][0]
    sid = school["X-School"]
    assert order_service.photo_origin(sid, card["code"], "b.jpg")["label"] == "5L · Student 1"


async def test_waiting_photos_have_a_signed_thumbnail_and_cards_list_all_their_photos(client, school):
    cid = await _class(client, school, "6M")
    await _up(client, school, cid, "a.jpg", _jpeg((5, 5, 5)))
    await _up(client, school, cid, "b.jpg", _jpeg((6, 6, 6)))
    waiting = await _waiting(client, school, cid)
    thumb = await client.get(waiting[0]["thumb_url"])
    assert thumb.status_code == 200 and thumb.headers["content-type"] == "image/webp"
    assert (await client.get(waiting[0]["thumb_url"].replace("sig=", "sig=x"))).status_code == 403
    await client.put(f"/api/admin/classes/{cid}/grouping", headers=school, json={"per_child": 2})
    await client.post(f"/api/admin/classes/{cid}/validate", headers=school)
    assert (await client.get(waiting[0]["thumb_url"])).status_code == 403          # no longer waiting
    card = (await client.get("/api/admin/cards", headers=school, params={"class_name": "6M"})).json()["cards"][0]
    assert [f["name"] for f in card["files"]] == ["a.jpg", "b.jpg"]
    assert (await client.get(card["files"][1]["thumb_url"])).status_code == 200


async def test_the_photo_count_is_what_the_folders_really_hold(client, school):
    """Production 2026-10-24: "CP/CE1 · 0 children · 7 photos" and an empty folder — the upload rows of cards that
    were deleted stayed counted. The count now comes from the pupils' folders."""
    cid = await _class(client, school, "CP/CE1")
    for i in range(3):
        assert (await _up(client, school, cid, f"P_{i}.jpg", _jpeg((60 * i, 40, 90)))).status_code == 200
    assert (await client.post(f"/api/admin/classes/{cid}/validate", headers=school)).status_code == 200
    assert (await _status(client, school, "CP/CE1"))["photos"] == 3
    cards = (await client.get("/api/admin/cards", headers=school)).json()["cards"]
    for c in cards:
        r = await client.delete("/api/admin/photos/child", params={"folder": c["folder"]}, headers=school)
        assert r.status_code == 200, r.text
    st = await _status(client, school, "CP/CE1")
    assert (st["photos"], st["staged"], st["cards"], st["status"]) == (0, 0, 0, "empty")   # 0 children, 0 photos, Empty
    # emptied, it starts over like a new class: the next photo waits for "Validate"
    assert (await _up(client, school, cid, "late.jpg", _jpeg((200, 1, 1)))).json()["state"] == "staged"
    st = await _status(client, school, "CP/CE1")
    assert (st["photos"], st["staged"], st["status"]) == (1, 1, "in_progress")
    assert (await client.post(f"/api/admin/classes/{cid}/validate", headers=school)).status_code == 200
    st = await _status(client, school, "CP/CE1")
    assert (st["photos"], st["cards"], st["status"]) == (1, 1, "validated")


async def test_photos_moved_out_of_a_child_leave_it_uncounted(client, school):
    """CPB "3 children · 3 photos" after its photos went elsewhere: a pupil is a folder that still holds a photo."""
    cid = await _class(client, school, "CPB")
    for i in range(2):
        assert (await _up(client, school, cid, f"B_{i}.jpg", _jpeg((70 * i, 200, 9)))).status_code == 200
    assert (await client.post(f"/api/admin/classes/{cid}/validate", headers=school)).status_code == 200
    assert (await _status(client, school, "CPB"))["cards"] == 2
    from core import storage
    with get_db() as conn:
        row = conn.execute("SELECT * FROM child_folders WHERE school_id=? AND class_name='CPB' ORDER BY seq LIMIT 1",
                           (school["X-School"],)).fetchone()
    folder = photo_service.school_root(school["X-School"]) / row["class_dir"] / photo_service.student_dirname(row["seq"])
    for f in storage.files(folder):
        storage.delete(f.key)                                   # the photo is gone, the folder row stays
    st = await _status(client, school, "CPB")
    assert (st["cards"], st["photos"], st["status"]) == (1, 1, "validated")


async def test_a_renamed_class_keeps_its_waiting_photos(client, school):
    cid = await _class(client, school, "CE2 B")
    for i in range(2):
        assert (await _up(client, school, cid, f"W_{i}.jpg", _jpeg((90 * i, 1, 200)))).status_code == 200
    r = await client.patch(f"/api/admin/classes/{cid}", json={"name": "CE2/CM1"}, headers=school)
    assert r.status_code == 200, r.text
    st = await _status(client, school, "CE2/CM1")
    assert st["staged"] == 2 and st["status"] == "in_progress"
    waiting = (await client.get(f"/api/admin/classes/{cid}/photos", headers=school)).json()["waiting"]
    assert len(waiting) == 2
    for w in waiting:                                                                    # the files followed
        assert (await client.get(w["thumb_url"])).status_code == 200
    assert (await client.post(f"/api/admin/classes/{cid}/validate", headers=school)).status_code == 200
    assert (await _status(client, school, "CE2/CM1"))["photos"] == 2
