"""Brief sheet 8: recap by product (built from the orders), stats by class with the sibling rules, PDF statement."""
import io
import json
import uuid

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()


def _line(photo, name, qty, price, fid, origin=None, sibling=False, kind="print"):
    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 + " EN", "es": name + " ES"})
    if origin:
        it.update(origin_class=origin, origin_sibling=sibling)
    return it


@pytest.fixture
async def school(client, admin_token):
    """2B: two cards (Ana, Ben) · 3A: one card (Cleo) · one sibling photo. Ben and Cleo are brother and sister."""
    h = {"Authorization": f"Bearer {admin_token}"}
    sid = (await client.post("/api/admin/schools", json={"name": f"Dash {uuid.uuid4().hex[:6]}"}, headers=h)).json()["school"]["id"]
    headers = {**h, "X-School": sid}
    await client.put("/api/admin/settings", json={"settings": {"revenue_share_pct": "35"}}, headers=headers)
    ids = {}
    for name, files in (("2B", ["ana.jpg", "ben.jpg"]), ("3A", ["cleo.jpg"])):
        cid = (await client.post("/api/admin/classes", json={"name": name}, headers=headers)).json()["class"]["id"]
        for i, f in enumerate(files):
            await client.post(f"/api/admin/classes/{cid}/photos", headers=headers,
                              files={"file": (f, _jpeg((10 * (len(ids) + i + 1), 0, 0)), "image/jpeg")})
        await client.post(f"/api/admin/classes/{cid}/validate", headers=headers)
        ids[name] = cid
    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((0, 0, 99)), "image/jpeg")})
    cards = (await client.get("/api/admin/cards", headers=headers)).json()["cards"]
    return {"h": headers, "sid": sid, "code": {c["filename"]: c["code"] for c in cards}}


async def _dash(client, school):
    r = await client.get("/api/director/dashboard", headers=school["h"])
    assert r.status_code == 200, r.text
    return r.json()


async def test_the_recap_by_product_is_built_from_the_orders_and_adds_up_to_the_gross_sales(client, school):
    c, sid = school["code"], school["sid"]
    insert_order(str(uuid.uuid4()), c["ana.jpg"], sid, [_line("ana.jpg", "Tirage 13×18", 2, 5.0, "fmt-1", "2B"),
                                                        _line("ana.jpg", "Fichier numérique", 1, 7.0, "digital", "2B", kind="digital")])
    insert_order(str(uuid.uuid4()), c["ben.jpg"], sid, [_line("ben.jpg", "Tirage 13×18", 1, 5.0, "fmt-1", "2B")])
    d = await _dash(client, school)
    by = {p["format_id"]: p for p in d["products"]}
    assert by["fmt-1"]["quantity"] == 3 and by["fmt-1"]["sales"] == 15.0 and by["digital"]["sales"] == 7.0
    assert by["fmt-1"]["name_fr"] == "Tirage 13×18" and by["fmt-1"]["name_en"] == "Tirage 13×18 EN"
    assert sum(p["sales"] for p in d["products"]) == d["gross_sales"] == 22.0     # the lines add up to the gross sales
    # The share is 35 % of the amount WITHOUT VAT (client 2026-11): 22 TTC -> 18.33 HT -> 6.42.
    assert d["gross_sales_ht"] == 18.33 and d["school_share"] == 6.42 and d["revenue_share_pct"] == 35.0 and d["vat_pct"] == 20.0
    assert by["fmt-1"]["sales_ht"] == 12.5
    assert not any(k in d for k in ("revenue_paper", "revenue_magic", "revenue_digital", "partner_name"))


