"""Tests offline para comfyui_import_workflow_json (impura: lee disco/URL + normaliza a API format).

Sin red, sin servidor: lee workflows desde archivos locales. Para el caso UI graph monkeypatchea
comfyui_object_info (devuelve None) para no consultar el servidor; se valida la resolucion de
conexiones y el descarte de nodos virtuales (Note).
"""

import json
import os
import sys

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

import ml.comfyui_import_workflow_json as mod
from ml.comfyui_import_workflow_json import comfyui_import_workflow_json
from _comfyui_wf_assert import assert_api_format, class_types


_API = {
    "1": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "m.safetensors"}},
    "2": {"class_type": "VAEDecode", "inputs": {"samples": ["1", 0], "vae": ["1", 2]}},
}

_UI_GRAPH = {
    "nodes": [
        {"id": 1, "type": "CheckpointLoaderSimple", "inputs": [], "widgets_values": ["m.safetensors"]},
        {"id": 2, "type": "Note", "inputs": []},
        {"id": 3, "type": "VAEDecode",
         "inputs": [{"name": "samples", "link": 10}, {"name": "vae", "link": 11}]},
    ],
    "links": [
        [10, 1, 0, 3, 0, "LATENT"],
        [11, 1, 2, 3, 1, "VAE"],
    ],
}


def _write(tmp_path, name, obj):
    p = tmp_path / name
    p.write_text(json.dumps(obj))
    return str(p)


def test_api_format_se_devuelve_tal_cual(tmp_path):
    res = comfyui_import_workflow_json(_write(tmp_path, "api.json", _API))
    assert res["ok"] is True and res["format_detected"] == "api"
    assert res["workflow"] == _API


def test_ui_graph_se_normaliza(tmp_path, monkeypatch):
    monkeypatch.setattr(mod, "comfyui_object_info", lambda server="", timeout=5.0: None)
    res = comfyui_import_workflow_json(_write(tmp_path, "ui.json", _UI_GRAPH))
    assert res["ok"] is True and res["format_detected"] == "ui_graph"
    api = res["workflow"]
    assert_api_format(api)
    # el nodo virtual Note se descarta; las conexiones del VAEDecode se resuelven al CheckpointLoader.
    assert "Note" not in class_types(api)
    assert "2" not in api
    assert api["3"]["inputs"]["samples"] == ["1", 0]
    assert api["3"]["inputs"]["vae"] == ["1", 2]


def test_json_invalido_error(tmp_path):
    p = tmp_path / "bad.json"
    p.write_text("no soy json {")
    res = comfyui_import_workflow_json(str(p))
    assert res["ok"] is False and "JSON invalido" in res["error"]


def test_formato_no_reconocido(tmp_path):
    res = comfyui_import_workflow_json(_write(tmp_path, "x.json", {"foo": "bar"}))
    assert res["ok"] is False and "no reconocido" in res["error"]


def test_json_no_es_objeto(tmp_path):
    res = comfyui_import_workflow_json(_write(tmp_path, "lst.json", [1, 2, 3]))
    assert res["ok"] is False and "no es un objeto de workflow" in res["error"]


def test_archivo_inexistente(tmp_path):
    res = comfyui_import_workflow_json(str(tmp_path / "no.json"))
    assert res["ok"] is False and "no se pudo leer" in res["error"]


def test_determinista(tmp_path):
    path = _write(tmp_path, "api.json", _API)
    assert comfyui_import_workflow_json(path) == comfyui_import_workflow_json(path)
