"""Branding assets with their placeholders (logo, watermark, card template) and card-only payments."""
import io

from PIL import Image

from core import config
from services import brand_service, card_service


def _png(size, color=(200, 30, 30, 255)) -> bytes:
    buf = io.BytesIO()
    Image.new("RGBA", size, color).save(buf, "PNG")
    return buf.getvalue()


async def test_without_a_logo_the_site_uses_the_text_placeholder(client):
    brand_service.delete_asset("logo")
    assert (await client.get("/api/brand")).json() == {"logo_url": None}
    assert (await client.get("/api/brand/logo.png")).status_code == 404


async def test_the_operator_uploads_the_logo_and_everyone_gets_it(client, admin_headers):
    r = await client.post("/api/admin/brand/logo", headers=admin_headers,
                          files={"file": ("logo.png", _png((600, 200)), "image/png")})
    assert r.status_code == 200, r.text
    url = (await client.get("/api/brand")).json()["logo_url"]
    assert url and url.startswith("/api/brand/logo.png?v=")
    got = await client.get(url.split("?")[0])
    assert got.status_code == 200 and got.headers["content-type"] == "image/png"
    assert (await client.delete("/api/admin/brand/logo", headers=admin_headers)).json()["logo"]["custom"] is False


async def test_a_director_cannot_change_the_brand(client, director_headers):
    r = await client.post("/api/admin/brand/logo", headers=director_headers,
                          files={"file": ("logo.png", _png((60, 20)), "image/png")})
    assert r.status_code == 403


async def test_uploads_that_are_not_images_or_have_the_wrong_shape_are_refused(client, admin_headers):
    r = await client.post("/api/admin/brand/watermark", headers=admin_headers,
                          files={"file": ("x.png", b"<svg onload=alert(1)>", "image/png")})
    assert r.status_code == 400
    r = await client.post("/api/admin/brand/card_template", headers=admin_headers,
                          files={"file": ("t.png", _png((1800, 1200)), "image/png")})       # landscape
    assert r.status_code == 400
    assert (await client.post("/api/admin/brand/other", headers=admin_headers,
                              files={"file": ("t.png", _png((10, 10)), "image/png")})).status_code == 400


def test_watermark_placeholder_and_uploaded_mark_both_change_the_photo():
    photo = Image.new("RGB", (800, 600), (90, 90, 90))
    cfg = {**brand_service.DEFAULT_WATERMARK}
    assert len(set(brand_service.stamp(photo, cfg).getdata())) > 5           # text placeholder
    for mode in ("tile", "center", "corner"):
        assert brand_service.stamp(photo, {**cfg, "mode": mode}).size == photo.size
    brand_service.save_asset("watermark", _png((400, 120), (255, 255, 0, 255)))
    try:
        out = brand_service.stamp(photo, cfg)
        assert any(px[0] > 120 and px[2] < 110 for px in out.getdata())     # yellow-ish: the uploaded mark
    finally:
        brand_service.delete_asset("watermark")
    assert brand_service.stamp(photo, {**cfg, "enabled": False}) is photo


async def test_watermark_settings_are_validated(client, admin_headers):
    for bad in ({"mode": "spiral"}, {"opacity": 0}, {"scale": 500}):
        assert (await client.put("/api/admin/brand-watermark", headers=admin_headers, json=bad)).status_code == 400


