"""Tests de las partes puras de comfyui_run_foreign_workflow_oneshot.

Cubren sin red ni GPU: la clasificacion de outputs por tipo, la resolucion de un
`source` que ya es dict en API format, y las ramas de error tempranas que retornan
antes de tocar el servidor (output_kind invalido, source de tipo invalido, dict mal
formado). El flujo completo import->resolve->submit->wait->fetch se valida por
integracion contra el server (ver report 0110).
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from pipelines.comfyui_run_foreign_workflow_oneshot import (
    _classify_outputs,
    _resolve_workflow,
    comfyui_run_foreign_workflow_oneshot,
)


def test_classify_outputs_reparte_por_extension():
    outs = {
        "1": {"images": [{"filename": "a.png", "subfolder": "", "type": "output"}]},
        "2": {"gifs": [{"filename": "b.webm", "subfolder": "", "type": "output"}]},
        "3": {"images": [{"filename": "c.webp", "subfolder": "", "type": "output"}]},
        "4": {"3d": [{"filename": "d.glb", "subfolder": "", "type": "output"}]},
    }
    b = _classify_outputs(outs)
    assert [i["filename"] for i in b["image"]] == ["a.png"]
    assert sorted(i["filename"] for i in b["video"]) == ["b.webm", "c.webp"]
    assert [i["filename"] for i in b["mesh"]] == ["d.glb"]


def test_resolve_workflow_dict_api_format():
    wf = {"1": {"class_type": "CheckpointLoaderSimple", "inputs": {}}}
    got, st, err = _resolve_workflow(wf, "127.0.0.1:8188", None, None)
    assert err == "" and st == "dict" and got is wf


def test_resolve_workflow_dict_mal_formado():
    got, st, err = _resolve_workflow({"1": {"no_class": 1}}, "127.0.0.1:8188", None, None)
    assert got == {} and "API format" in err


def test_resolve_workflow_tipo_invalido():
    got, st, err = _resolve_workflow(123, "127.0.0.1:8188", None, None)
    assert got == {} and "source debe ser" in err


def test_pipeline_output_kind_invalido_no_toca_server():
    r = comfyui_run_foreign_workflow_oneshot("cualquier", output_kind="bogus")
    assert not r["ok"] and "output_kind" in r["error"] and r["prompt_id"] == ""


def test_pipeline_dict_mal_formado_no_toca_server():
    r = comfyui_run_foreign_workflow_oneshot({"1": {"no_class": 1}}, server="127.0.0.1:8188")
    assert not r["ok"] and "import fallo" in r["error"] and r["prompt_id"] == ""


if __name__ == "__main__":
    import pytest

    raise SystemExit(pytest.main([__file__, "-v"]))
