"""Tests de los helpers puros de comfyui_replicate_civitai_oneshot.

No tocan red ni GPU: validan la clasificación de la entrada, la elección de
checkpoint sustituto, el match de modelos instalados y la extracción de prompt de
un workflow. El pipeline completo se valida en vivo en el report 0127.
"""
import os
import sys

_FUNCTIONS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _FUNCTIONS_ROOT not in sys.path:
    sys.path.insert(0, _FUNCTIONS_ROOT)

from pipelines.comfyui_replicate_civitai_oneshot import (  # noqa: E402
    _classify_input,
    _extract_positive_from_workflow,
    _find_installed,
    _pick_checkpoint,
)


def test_classify_input_image_modelversion_workflow_error():
    assert _classify_input(23526611) == ("image", 23526611)
    assert _classify_input("https://civitai.com/images/777?x=1") == ("image", 777)
    assert _classify_input("https://civitai.com/models/1?modelVersionId=42")[0] == "model_version"
    assert _classify_input({"3": {"class_type": "KSampler"}})[0] == "workflow_source"
    assert _classify_input("/tmp/foo.json")[0] == "workflow_source"
    assert _classify_input("https://civitai.com/models/123")[0] == "error"
    assert _classify_input("texto_suelto")[0] == "error"


def test_pick_checkpoint_familia_y_exacto():
    installed = ["IMG_dreamshaper_8.safetensors", "IMG_juggernaut_xl_v11.safetensors",
                 "IMG_v1-5-pruned-emaonly-fp16.safetensors", "VIDEO_svd.safetensors",
                 "3D_hunyuan3d-dit-v2-mini.safetensors"]
    # familia sdxl -> elige el que tiene 'xl'
    ck, exact = _pick_checkpoint(installed, "sdxl", "algun_modelo_no_instalado")
    assert ck == "IMG_juggernaut_xl_v11.safetensors" and exact is False
    # familia sd15 -> evita los xl y los de video/3d
    ck, exact = _pick_checkpoint(installed, "sd15", "otro")
    assert "xl" not in ck.lower() and "svd" not in ck and exact is False
    # hint exacto instalado -> exact True
    ck, exact = _pick_checkpoint(installed, "sd15", "IMG_dreamshaper_8")
    assert ck == "IMG_dreamshaper_8.safetensors" and exact is True


def test_find_installed_match_normalizado():
    installed = ["SDXL_detail_tweaker.safetensors", "SD15_watercolor_style.safetensors"]
    # match normalizado (ignora separadores/ext/case)
    assert _find_installed("Detail-Tweaker XL", installed) == "SDXL_detail_tweaker.safetensors"
    # no instalado -> None
    assert _find_installed("LoRA Inexistente 9000", installed) is None


def test_extract_positive_from_workflow():
    wf = {
        "6": {"class_type": "CLIPTextEncode", "inputs": {"text": "a long positive prompt about a knight"}},
        "7": {"class_type": "CLIPTextEncode", "inputs": {"text": "blurry"}},
        "3": {"class_type": "KSampler", "inputs": {}},
    }
    assert _extract_positive_from_workflow(wf) == "a long positive prompt about a knight"
    assert _extract_positive_from_workflow({}) == ""


if __name__ == "__main__":
    test_classify_input_image_modelversion_workflow_error()
    test_pick_checkpoint_familia_y_exacto()
    test_find_installed_match_normalizado()
    test_extract_positive_from_workflow()
    print("OK")