async def test_the_card_uses_the_client_template_once_uploaded(client, admin_headers):
    placeholder = card_service.render_card(code="MEE-AAA-111", classes=["CP A"], school_name="X",
                                           portal_url="https://p.example")
    r = await client.post("/api/admin/brand/card_template", headers=admin_headers,
                          files={"file": ("t.png", _png((800, 1200), (12, 140, 60, 255)), "image/png")})
    assert r.status_code == 200, r.text
    try:
        card = card_service.render_card(code="MEE-AAA-111", classes=["CP A"], school_name="X",
                                        portal_url="https://p.example")
        img = Image.open(io.BytesIO(card)).convert("RGB")
        assert img.size == (1200, 1800) and card != placeholder
        assert img.getpixel((1150, 40)) == (12, 140, 60)                    # the template's background
        # zones move the parts; nonsense is refused
        ok = await client.put("/api/admin/brand-zones", headers=admin_headers,
                              json={"zones": {"qr": {"x": 800, "y": 1400, "size": 360}, "url": None}})
        assert ok.status_code == 200
        bad = await client.put("/api/admin/brand-zones", headers=admin_headers, json={"zones": {"qr": {"x": 5}}})
        assert bad.status_code == 400
        prev = await client.get("/api/admin/brand/card-preview.png", headers=admin_headers)
        assert prev.status_code == 200 and prev.headers["content-type"] == "image/png"
    finally:
        await client.delete("/api/admin/brand/card_template", headers=admin_headers)


async def test_payment_is_card_only(client, monkeypatch):
    """Client request: credit or debit card only. The PaymentIntent lists `card` and nothing else, so turning
    on more methods in the Stripe dashboard changes nothing."""
    import main
    seen = {}

    class _PI:
        client_secret, id = "cs_test", "pi_test_card_only"

    def fake_create(**kw):
        seen.update(kw)
        return _PI()

    monkeypatch.setattr(config, "STRIPE_SECRET_KEY", "sk_test_x")
    monkeypatch.setattr(main.stripe.PaymentIntent, "create", staticmethod(fake_create))
    body = {"family_code": "TST-1001", "customer_email": "a@example.com", "class_name": "CE1 A",
            "items": [{"photo_filename": "portrait.jpg", "format_id": "digital", "format_label": "Digital",
                       "quantity": 1, "unit_price": 7.0, "is_magic": False}], "total": 7.0}
    r = await client.post("/api/portal/orders", json=body)
    assert r.status_code == 200, r.text
    assert seen["payment_method_types"] == ["card"]
    assert "automatic_payment_methods" not in seen


def test_logo_tone_says_which_background_the_logo_needs(tmp_path):
    def logo(color):
        im = Image.new("RGBA", (300, 80), (0, 0, 0, 0))
        im.paste(Image.new("RGBA", (200, 40), color), (50, 20))
        buf = io.BytesIO()
        im.save(buf, "PNG")
        return buf.getvalue()
    brand_service.delete_asset("logo")
    assert brand_service.logo_tone() is None
    try:
        brand_service.save_asset("logo", logo((20, 20, 20, 255)))
        assert brand_service.logo_tone() == "dark"                          # dark ink: needs a light background
        brand_service.save_asset("logo", logo((255, 255, 255, 255)))
        assert brand_service.logo_tone() == "light"                         # white ink: needs a dark one
        brand_service.save_asset("logo", _png((300, 80), (255, 255, 255, 255)))
        assert brand_service.logo_tone() == "dark"                          # opaque: carries its own background
        # the sheet still draws with an opaque logo
        card_service.render_card(code="MEE-AAA-111", classes=["CP A"], school_name="X",
                                 portal_url="https://p.example")
    finally:
        brand_service.delete_asset("logo")


def test_a_logo_with_white_boxes_behind_dark_ink_still_needs_a_light_background():
    logo = Image.new("RGBA", (500, 100), (0, 0, 0, 0))                      # transparent margin: not "opaque"
    logo.paste(Image.new("RGBA", (400, 100), (255, 255, 255, 255)), (50, 0))     # an opaque white box...
    logo.paste(Image.new("RGBA", (300, 30), (10, 10, 10, 255)), (100, 35))       # ...with black ink on it
    buf = io.BytesIO()
    logo.save(buf, "PNG")
    try:
        brand_service.save_asset("logo", buf.getvalue())
        assert brand_service.logo_tone() == "dark"
    finally:
        brand_service.delete_asset("logo")