async def test_a_product_deleted_or_hidden_later_stays_in_the_recap(client, school):
    c, sid = school["code"], school["sid"]
    created = (await client.post("/api/admin/formats", headers=school["h"],
                                 json={"name_fr": "Porte-clés", "kind": "print", "price": 6.0})).json()["format"]
    insert_order(str(uuid.uuid4()), c["ana.jpg"], sid, [_line("ana.jpg", "Porte-clés", 1, 6.0, created["format_id"], "2B")])
    await client.patch(f"/api/admin/formats/{created['id']}", headers=school["h"], json={"active": False})
    await client.delete(f"/api/admin/formats/{created['id']}", headers=school["h"])
    d = await _dash(client, school)
    assert [(p["name_fr"], p["sales"]) for p in d["products"]] == [("Porte-clés", 6.0)]
    # and one that never sold is not invented
    assert (await client.get("/api/admin/formats", headers=school["h"])).json()["formats"]


async def test_an_ai_photo_is_the_same_product_as_a_classic_one(client, school):
    c, sid = school["code"], school["sid"]
    ai = _line("ia_91_1.webp", "Tirage 13×18", 1, 5.0, "fmt-1", "2B")
    ai["is_magic"] = True
    insert_order(str(uuid.uuid4()), c["ana.jpg"], sid, [_line("ana.jpg", "Tirage 13×18", 1, 5.0, "fmt-1", "2B"), ai])
    d = await _dash(client, school)
    assert [(p["format_id"], p["quantity"]) for p in d["products"]] == [("fmt-1", 2)]      # no separate "magic" line


async def test_old_orders_with_the_three_historic_lines_still_total_correctly(client, school):
    c, sid = school["code"], school["sid"]
    old_ai = item(fmt="magic-pack", photo="ana.jpg", price=20.0, qty=1, magic=True, label="Pack magique")
    insert_order(str(uuid.uuid4()), c["ana.jpg"], sid, [item(fmt="print-10x15", photo="ana.jpg", price=9.0), old_ai])
    d = await _dash(client, school)
    names = {p["format_id"]: p["name_en"] for p in d["products"]}
    assert names == {"print-10x15": "10×15 Print", "magic-pack": "Magic pack"} and d["gross_sales"] == 29.0


async def test_the_sibling_rules_buyers_in_each_class_and_revenue_split(client, school):
    c, sid = school["code"], school["sid"]
    r = await client.post("/api/admin/families/merge", headers=school["h"], json={
        "codes": [c["ben.jpg"], c["cleo.jpg"], c["together.jpg"]], "confirm": True})
    assert r.status_code == 200, r.text
    fam = c["ben.jpg"]
    # the family orders: Ben's solo print (2B), Cleo's solo print (3A), the sibling photo (split)
    insert_order(str(uuid.uuid4()), fam, sid, [_line("ben.jpg", "Tirage 13×18", 1, 10.0, "fmt-1", "2B"),
                                               _line("cleo.jpg", "Tirage 13×18", 2, 10.0, "fmt-1", "3A"),
                                               _line("together.jpg", "Tirage 20×30", 1, 20.0, "fmt-2", "Fratries", sibling=True)])
    # Ana's family orders once (2B only)
    insert_order(str(uuid.uuid4()), c["ana.jpg"], sid, [_line("ana.jpg", "Tirage 13×18", 1, 10.0, "fmt-1", "2B")])
    d = await _dash(client, school)
    cls = {x["class_name"]: x for x in d["classes"]}
    assert set(cls) == {"2B", "3A"}                                            # the Siblings folder is not a class here
    # 2B: Ben solo 10 + half the sibling photo 10 + Ana 10 ; 3A: Cleo solo 20 + half the sibling photo 10
    assert cls["2B"]["sales"] == 30 and cls["3A"]["sales"] == 30
    assert cls["2B"]["cards"] == 2 and cls["3A"]["cards"] == 1
    assert cls["2B"]["buyers"] == 2 and cls["3A"]["buyers"] == 1               # the sibling family is a buyer in BOTH
    assert cls["2B"]["participation"] == 100 and cls["3A"]["participation"] == 100
    assert d["gross_sales"] == 60.0 and cls["2B"]["sales"] + cls["3A"]["sales"] == 60


