"""Tests offline de comfyui_build_pixelart_workflow (sin red ni GPU; estructura del dict)."""

import os
import sys

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


def _classes(wf):
    return [n["class_type"] for n in wf.values()]


def _ksampler(wf):
    return next(n for n in wf.values() if n["class_type"] == "KSampler")


def test_golden_lcm_two_loras():
    wf = comfyui_build_pixelart_workflow("isometric house, pixel, 32x32 style", use_lcm=True)
    cls = _classes(wf)
    # Dos LoraLoader: SDXL_pixel-art + SDXL_lcm-lora.
    loras = [n for n in wf.values() if n["class_type"] == "LoraLoader"]
    assert len(loras) == 2
    names = {n["inputs"]["lora_name"] for n in loras}
    assert names == {"SDXL_pixel-art.safetensors", "SDXL_lcm-lora.safetensors"}
    px = next(n for n in loras if n["inputs"]["lora_name"] == "SDXL_pixel-art.safetensors")
    assert px["inputs"]["strength_model"] == 1.2
    # KSampler con defaults LCM.
    ks = _ksampler(wf)["inputs"]
    assert ks["steps"] == 8 and ks["cfg"] == 1.5
    assert ks["sampler_name"] == "lcm" and ks["scheduler"] == "sgm_uniform"
    assert "CheckpointLoaderSimple" in cls and "SaveImage" in cls


def test_edge_no_lcm_single_lora():
    wf = comfyui_build_pixelart_workflow("a pixel sword", use_lcm=False)
    loras = [n for n in wf.values() if n["class_type"] == "LoraLoader"]
    assert len(loras) == 1
    assert loras[0]["inputs"]["lora_name"] == "SDXL_pixel-art.safetensors"
    ks = _ksampler(wf)["inputs"]
    assert ks["steps"] == 25 and ks["cfg"] == 7.0
    assert ks["sampler_name"] == "euler" and ks["scheduler"] == "normal"


def test_edge_overrides_and_clamp():
    wf = comfyui_build_pixelart_workflow(
        "pixel knight", use_lcm=True, steps=12, cfg=2.0, lora_strength=5.0
    )
    ks = _ksampler(wf)["inputs"]
    assert ks["steps"] == 12 and ks["cfg"] == 2.0
    px = next(
        n for n in wf.values()
        if n["class_type"] == "LoraLoader" and n["inputs"]["lora_name"] == "SDXL_pixel-art.safetensors"
    )
    assert px["inputs"]["strength_model"] == 2.0  # clamp a [0,2]


def test_error_empty_prompt():
    try:
        comfyui_build_pixelart_workflow("   ")
        assert False, "deberia lanzar ValueError"
    except ValueError as e:
        assert "positive" in str(e)


def test_determinism():
    a = comfyui_build_pixelart_workflow("pixel cat", seed=3)
    b = comfyui_build_pixelart_workflow("pixel cat", seed=3)
    assert a == b


def test_transparent_default_injects_rembg():
    """transparent default True -> nodo Image Rembg y SaveImage repuntado a el."""
    wf = comfyui_build_pixelart_workflow("pixel knight, full body")
    rembg = [n for n in wf.values() if n["class_type"] == "Image Rembg (Remove Background)"]
    assert len(rembg) == 1
    assert rembg[0]["inputs"]["transparency"] is True
    assert rembg[0]["inputs"]["model"] == "u2net"
    # SaveImage debe leer de la salida del Rembg, no del VAEDecode.
    rembg_id = next(k for k, n in wf.items() if n["class_type"] == "Image Rembg (Remove Background)")
    save = next(n for n in wf.values() if n["class_type"] == "SaveImage")
    assert save["inputs"]["images"][0] == rembg_id


def test_transparent_false_no_rembg():
    """transparent=False -> sin nodo Rembg (tiles/fondos opacos)."""
    wf = comfyui_build_pixelart_workflow("seamless grass tile", transparent=False)
    rembg = [n for n in wf.values() if n["class_type"] == "Image Rembg (Remove Background)"]
    assert len(rembg) == 0
    # SaveImage lee directo del VAEDecode.
    vae_id = next(k for k, n in wf.items() if n["class_type"] == "VAEDecode")
    save = next(n for n in wf.values() if n["class_type"] == "SaveImage")
    assert save["inputs"]["images"][0] == vae_id


def test_rembg_model_override():
    wf = comfyui_build_pixelart_workflow("anime hero", rembg_model="isnet-anime")
    rembg = next(n for n in wf.values() if n["class_type"] == "Image Rembg (Remove Background)")
    assert rembg["inputs"]["model"] == "isnet-anime"
