"""Tests de estructura y pureza para comfyui_inject_lora (funcion pura)."""

import os
import sys

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

from ml.comfyui_build_txt2img_workflow import comfyui_build_txt2img_workflow
from ml.comfyui_inject_lora import comfyui_inject_lora
from _comfyui_wf_assert import assert_api_format, class_types


def _lora_node_id(wf):
    return next(nid for nid, n in wf.items() if n["class_type"] == "LoraLoader")


def test_no_muta_la_entrada():
    base = comfyui_build_txt2img_workflow("ck.safetensors", "POS", "NEG")
    base_antes = {k: dict(v) for k, v in base.items()}
    _ = comfyui_inject_lora(base, "style.safetensors")
    # La copia profunda garantiza que el dict original queda intacto (pureza).
    assert "LoraLoader" not in class_types(base)
    assert set(base) == set(base_antes)


def test_inserta_loraloader_y_respeta_strength():
    base = comfyui_build_txt2img_workflow("ck.safetensors", "POS", "NEG")
    inj = comfyui_inject_lora(base, "style.safetensors", strength_model=0.7, strength_clip=0.4)
    assert_api_format(inj)
    assert "LoraLoader" in class_types(inj)
    lid = _lora_node_id(inj)
    lora_in = inj[lid]["inputs"]
    assert lora_in["lora_name"] == "style.safetensors"
    assert lora_in["strength_model"] == 0.7
    assert lora_in["strength_clip"] == 0.4


def test_reconecta_el_ksampler_al_lora():
    base = comfyui_build_txt2img_workflow("ck.safetensors", "POS", "NEG")
    inj = comfyui_inject_lora(base, "style.safetensors")
    lid = _lora_node_id(inj)
    ks = next(n for n in inj.values() if n["class_type"] == "KSampler")
    # El KSampler debe tomar el modelo del LoraLoader, no ya del checkpoint.
    assert ks["inputs"]["model"][0] == lid


def test_determinista():
    # Builder puro: misma base + mismos args -> mismo dict (deepcopy, sin estado).
    base = comfyui_build_txt2img_workflow("ck.safetensors", "POS", "NEG")
    a = comfyui_inject_lora(base, "style.safetensors")
    b = comfyui_inject_lora(base, "style.safetensors")
    assert a == b
