"""Tests offline de comfyui_build_trap_hazard_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_trap_hazard_workflow import (  # noqa: E402
    comfyui_build_trap_hazard_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 _pos_with(wf, needle):
    return next(
        n for n in wf.values()
        if n["class_type"] == "CLIPTextEncode" and needle in n["inputs"]["text"]
    )


def test_golden_transparent_recipe():
    wf = comfyui_build_trap_hazard_workflow(
        "spiked floor trap", view="side", transparent=True, seed=7
    )
    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
    # Prompt scaffold de hazard.
    pos = _pos_with(wf, "spiked floor trap")
    text = pos["inputs"]["text"]
    assert text.startswith("spiked floor trap")
    assert "single hazard object" in text
    assert "trap" in text
    assert "centered" in text
    assert "plain background" in text
    assert "game asset" in text
    assert "side view" in text
    # SaveImage cuelga del Rembg, no del VAEDecode.
    rembg_id = _id_of(wf, "Image Rembg (Remove Background)")
    save = _by_class(wf, "SaveImage")[0]
    assert save["inputs"]["images"][0] == rembg_id
    # transparency activa en el nodo Rembg.
    rembg = _by_class(wf, "Image Rembg (Remove Background)")[0]
    assert rembg["inputs"]["transparency"] is True


def test_edge_transparent_false_no_rembg():
    wf = comfyui_build_trap_hazard_workflow("lava pit", transparent=False)
    assert "Image Rembg (Remove Background)" not in _classes(wf)
    vae_id = _id_of(wf, "VAEDecode")
    save = _by_class(wf, "SaveImage")[0]
    assert save["inputs"]["images"][0] == vae_id


def test_edge_size_square():
    wf = comfyui_build_trap_hazard_workflow("spinning saw blade", size=768)
    latent = _by_class(wf, "EmptyLatentImage")[0]
    assert latent["inputs"]["width"] == 768
    assert latent["inputs"]["height"] == 768


def test_edge_hazard_at_start_of_scaffold():
    wf = comfyui_build_trap_hazard_workflow("acid pool")
    pos = _pos_with(wf, "acid pool")
    assert pos["inputs"]["text"].startswith("acid pool")


def test_edge_view_reflected():
    wf = comfyui_build_trap_hazard_workflow("pressure plate", view="top-down")
    pos = _pos_with(wf, "pressure plate")
    assert "top-down view" in pos["inputs"]["text"]


def test_edge_view_empty_no_dangling_clause():
    wf = comfyui_build_trap_hazard_workflow("flame jet", view="")
    pos = _pos_with(wf, "flame jet")
    text = pos["inputs"]["text"]
    # Sin clausula "view" colgando cuando view es vacio.
    assert " view," not in text
    assert "single hazard object" in text


def test_edge_style_reflected():
    wf = comfyui_build_trap_hazard_workflow(
        "arrow trap", style="pixel art hazard"
    )
    pos = _pos_with(wf, "arrow trap")
    assert "pixel art hazard" in pos["inputs"]["text"]


def test_edge_negative_rejects_living_character():
    wf = comfyui_build_trap_hazard_workflow("electric trap")
    neg = next(
        n for n in wf.values()
        if n["class_type"] == "CLIPTextEncode"
        and "electric trap" not in n["inputs"]["text"]
    )
    ntext = neg["inputs"]["text"]
    # Diferenciado de enemy_creature: rechaza personaje/criatura vivos.
    assert "character" in ntext
    assert "creature" in ntext
    assert "multiple objects" in ntext


def test_edge_lora_injected():
    wf = comfyui_build_trap_hazard_workflow(
        "bear trap", lora="SD15_pixel_art.safetensors", lora_strength=0.8
    )
    loras = _by_class(wf, "LoraLoader")
    assert len(loras) == 1
    assert loras[0]["inputs"]["lora_name"] == "SD15_pixel_art.safetensors"
    assert loras[0]["inputs"]["strength_model"] == 0.8


def test_edge_transparent_default_true():
    wf = comfyui_build_trap_hazard_workflow("swinging blade")
    assert "Image Rembg (Remove Background)" in _classes(wf)


def test_error_empty_hazard():
    import pytest

    with pytest.raises(ValueError):
        comfyui_build_trap_hazard_workflow("   ")


def test_determinism():
    a = comfyui_build_trap_hazard_workflow("spiked floor trap", seed=7)
    b = comfyui_build_trap_hazard_workflow("spiked floor trap", seed=7)
    assert a == b