async def test_a_school_has_its_own_brand_and_inherits_what_it_did_not_set(client, admin_headers, other_admin_headers):
    """Client 2026-10-28: the branding follows the school in use. Asset by asset: its own file, else the default."""
    from conftest import SCHOOL, OTHER_SCHOOL
    mine = "/api/admin/brand?scope=school"
    up = lambda kind, png, h, scope="school": client.post(f"/api/admin/brand/{kind}?scope={scope}", headers=h,
                                                          files={"file": ("x.png", png, "image/png")})
    try:
        assert (await up("logo", _png((600, 200), (20, 20, 20, 255)), admin_headers, "default")).status_code == 200
        # the school's own logo, only for that school
        r = await up("logo", _png((600, 200), (255, 255, 255, 255)), admin_headers)
        assert r.status_code == 200 and r.json()["scope"] == "school" and r.json()["logo"]["custom"] is True
        own_url = (await client.get(f"/api/brand?school={SCHOOL}")).json()["logo_url"]
        assert f"school={SCHOOL}" in own_url
        assert (await client.get(own_url)).content != (await client.get("/api/brand/logo.png")).content
        other = (await client.get(mine, headers=other_admin_headers)).json()
        assert other["logo"]["custom"] is False and other["logo"]["url"]                  # inherits the default
        assert "school=" not in (await client.get(f"/api/brand?school={OTHER_SCHOOL}")).json()["logo_url"]
        assert (await client.get("/api/admin/brand", headers=admin_headers)).json()["logo"]["custom"] is True

        # the watermark settings too: the school's previews are stamped with ITS mark
        put = await client.put("/api/admin/brand-watermark?scope=school", headers=admin_headers,
                               json={"text": "ECOLE A", "mode": "center"})
        assert put.status_code == 200
        assert brand_service.get_watermark(SCHOOL)["text"] == "ECOLE A"
        assert brand_service.get_watermark(OTHER_SCHOOL)["text"] == brand_service.get_watermark()["text"]
        assert brand_service.watermark_fingerprint(brand_service.get_watermark(SCHOOL), SCHOOL) != \
            brand_service.watermark_fingerprint(brand_service.get_watermark(OTHER_SCHOOL), OTHER_SCHOOL)
        prev = await client.get("/api/admin/brand/watermark-preview.png?scope=school", headers=admin_headers)
        assert prev.status_code == 200

        # the sheet uses the school's template
        assert (await up("card_template", _png((800, 1200), (12, 140, 60, 255)), admin_headers)).status_code == 200
        card = card_service.render_card(code="MEE-AAA-111", classes=["CP A"], school_name="X",
                                        portal_url="https://p.example", school_id=SCHOOL)
        assert Image.open(io.BytesIO(card)).convert("RGB").getpixel((1150, 40)) == (12, 140, 60)
        other_card = card_service.render_card(code="MEE-AAA-111", classes=["CP A"], school_name="X",
                                              portal_url="https://p.example", school_id=OTHER_SCHOOL)
        assert Image.open(io.BytesIO(other_card)).convert("RGB").getpixel((1150, 40)) != (12, 140, 60)

        # reset = back to the default, and the default level was never touched
        for kind in ("logo", "watermark", "card_template"):
            r = await client.delete(f"/api/admin/brand/{kind}?scope=school", headers=admin_headers)
            assert r.status_code == 200 and r.json()[kind]["custom"] is False
        assert brand_service.get_watermark(SCHOOL) == brand_service.get_watermark()
        assert "school=" not in (await client.get(f"/api/brand?school={SCHOOL}")).json()["logo_url"]
    finally:
        for kind in ("logo", "watermark", "card_template"):
            brand_service.delete_asset(kind, SCHOOL)
        brand_service.delete_asset("logo")


async def test_the_public_logo_refuses_a_school_that_is_a_path(client):
    assert (await client.get("/api/brand/logo.png?school=../x")).status_code == 404
    assert (await client.get("/api/brand?school=..%2Fx")).status_code == 200
