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

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_txt2img_workflow import comfyui_build_txt2img_workflow
from ml.comfyui_inject_hires_fix import comfyui_inject_hires_fix
from _comfyui_wf_assert import assert_api_format, class_types


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


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_hires_fix(base)
    # La copia profunda garantiza que el dict original queda intacto (pureza).
    assert "UltimateSDUpscale" not in class_types(base)
    assert "UpscaleModelLoader" not in class_types(base)
    assert set(base) == set(base_antes)


def test_inserta_ultimatesdupscale_y_loader():
    base = comfyui_build_txt2img_workflow("ck.safetensors", "POS", "NEG")
    inj = comfyui_inject_hires_fix(base)
    assert_api_format(inj)
    assert "UltimateSDUpscale" in class_types(inj)
    assert "UpscaleModelLoader" in class_types(inj)


def test_repunta_el_saveimage_al_upscale():
    base = comfyui_build_txt2img_workflow("ck.safetensors", "POS", "NEG")
    inj = comfyui_inject_hires_fix(base)
    upscale_id = _node_id(inj, "UltimateSDUpscale")
    save = next(n for n in inj.values() if n["class_type"] == "SaveImage")
    # El SaveImage debe tomar la imagen del UltimateSDUpscale, no ya del VAEDecode.
    assert save["inputs"]["images"][0] == upscale_id


def test_params_reflejados():
    base = comfyui_build_txt2img_workflow("ck.safetensors", "POS", "NEG")
    inj = comfyui_inject_hires_fix(
        base, upscale_by=2.5, denoise=0.33, seed=123, upscale_model="x4.pth"
    )
    upscale_id = _node_id(inj, "UltimateSDUpscale")
    loader_id = _node_id(inj, "UpscaleModelLoader")
    up_in = inj[upscale_id]["inputs"]
    assert up_in["upscale_by"] == 2.5
    assert up_in["denoise"] == 0.33
    assert up_in["seed"] == 123
    assert inj[loader_id]["inputs"]["model_name"] == "x4.pth"
    # Defaults fijos copiados del builder hermano.
    assert up_in["mode_type"] == "Linear"
    assert up_in["force_uniform_tiles"] is True
    assert up_in["tiled_decode"] is False
    # /object_info marca batch_size como input REQUERIDO de UltimateSDUpscale.
    # Sin el, el submit fallaba con node_errors. Regresion guard.
    assert up_in["batch_size"] == 1


def test_lanza_valueerror_sin_vaedecode():
    # Workflow sin VAEDecode: la funcion no puede localizar la fuente de imagen.
    bad = {
        "4": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "x"}},
    }
    with pytest.raises(ValueError):
        comfyui_inject_hires_fix(bad)