async def test_a_class_with_no_buyer_has_a_zero_rate_and_the_total_still_adds_up(client, school):
    c, sid = school["code"], school["sid"]
    insert_order(str(uuid.uuid4()), c["cleo.jpg"], sid, [_line("cleo.jpg", "Tirage 13×18", 1, 10.0, "fmt-1", "3A")])
    d = await _dash(client, school)
    cls = {x["class_name"]: x for x in d["classes"]}
    assert (cls["2B"]["participation"], cls["2B"]["buyers"], cls["2B"]["sales"]) == (0, 0, 0)
    assert (cls["3A"]["participation"], cls["3A"]["sales"]) == (100, 10)
    assert sum(x["sales"] for x in d["classes"]) == d["gross_sales"]


async def test_an_unmerged_sibling_photo_order_is_split_over_the_checkout_class_or_dropped_safely(client, school):
    c, sid = school["code"], school["sid"]
    # a family with no classes and no origin on the line (very old order): no crash, nothing credited, still in the recap
    orphan = "ORP-AAA-BBB"
    with get_db() as conn:
        conn.execute("INSERT INTO families (code, family_name, school_id, created_at) VALUES (?,?,?,?)", (orphan, "", sid, "2026-10-01"))
        conn.commit()
    insert_order(str(uuid.uuid4()), orphan, sid, [item(fmt="print-10x15", photo="x.jpg", price=9.0)])
    d = await _dash(client, school)
    assert d["gross_sales"] == 9.0 and sum(x["sales"] for x in d["classes"]) == 0


async def test_new_orders_remember_which_class_each_photo_came_from(client, school):
    c, sid = school["code"], school["sid"]
    fam = c["ben.jpg"]
    with get_db() as conn:
        conn.execute("UPDATE families SET consent_at=? WHERE code=?", ("2026-10-01", fam))
        conn.commit()
    p = (await client.post("/api/admin/formats", headers=school["h"], json={"name_fr": "Tirage", "kind": "print", "price": 4.0})).json()["format"]
    body = {"family_code": fam, "customer_email": "p@example.com",
            "items": [{"photo_filename": "ben.jpg", "format_id": p["format_id"], "format_label": "Tirage", "quantity": 1,
                       "unit_price": 4.0, "is_magic": False}], "total": 4.0}
    r = await client.post("/api/portal/orders", json=body)
    assert r.status_code == 200, r.text
    with get_db() as conn:
        line = json.loads(conn.execute("SELECT items_json FROM orders WHERE id=?", (r.json()["order_id"],)).fetchone()["items_json"])[0]
    assert line["origin_class"] == "2B" and line["origin_sibling"] is False


