#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""ComfyUI UI 格式工作流 → API 格式 prompt（官方 LMS 工作流专用转换器）

为什么需要它：ComfyUI 的 /prompt 只接受 API 格式，而官方仓库给的是 UI 格式
（前端画布格式）。本脚本做最小、可审计的等价转换：

1. **扁平化 cg-use-everywhere 的 Set/Get 虚拟连线**：GetNode(name) → 找到同名 SetNode
   → 其上游 (node, slot)。Reroute 直通。转换后 Set/Get/Reroute 节点全部消失。
2. **依赖闭包裁剪**：只保留指定输出节点（默认 #47 SaveVideo）的依赖闭包
   → 自动剔除官方图里的 GT/对比面板分支（VHS_VideoCombine、AddLabel、ImageConcatMulti 等）。
3. **widget → 输入名映射**：按 /object_info 的 schema 顺序把 widgets_values 映射到输入名。
4. **枚举值自愈**：若 widget 值不在枚举里（作者本机文件名与实机不同），
   按 basename 唯一匹配替换，并记录到 report（全部打印，便于审计）。
"""
from __future__ import annotations

import json
import urllib.request
from typing import Any

LINK_TYPES = {
    "MODEL", "CLIP", "VAE", "CONDITIONING", "LATENT", "IMAGE", "MASK", "AUDIO",
    "NOISE", "GUIDER", "SAMPLER", "SIGMAS", "VIDEO", "VHS_VIDEOINFO",
    "VHS_BATCH_MANAGER", "CLIP_VISION", "CONTROL_NET", "UPSCALE_MODEL",
    "STYLE_MODEL", "GLIGEN", "SIGMAS", "LATENT_UPSCALE", "WEBCAM",
}
UI_ONLY_TYPES = {"Note", "MarkdownNote", "Reroute", "PrimitiveNode"}


class SchemaCache:
    def __init__(self, comfy_url: str):
        self.url = comfy_url.rstrip("/")
        self.cache: dict[str, dict] = {}

    def get(self, class_type: str) -> dict:
        if class_type not in self.cache:
            with urllib.request.urlopen(f"{self.url}/object_info/{class_type}", timeout=30) as r:
                data = json.load(r)
            if class_type not in data:
                raise KeyError(f"节点类型未注册: {class_type}")
            self.cache[class_type] = data[class_type]
        return self.cache[class_type]

    def widget_names(self, class_type: str) -> list[str]:
        """按 schema 顺序返回 widget 输入名（排除纯连线输入与 autogrow）。"""
        info = self.get(class_type).get("input", {})
        names: list[str] = []
        for group in ("required", "optional"):
            for name, spec in (info.get(group) or {}).items():
                t = spec[0] if isinstance(spec, list) else spec
                if isinstance(t, str) and (t in LINK_TYPES or t.startswith("COMFY_AUTOGROW")):
                    continue
                if isinstance(t, dict):
                    continue
                names.append(name)
        return names

    def options(self, class_type: str, name: str) -> list | None:
        info = self.get(class_type).get("input", {})
        for group in ("required", "optional"):
            spec = (info.get(group) or {}).get(name)
            if spec:
                t = spec[0]
                if isinstance(t, list):
                    return t
                if isinstance(t, str) in (True, False) and t in ("COMBO", "COMFY_DYNAMICCOMBO_V3"):
                    opts = spec[1].get("options") if len(spec) > 1 and isinstance(spec[1], dict) else None
                    if opts and isinstance(opts[0], str):
                        return opts
                    if opts and isinstance(opts[0], dict):
                        return [o["key"] for o in opts]
                return None
        return None


def convert(workflow: dict, comfy_url: str, keep_outputs: list[int] | None = None,
            patches: dict[int, dict] | None = None) -> tuple[dict, list[str]]:
    """返回 (api_prompt, report)。"""
    report: list[str] = []
    sc = SchemaCache(comfy_url)
    patches = patches or {}
    nodes = {n["id"]: n for n in workflow["nodes"]}

    # ---- link 索引：link_id -> (src_node, src_slot)
    links: dict[int, tuple[int, int]] = {}
    for l in workflow.get("links", []):
        if isinstance(l, list) and len(l) >= 6:
            links[l[0]] = (l[1], l[2])
        elif isinstance(l, dict):
            links[l["id"]] = (l["origin_id"], l["origin_slot"])

    # ---- Set/Get 索引
    set_by_name: dict[str, tuple[int, int]] = {}   # name -> (src_node, src_slot)
    for nid, n in nodes.items():
        if n["type"] == "SetNode":
            name = (n.get("widgets_values") or ["?"])[0]
            inp = (n.get("inputs") or [{}])[0]
            lid = inp.get("link")
            if lid in links:
                set_by_name[name] = links[lid]

    def resolve(node_id: int, slot: int, depth: int = 0) -> tuple[int, int]:
        """把 Get/Reroute 链解开，返回真正的数据源 (node, slot)。"""
        if depth > 20:
            raise RuntimeError("Set/Get 解析过深（疑似环）")
        n = nodes[node_id]
        if n["type"] == "GetNode":
            name = (n.get("widgets_values") or ["?"])[0]
            if name not in set_by_name:
                raise RuntimeError(f"GetNode({name}) 找不到对应 SetNode")
            return resolve(*set_by_name[name], depth + 1)
        if n["type"] == "SetNode":
            # 有线直接连到 SetNode 的情况：SetNode 是直通，取它的上游
            inp = (n.get("inputs") or [{}])[0]
            lid = inp.get("link")
            if lid in links:
                return resolve(*links[lid], depth + 1)
            return (node_id, slot)
        if n["type"] == "Reroute":
            inp = (n.get("inputs") or [{}])[0]
            lid = inp.get("link")
            if lid in links:
                return resolve(*links[lid], depth + 1)
            return (node_id, slot)
        return (node_id, slot)

    # ---- 收集每个节点的输入（连线 + widget）
    def node_inputs(nid: int) -> dict[str, Any]:
        n = nodes[nid]
        ct = n["type"]
        vals: dict[str, Any] = {}
        # widget 按 schema 顺序吃 widgets_values
        wv = n.get("widgets_values")
        names = sc.widget_names(ct)
        if isinstance(wv, dict):
            for name in names:
                if name in wv:
                    vals[name] = wv[name]
        elif isinstance(wv, list):
            for name, v in zip(names, wv):
                vals[name] = v
            if len(wv) > len(names):
                report.append(f"  · #{nid} {ct}: widgets_values 比 schema 多 {len(wv)-len(names)} 项（已忽略尾部）")
        # 连线覆盖 widget
        for inp in n.get("inputs") or []:
            lid = inp.get("link")
            if lid is None or lid not in links:
                continue
            src_id, src_slot = resolve(*links[lid])
            vals[inp["name"]] = [str(src_id), src_slot]
        return vals

    # ---- 依赖闭包（从输出节点向上）
    if keep_outputs is None:
        keep_outputs = [n["id"] for n in workflow["nodes"] if n["type"] in ("SaveVideo", "VHS_VideoCombine")]
    need: set[int] = set()
    stack = [i for i in keep_outputs if i in nodes]
    while stack:
        nid = stack.pop()
        if nid in need:
            continue
        need.add(nid)
        n = nodes[nid]
        if n["type"] in UI_ONLY_TYPES:
            continue
        for inp in n.get("inputs") or []:
            lid = inp.get("link")
            if lid is not None and lid in links:
                s = resolve(*links[lid])[0]
                if s not in need:
                    stack.append(s)
        # Set 节点本身不在闭包里，但其上游已被 resolve 引入

    # ---- 组装 API prompt
    api: dict[str, dict] = {}
    for nid in sorted(need):
        n = nodes[nid]
        ct = n["type"]
        if ct in UI_ONLY_TYPES or ct in ("SetNode", "GetNode"):
            continue
        sc.get(ct)  # 未注册节点在这里直接报错
        vals = node_inputs(nid)
        # 补丁
        for k, v in (patches.get(nid) or {}).items():
            report.append(f"  · 补丁 #{nid} {ct}.{k}: {vals.get(k)!r} → {v!r}")
            vals[k] = v
        # 枚举自愈
        if ct != "VHS_LoadVideoFFmpeg":  # VHS 的文件名由补丁显式指定
            for k, v in list(vals.items()):
                if isinstance(v, list):
                    continue
                opts = sc.options(ct, k)
                if opts and v not in opts:
                    base = str(v).split("/")[-1].split("\\")[-1].lower()
                    cand = [o for o in opts if str(o).split("/")[-1].lower() == base]
                    if len(cand) == 1:
                        report.append(f"  · 枚举自愈 #{nid} {ct}.{k}: {v!r} → {cand[0]!r}")
                        vals[k] = cand[0]
                    else:
                        report.append(f"  !! 枚举无法自愈 #{nid} {ct}.{k}={v!r}（候选 {cand[:3]}）")
        api[str(nid)] = {"class_type": ct, "inputs": vals}

    report.append(f"闭包保留 {len(api)} 个节点（原图 {len(nodes)} 个），输出节点 {keep_outputs}")
    # 悬空引用检查：所有连线目标必须已在 api 里
    dangling = [(nid, k, v) for nid, n in api.items() for k, v in n["inputs"].items()
                if isinstance(v, list) and len(v) == 2 and str(v[0]) not in api]
    if dangling:
        raise RuntimeError(f"转换后有悬空连线（Set/Get 未完全扁平化）: {dangling[:5]}")
    report.append("悬空连线检查: 通过")
    report.append("保留节点类型: " + ", ".join(sorted({v['class_type'] for v in api.values()})))
    return api, report


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument("workflow")
    ap.add_argument("--comfy", default="http://192.168.31.31:8189")
    ap.add_argument("--keep", type=int, nargs="*", default=None)
    ap.add_argument("-o", "--out")
    a = ap.parse_args()
    wf = json.load(open(a.workflow, encoding="utf-8"))
    api, rep = convert(wf, a.comfy, a.keep)
    print("\n".join(rep))
    if a.out:
        json.dump({"prompt": api}, open(a.out, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
        print("wrote", a.out)
