"""Tests de estructura/determinismo para comfyui_build_asset_variant_workflow (func pura, img2img)."""

import os
import sys

import pytest

sys.path.insert(0, os.path.dirname(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from ml.comfyui_build_asset_variant_workflow import comfyui_build_asset_variant_workflow
from _comfyui_wf_assert import assert_api_format, class_types, node_by_ct


def _texts(wf):
    return [n["inputs"].get("text", "") for n in wf.values() if n["class_type"] == "CLIPTextEncode"]


def test_estructura_img2img():
    # img2img: parte de una imagen (LoadImage + VAEEncode), NO de EmptyLatentImage.
    wf = comfyui_build_asset_variant_workflow("enemy.png", "ice element")
    assert_api_format(wf)
    cts = class_types(wf)
    for ct in ("CheckpointLoaderSimple", "LoadImage", "VAEEncode", "CLIPTextEncode",
               "KSampler", "VAEDecode", "SaveImage"):
        assert ct in cts, f"falta nodo {ct}"
    assert "EmptyLatentImage" not in cts  # img2img no genera desde ruido


def test_load_image_y_prompt_reflejados():
    wf = comfyui_build_asset_variant_workflow("  enemy_creature_00001_.png  ", "fire element")
    # input_image se strippea y llega al LoadImage.
    assert node_by_ct(wf, "LoadImage")["inputs"]["image"] == "enemy_creature_00001_.png"
    # el positivo contiene la variante + el refuerzo de composicion.
    pos = [t for t in _texts(wf) if "same composition" in t]
    assert pos and "fire element" in pos[0]


def test_size_default_inserta_imagescale():
    # size=512 por defecto -> normaliza la base con un ImageScale a 512x512.
    wf = comfyui_build_asset_variant_workflow("enemy.png", "golden tier 2")
    scale = node_by_ct(wf, "ImageScale")["inputs"]
    assert scale["width"] == 512 and scale["height"] == 512


def test_size_none_sin_imagescale():
    wf = comfyui_build_asset_variant_workflow("enemy.png", "frozen", size=None)
    assert "ImageScale" not in class_types(wf)


def test_denoise_se_clampa():
    assert node_by_ct(comfyui_build_asset_variant_workflow("e.png", "v", denoise=2.0),
                      "KSampler")["inputs"]["denoise"] == 1.0
    assert node_by_ct(comfyui_build_asset_variant_workflow("e.png", "v", denoise=-1.0),
                      "KSampler")["inputs"]["denoise"] == 0.0
    assert node_by_ct(comfyui_build_asset_variant_workflow("e.png", "v", denoise=0.5),
                      "KSampler")["inputs"]["denoise"] == 0.5


def test_filename_prefix_y_seed():
    wf = comfyui_build_asset_variant_workflow("e.png", "v", seed=123, filename_prefix="mio")
    assert node_by_ct(wf, "SaveImage")["inputs"]["filename_prefix"] == "mio"
    assert node_by_ct(wf, "KSampler")["inputs"]["seed"] == 123


def test_lora_inyecta_loraloader():
    sin = comfyui_build_asset_variant_workflow("e.png", "v")
    con = comfyui_build_asset_variant_workflow("e.png", "v", lora="SD15_dark.safetensors")
    assert "LoraLoader" not in class_types(sin)
    assert "LoraLoader" in class_types(con)


def test_input_image_vacio_lanza():
    with pytest.raises(ValueError):
        comfyui_build_asset_variant_workflow("   ", "v")


def test_variant_vacio_lanza():
    with pytest.raises(ValueError):
        comfyui_build_asset_variant_workflow("e.png", "")


def test_determinista():
    a = comfyui_build_asset_variant_workflow("e.png", "ice", seed=7, denoise=0.5)
    b = comfyui_build_asset_variant_workflow("e.png", "ice", seed=7, denoise=0.5)
    assert a == b
