"""Test workflow_llm_to_image.json — same converter, validation-only (don't run heavy image gen)."""
import json, urllib.request, urllib.error, uuid

COMFY = "http://127.0.0.1:8188"
WF_PATH = r"D:\Comfy\App\ComfyUI_windows_portable\ComfyUI\custom_nodes\ComfyUI-MusicVideoDirector\workflow_llm_to_image.json"

def http_json(method, path, body=None):
    url = COMFY + path
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, method=method,
                                  headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            return r.status, json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read().decode())

wf_ui = json.load(open(WF_PATH, encoding="utf-8"))
obj_info = json.load(open(r"D:\Comfy\object_info.json", encoding="utf-8"))
links_by_id = {l[0]: l for l in wf_ui["links"]}

print("=== Workflow nodes ===")
for n in wf_ui["nodes"]:
    print(f"  [{n['id']}] {n['type']}  mode={n.get('mode',0)}  widgets={len(n.get('widgets_values') or [])}")

def convert(wf_ui, mute_ids=set()):
    api = {}
    for n in wf_ui["nodes"]:
        nid = n["id"]
        if n.get("mode") == 2 or nid in mute_ids:
            continue
        ctype = n["type"]
        if ctype == "Note":
            continue
        if ctype not in obj_info:
            print(f"  ! Unknown class_type: {ctype}")
            continue
        schema = obj_info[ctype]["input"]
        all_inputs = list(schema.get("required", {}).keys()) + list(schema.get("optional", {}).keys())
        link_inputs = {}
        widget_converted = set()
        for inp in n.get("inputs", []) or []:
            if inp.get("widget"):
                widget_converted.add(inp["name"])
            if inp.get("link") is not None:
                lk = links_by_id.get(inp["link"])
                if lk:
                    link_inputs[inp["name"]] = [str(lk[1]), lk[2]]
        widgets = list(n.get("widgets_values", []) or [])
        widget_idx = 0
        inputs = {}
        CONTROL_VALS = {"fixed", "randomize", "increment", "decrement"}
        for name in all_inputs:
            if name in link_inputs:
                inputs[name] = link_inputs[name]
                if name in widget_converted and widget_idx < len(widgets):
                    widget_idx += 1
            else:
                if widget_idx < len(widgets):
                    inputs[name] = widgets[widget_idx]
                    widget_idx += 1
                    # Skip phantom control_after_generate widget for seed-like INT
                    if (widget_idx < len(widgets)
                            and isinstance(widgets[widget_idx], str)
                            and widgets[widget_idx] in CONTROL_VALS):
                        widget_idx += 1
        api[str(nid)] = {"class_type": ctype, "inputs": inputs}
    return api

api_wf = convert(wf_ui)
print(f"\n=== Converted {len(api_wf)} nodes ===")
client_id = str(uuid.uuid4())
status, resp = http_json("POST", "/prompt", {"prompt": api_wf, "client_id": client_id})
print(f"HTTP {status}")
print(json.dumps(resp, indent=2, ensure_ascii=False)[:5000])
