"""Tests offline de comfyui_build_vehicle_mount_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_vehicle_mount_workflow import (  # noqa: E402
    comfyui_build_vehicle_mount_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_vehicle_mount_workflow(
        "armored war horse with saddle", 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
    # El vehiculo aparece en el prompt positivo con el scaffold de vehiculo.
    pos = _pos_with(wf, "armored war horse with saddle")
    txt = pos["inputs"]["text"]
    assert "side view" in txt
    assert "full vehicle" in txt
    assert "centered" in txt
    assert "game asset" in txt
    assert "no rider" in txt
    # 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_vehicle_mount_workflow("red sports car", 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_vehicle_mount_workflow("small spaceship", size=768)
    latent = _by_class(wf, "EmptyLatentImage")[0]["inputs"]
    assert latent["width"] == 768
    assert latent["height"] == 768  # cuadrado


def test_edge_view_reflected():
    # La vista isometrica se refleja en el prompt como "isometric view".
    wf = comfyui_build_vehicle_mount_workflow(
        "war chariot", view="isometric", transparent=False
    )
    pos = _pos_with(wf, "war chariot")
    assert "isometric view" in pos["inputs"]["text"]


def test_edge_view_default_side():
    # Sin view, por defecto "side view".
    wf = comfyui_build_vehicle_mount_workflow("wooden sailing ship", transparent=False)
    pos = _pos_with(wf, "wooden sailing ship")
    txt = pos["inputs"]["text"]
    assert txt.startswith("wooden sailing ship")
    assert "side view" in txt


def test_edge_style_in_prompt():
    wf = comfyui_build_vehicle_mount_workflow(
        "fantasy dragon mount", style="stylized fantasy mount", transparent=False
    )
    pos = _pos_with(wf, "fantasy dragon mount")
    assert "stylized fantasy mount" in pos["inputs"]["text"]


def test_edge_lora_reflected():
    wf = comfyui_build_vehicle_mount_workflow(
        "mecha walker", lora="SDXL_mecha.safetensors", lora_strength=0.9
    )
    loras = _by_class(wf, "LoraLoader")
    assert len(loras) == 1
    assert loras[0]["inputs"]["lora_name"] == "SDXL_mecha.safetensors"
    assert loras[0]["inputs"]["strength_model"] == 0.9


def test_error_empty_vehicle():
    try:
        comfyui_build_vehicle_mount_workflow("  ")
        assert False
    except ValueError as e:
        assert "vehicle" in str(e)


def test_determinism():
    a = comfyui_build_vehicle_mount_workflow(
        "griffon mount", view="iso", lora="SD15_vehicle_concept.safetensors", seed=7
    )
    b = comfyui_build_vehicle_mount_workflow(
        "griffon mount", view="iso", lora="SD15_vehicle_concept.safetensors", seed=7
    )
    assert a == b
