"""Tests offline de comfyui_build_isometric_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_isometric_workflow import comfyui_build_isometric_workflow  # noqa: E402


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


def test_golden_iso_lora_no_controlnet():
    wf = comfyui_build_isometric_workflow("isometric house, game asset")
    loras = _by_class(wf, "LoraLoader")
    assert len(loras) == 1
    assert loras[0]["inputs"]["lora_name"] == "SD15_isometric_game_assets.safetensors"
    assert loras[0]["inputs"]["strength_model"] == 0.9
    # Sin grid_image -> sin ControlNet.
    assert len(_by_class(wf, "ControlNetApply")) == 0
    assert len(_by_class(wf, "ControlNetLoader")) == 0
    ks = next(n for n in wf.values() if n["class_type"] == "KSampler")
    assert ks["inputs"]["sampler_name"] == "dpmpp_2m"
    assert ks["inputs"]["scheduler"] == "karras"


def test_edge_with_grid_controlnet():
    wf = comfyui_build_isometric_workflow(
        "isometric grass tile", grid_image="iso_grid.png", controlnet_strength=0.7
    )
    assert len(_by_class(wf, "ControlNetApply")) == 1
    assert len(_by_class(wf, "ControlNetLoader")) == 1
    cn = _by_class(wf, "ControlNetLoader")[0]
    assert cn["inputs"]["control_net_name"] == "control_v11p_sd15_canny_fp16.safetensors"
    apply = _by_class(wf, "ControlNetApply")[0]
    assert apply["inputs"]["strength"] == 0.7
    # LoadImage del grid presente.
    loads = [n for n in wf.values() if n["class_type"] == "LoadImage"]
    assert any(n["inputs"]["image"] == "iso_grid.png" for n in loads)


def test_error_empty_prompt():
    try:
        comfyui_build_isometric_workflow("")
        assert False
    except ValueError as e:
        assert "positive" in str(e)


def test_determinism():
    a = comfyui_build_isometric_workflow("iso tower", seed=2)
    b = comfyui_build_isometric_workflow("iso tower", seed=2)
    assert a == b
