"""Tests de estructura/determinismo para comfyui_build_inpaint_asset_workflow (func pura, inpaint)."""

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_inpaint_asset_workflow import comfyui_build_inpaint_asset_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_vae_encode():
    wf = comfyui_build_inpaint_asset_workflow("asset.png", "mask.png", "a golden sword")
    assert_api_format(wf)
    cts = class_types(wf)
    for ct in ("CheckpointLoaderSimple", "LoadImage", "LoadImageMask",
               "VAEEncodeForInpaint", "CLIPTextEncode", "KSampler", "VAEDecode", "SaveImage"):
        assert ct in cts, f"falta nodo {ct}"


def test_prompt_region_y_grow_mask():
    wf = comfyui_build_inpaint_asset_workflow("a.png", "m.png", "blue shield", grow_mask=8)
    pos = [t for t in _texts(wf) if "seamless blend" in t]
    assert pos and "blue shield" in pos[0]
    assert node_by_ct(wf, "VAEEncodeForInpaint")["inputs"]["grow_mask_by"] == 8


def test_grow_mask_se_clampa():
    wf = comfyui_build_inpaint_asset_workflow("a.png", "m.png", "p", grow_mask=999)
    assert node_by_ct(wf, "VAEEncodeForInpaint")["inputs"]["grow_mask_by"] == 64


def test_modo_noise_mask_degrada():
    # noise_mask reemplaza VAEEncodeForInpaint por VAEEncode + SetLatentNoiseMask (+ GrowMask).
    wf = comfyui_build_inpaint_asset_workflow("a.png", "m.png", "p", mode="noise_mask", grow_mask=6)
    cts = class_types(wf)
    assert "VAEEncodeForInpaint" not in cts
    assert "VAEEncode" in cts and "SetLatentNoiseMask" in cts and "GrowMask" in cts


def test_size_inserta_imagescale_a_imagen_y_mascara():
    # size en modo vae_encode escala imagen Y mascara de forma consistente.
    wf = comfyui_build_inpaint_asset_workflow("a.png", "m.png", "p", size=768)
    scales = [n for n in wf.values() if n["class_type"] == "ImageScale"]
    assert len(scales) == 2  # una para la imagen, otra para la mascara
    assert all(s["inputs"]["width"] == 768 and s["inputs"]["height"] == 768 for s in scales)
    assert "ImageToMask" in class_types(wf)


def test_lora_y_filename():
    wf = comfyui_build_inpaint_asset_workflow("a.png", "m.png", "p", lora="x.safetensors",
                                              filename_prefix="mio")
    assert "LoraLoader" in class_types(wf)
    assert node_by_ct(wf, "SaveImage")["inputs"]["filename_prefix"] == "mio"


def test_errores():
    with pytest.raises(ValueError):
        comfyui_build_inpaint_asset_workflow("", "m.png", "p")
    with pytest.raises(ValueError):
        comfyui_build_inpaint_asset_workflow("a.png", "", "p")
    with pytest.raises(ValueError):
        comfyui_build_inpaint_asset_workflow("a.png", "m.png", "")
    with pytest.raises(ValueError):
        comfyui_build_inpaint_asset_workflow("a.png", "m.png", "p", mode="otro")


def test_determinista():
    a = comfyui_build_inpaint_asset_workflow("a.png", "m.png", "orb", seed=7, grow_mask=6)
    b = comfyui_build_inpaint_asset_workflow("a.png", "m.png", "orb", seed=7, grow_mask=6)
    assert a == b
