"""Tests de comfyui_matting_luma_to_alpha (offline, sin red ni GPU; PIL/numpy)."""

import os
import sys

import numpy as np
from PIL import Image

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ml.comfyui_matting_luma_to_alpha import comfyui_matting_luma_to_alpha  # noqa: E402


def _radial_glow_png(path, size=64):
    """Degradado radial blanco (centro brillante) sobre negro."""
    yy, xx = np.mgrid[0:size, 0:size]
    cx = cy = (size - 1) / 2.0
    dist = np.sqrt((xx - cx) ** 2 + (yy - cy) ** 2)
    val = np.clip(1.0 - dist / (size / 2.0), 0.0, 1.0)
    val = val / val.max()            # normaliza el pico a 1.0 (centro = blanco puro)
    arr = (val[..., None] * 255).astype(np.uint8).repeat(3, axis=2)
    Image.fromarray(arr, "RGB").save(path)
    return path


def test_golden_radial_glow(tmp_path):
    src = _radial_glow_png(str(tmp_path / "glow.png"))
    res = comfyui_matting_luma_to_alpha(src)
    assert res["ok"] is True, res["error"]
    img = Image.open(res["out_path"])
    assert img.mode == "RGBA"
    a = np.asarray(img)[..., 3]
    assert a[32, 32] >= 250           # centro brillante -> opaco
    assert a[0, 0] <= 5               # esquina negra -> transparente


def test_edge_all_black_is_transparent(tmp_path):
    src = str(tmp_path / "black.png")
    Image.fromarray(np.zeros((32, 32, 3), np.uint8), "RGB").save(src)
    res = comfyui_matting_luma_to_alpha(src)
    assert res["ok"] is True          # efecto invisible, NO error
    a = np.asarray(Image.open(res["out_path"]))[..., 3]
    assert int(a.max()) == 0          # alpha todo 0


def test_edge_preserves_color(tmp_path):
    """Un frame rojo brillante conserva su RGB y gana alpha por su luma."""
    src = str(tmp_path / "red.png")
    Image.fromarray(np.full((16, 16, 3), [255, 0, 0], np.uint8), "RGB").save(src)
    res = comfyui_matting_luma_to_alpha(src)
    rgba = np.asarray(Image.open(res["out_path"]))
    assert tuple(rgba[8, 8, :3]) == (255, 0, 0)   # color preservado (sin premultiply)
    assert rgba[8, 8, 3] > 0                        # alpha desde luma del rojo


def test_edge_input_rgba_recomputes_from_luma(tmp_path):
    """Input ya RGBA con alpha=0: se ignora y se recomputa alpha desde la luma."""
    src = str(tmp_path / "rgba_in.png")
    arr = np.zeros((16, 16, 4), np.uint8)
    arr[..., :3] = 255                # blanco
    arr[..., 3] = 0                   # alpha previo nulo (debe ignorarse)
    Image.fromarray(arr, "RGBA").save(src)
    res = comfyui_matting_luma_to_alpha(src)
    a = np.asarray(Image.open(res["out_path"]))[..., 3]
    assert int(a.min()) >= 250        # alpha recomputado desde RGB blanco


def test_edge_gamma_raises_midtone_alpha(tmp_path):
    """gamma>1 sube el alpha de los medios tonos respecto a gamma=1."""
    src = str(tmp_path / "mid.png")
    Image.fromarray(np.full((16, 16, 3), 128, np.uint8), "RGB").save(src)
    base = comfyui_matting_luma_to_alpha(src, out_path=str(tmp_path / "g1.png"), gamma=1.0)
    hi = comfyui_matting_luma_to_alpha(src, out_path=str(tmp_path / "g2.png"), gamma=2.0)
    a1 = int(np.asarray(Image.open(base["out_path"]))[8, 8, 3])
    a2 = int(np.asarray(Image.open(hi["out_path"]))[8, 8, 3])
    assert a2 > a1


def test_edge_premultiply(tmp_path):
    """premultiply multiplica el RGB por el alpha (medio tono -> RGB reducido)."""
    src = str(tmp_path / "mid.png")
    Image.fromarray(np.full((16, 16, 3), 128, np.uint8), "RGB").save(src)
    res = comfyui_matting_luma_to_alpha(src, premultiply=True)
    rgba = np.asarray(Image.open(res["out_path"]))[8, 8]
    assert rgba[0] < 128              # RGB premultiplicado por alpha (<1)


def test_error_missing_path(tmp_path):
    res = comfyui_matting_luma_to_alpha(str(tmp_path / "nope.png"))
    assert res["ok"] is False
    assert "no existe" in res["error"]
