"""Tests offline para comfyui_flatten_alpha_on_color (impura PIL: aplana RGBA sobre fondo solido).

Sin red, sin GPU, sin servidor: crea un PNG RGBA real y verifica el RGB resultante.
"""

import os
import sys

import pytest

sys.path.insert(0, os.path.dirname(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from ml.comfyui_flatten_alpha_on_color import comfyui_flatten_alpha_on_color

PIL = pytest.importorskip("PIL")
from PIL import Image  # noqa: E402


def _rgba(path, size=(32, 32), color=(0, 0, 0, 0)):
    Image.new("RGBA", size, color).save(path)
    return str(path)


def test_aplana_transparente_sobre_blanco(tmp_path):
    src = _rgba(tmp_path / "sprite.png", color=(0, 0, 0, 0))  # totalmente transparente
    out = tmp_path / "flat.png"
    res = comfyui_flatten_alpha_on_color(src, out_path=str(out), color=(255, 255, 255))
    assert res["ok"] is True and res["error"] == ""
    with Image.open(res["out_path"]) as im:
        assert im.mode == "RGB"  # sin alpha
        # sobre alpha 0 queda el fondo solido: blanco.
        assert im.getpixel((0, 0)) == (255, 255, 255)


def test_color_de_fondo_personalizado(tmp_path):
    src = _rgba(tmp_path / "s.png", color=(0, 0, 0, 0))
    res = comfyui_flatten_alpha_on_color(src, out_path=str(tmp_path / "o.png"), color=(10, 20, 30))
    with Image.open(res["out_path"]) as im:
        assert im.getpixel((0, 0)) == (10, 20, 30)


def test_size_redimensiona_cuadrado(tmp_path):
    src = _rgba(tmp_path / "s.png", size=(32, 16))
    res = comfyui_flatten_alpha_on_color(src, out_path=str(tmp_path / "o.png"), size=64)
    assert res["size"] == [64, 64]
    with Image.open(res["out_path"]) as im:
        assert im.size == (64, 64)


def test_out_path_default_sufijo_flat(tmp_path):
    src = _rgba(tmp_path / "sprite.png")
    res = comfyui_flatten_alpha_on_color(src)  # out_path None -> <base>_flat.png
    assert res["ok"] is True
    assert res["out_path"].endswith("sprite_flat.png")


def test_error_imagen_inexistente(tmp_path):
    res = comfyui_flatten_alpha_on_color(str(tmp_path / "no.png"))
    assert res["ok"] is False and "no existe" in res["error"]


def test_determinista(tmp_path):
    src = _rgba(tmp_path / "s.png", color=(5, 5, 5, 128))
    a = comfyui_flatten_alpha_on_color(src, out_path=str(tmp_path / "a.png"), color=(200, 0, 0))
    b = comfyui_flatten_alpha_on_color(src, out_path=str(tmp_path / "b.png"), color=(200, 0, 0))
    with Image.open(a["out_path"]) as ia, Image.open(b["out_path"]) as ib:
        assert ia.tobytes() == ib.tobytes()