async def test_the_pdf_statement_has_the_same_breakdown(client, school):
    c, sid = school["code"], school["sid"]
    insert_order(str(uuid.uuid4()), c["ana.jpg"], sid, [_line("ana.jpg", "Tirage 13×18", 2, 5.0, "fmt-1", "2B")])
    r = await client.get("/api/director/statement.pdf", headers=school["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("/api/director/statement.pdf", headers=school["h"], params={"lang": lang})).status_code == 200
    ev = (await client.get("/api/admin/audit?action=statement", headers=school["h"])).json()["events"]
    assert ev


def test_a_long_statement_paginates():
    from services import stats_service
    recap = stats_service.product_recap([])
    recap["products"] = [{"format_id": f"p{i}", "quantity": 1, "sales": 5.0, "sales_ht": stats_service.ht(5.0), "name_fr": f"Produit {i}"}
                         for i in range(60)]
    recap["gross"], recap["gross_ht"] = 300.0, stats_service.ht(300.0)
    assert stats_service.statement_pdf("Ecole", recap, 35.0).startswith(b"%PDF")


async def test_the_head_teacher_sees_the_dashboard_and_the_statement_read_only(client, director_headers, operator_headers):
    assert (await client.get("/api/director/dashboard", headers=director_headers)).status_code == 200
    assert (await client.get("/api/director/statement.pdf", headers=director_headers)).status_code == 200
    assert (await client.get("/api/director/statement.pdf", headers=operator_headers)).status_code == 403
    for method, url, body in (("PUT", "/api/admin/settings", {"settings": {}}),
                              ("POST", "/api/admin/formats", {"name_fr": "x", "kind": "print", "price": 1})):
        assert (await client.request(method, url, json=body, headers=director_headers)).status_code in (401, 403)


async def test_the_operator_class_list_has_no_money(client, school, operator_headers):
    mine = {**operator_headers, "X-School": school["sid"]}
    cls = (await client.get("/api/admin/classes", headers=mine)).json()["classes"]
    assert all(c["sales"] is None for c in cls) and {c["class_name"] for c in cls} >= {"2B", "3A"}


def test_ht_is_ttc_divided_by_1_20_and_the_share_is_on_the_ht():
    from services import stats_service as st
    assert st.ht(1620.0) == 1350.0 and st.ht(127.0) == 105.83      # the client's example (NOT 1620 - 20 % = 1296)
    assert st.school_share(1620.0, 35.0) == 472.5



async def test_orders_and_cards_come_in_pages_sorted_and_searched_over_the_whole_list(client, school):
    for k in range(7):
        insert_order(str(uuid.uuid4()), school["code"]["ana.jpg"], school["sid"], [_line("ana.jpg", "Tirage", 1, float(k + 1), "fmt-1", "2B")])
    h = school["h"]
    everything = (await client.get("/api/admin/orders", headers=h)).json()
    assert len(everything["orders"]) == 7 and everything["total"] == 7                  # no `page`: the whole list
    p1 = (await client.get("/api/admin/orders", headers=h, params={"page": 1, "page_size": 3, "sort": "total", "dir": "desc"})).json()
    p3 = (await client.get("/api/admin/orders", headers=h, params={"page": 3, "page_size": 3, "sort": "total", "dir": "desc"})).json()
    assert [o["total"] for o in p1["orders"]] == [7.0, 6.0, 5.0] and [o["total"] for o in p3["orders"]] == [1.0]
    assert p1["pages"] == 3 and p1["total"] == 7
    big = (await client.get("/api/admin/orders", headers=h, params={"page": 99, "page_size": 3})).json()
    assert big["page"] == 3                                                           # a page past the end lands on the last one
    one = (await client.get("/api/admin/orders", headers=h, params={"q": p1["orders"][0]["short_id"].lower()})).json()
    assert [o["id"] for o in one["orders"]] == [p1["orders"][0]["id"]]

    allc = (await client.get("/api/admin/cards", headers=h)).json()
    pc = (await client.get("/api/admin/cards", headers=h, params={"page": 1, "page_size": 2})).json()
    assert len(pc["cards"]) == 2 and pc["pages"] == -(-len(allc["cards"]) // 2) and pc["total_shown"] == len(allc["cards"])
    assert pc["unlinked"] == allc["unlinked"]                                          # counts are of the whole list, not the page
    code = allc["cards"][-1]["code"]
    found = (await client.get("/api/admin/cards", headers=h, params={"q": code.lower().replace("-", " "), "page": 1})).json()
    assert [c["code"] for c in found["cards"]] == [code]


def test_signed_urls_repeat_within_a_window_so_the_browser_can_cache_them(monkeypatch):
    import time
    from core import security
    now = 1_800_000_100
    monkeypatch.setattr(time, "time", lambda: now)
    a = security.sign("admin:s/c/f.jpg", 3600)
    monkeypatch.setattr(time, "time", lambda: now + 7)          # a few seconds later: the very same URL
    assert security.sign("admin:s/c/f.jpg", 3600) == a
    assert 3600 <= a[0] - now <= 3600 + security.SIGN_WINDOW_SECS    # never shorter than asked, at most one window longer
    assert security.verify_signature("admin:s/c/f.jpg", a[0], a[1])
    monkeypatch.setattr(time, "time", lambda: now + 3600 + security.SIGN_WINDOW_SECS + 1)
    assert not security.verify_signature("admin:s/c/f.jpg", a[0], a[1])   # and it does expire
