"""Tests offline de comfyui_build_ui_hud_workflow (estructura del dict, sin GPU)."""

import os
import sys

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


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


def _by_class(wf, cls):
    return [n for n in wf.values() if n["class_type"] == cls]


def _id_of(wf, cls):
    return next(nid for nid, n in wf.items() if n["class_type"] == cls)


def test_golden_transparent_recipe():
    wf = comfyui_build_ui_hud_workflow("health bar", transparent=True, seed=42)
    cls = _classes(wf)
    # Cadena base txt2img + Rembg para alpha.
    assert "CheckpointLoaderSimple" in cls
    assert "KSampler" in cls
    assert "VAEDecode" in cls
    assert "SaveImage" in cls
    assert "Image Rembg (Remove Background)" in cls
    # El element aparece en el prompt positivo, con el scaffold de UI.
    pos = next(
        n for n in wf.values()
        if n["class_type"] == "CLIPTextEncode" and "health bar" in n["inputs"]["text"]
    )
    assert "game UI element" in pos["inputs"]["text"]
    assert "centered" in pos["inputs"]["text"]
    assert "plain background" in pos["inputs"]["text"]
    # SaveImage toma la imagen del Rembg (no del VAEDecode).
    rembg_id = _id_of(wf, "Image Rembg (Remove Background)")
    save = next(n for n in wf.values() if n["class_type"] == "SaveImage")
    assert save["inputs"]["images"] == [rembg_id, 0]
    assert _by_class(wf, "Image Rembg (Remove Background)")[0]["inputs"]["transparency"] is True


def test_edge_opaque_no_rembg():
    wf = comfyui_build_ui_hud_workflow("wooden button", transparent=False)
    assert "Image Rembg (Remove Background)" not in _classes(wf)
    # SaveImage toma del VAEDecode directamente.
    vd_id = _id_of(wf, "VAEDecode")
    save = next(n for n in wf.values() if n["class_type"] == "SaveImage")
    assert save["inputs"]["images"] == [vd_id, 0]


def test_edge_size_reflected():
    wf = comfyui_build_ui_hud_workflow("mana orb", size=768)
    latent = _by_class(wf, "EmptyLatentImage")[0]["inputs"]
    assert latent["width"] == 768
    assert latent["height"] == 768  # cuadrado


def test_edge_ui_style_in_prompt():
    wf = comfyui_build_ui_hud_workflow(
        "ornate frame", ui_style="sci-fi HUD, neon glow", transparent=False
    )
    pos = next(
        n for n in wf.values()
        if n["class_type"] == "CLIPTextEncode" and "ornate frame" in n["inputs"]["text"]
    )
    assert "sci-fi HUD, neon glow" in pos["inputs"]["text"]


def test_edge_lora_reflected():
    wf = comfyui_build_ui_hud_workflow(
        "magic icon", lora="SD15_detail_tweaker.safetensors", lora_strength=0.9
    )
    loras = _by_class(wf, "LoraLoader")
    assert len(loras) == 1
    assert loras[0]["inputs"]["lora_name"] == "SD15_detail_tweaker.safetensors"
    assert loras[0]["inputs"]["strength_model"] == 0.9


def test_error_empty_element():
    try:
        comfyui_build_ui_hud_workflow("  ")
        assert False
    except ValueError as e:
        assert "element" in str(e)


def test_determinism():
    a = comfyui_build_ui_hud_workflow("menu cursor", lora="SD15_detail_tweaker.safetensors", seed=7)
    b = comfyui_build_ui_hud_workflow("menu cursor", lora="SD15_detail_tweaker.safetensors", seed=7)
    assert a == b
