#!/usr/bin/env python3
"""Patch PRISM2 expand workflows so video duration has a single entry.

Usage:
    python3 patch_prism2_timing.py <workflow_dir> [--dry-run]
    python3 patch_prism2_timing.py samples --suffix=-timing

The script reads every ``*.json`` workflow directly inside ``workflow_dir``
(not nested folders). It does not contact ComfyUI.

What a fresh workflow gains
---------------------------
* Node 61 ``H3Timing``. ``seconds`` defaults to the current
  ``MiniMaxH3ImageToVideo.length / 24``. ``fps`` defaults to the current
  ``CreateVideo`` fps widget so playback does not jump.
* Node 60 ``StringReplace``. Node 40's ``DURATION = <number> seconds`` line
  becomes ``DURATION = {duration} seconds``. ``{duration}`` is replaced by
  ``H3Timing.duration_text`` (``8.00``, without the unit word).
* ``20.length``, ``28.fps`` and ``49.duration`` are fed by node 61.
* Every link that used to leave node 40 (in the samples: ``42.replace`` and
  ``47.on_false``) is re-originated at node 60, so the placeholder cannot leak.
* ``CreateVideo`` widgets ``[24.0, 8]`` become ``[24.0]``. The ``8`` is the
  legacy value that the running graph parses as ``bit_depth=8``. The fps
  placeholder stays at index 0. An unlinked ``bit_depth`` input is removed
  with it so the node falls back to the combo default ``auto``.

Idempotency
-----------
A workflow that already contains both node 60 (StringReplace) and node 61
(H3Timing) is skipped and not rewritten. Running twice does not change bytes.

JSON rules this script follows (see 节点事实.md)
-----------------------------------------------
* A widget that becomes a wire keeps its ``widgets_values`` placeholder.
  The new or updated input is
  ``{"name", "type", "widget": {"name"}, "link"}``.
* ``links`` entries are 6-tuples
  ``[id, origin_id, origin_slot, target_id, target_slot, type]``.
* ``target_slot`` is the index of that input in the target node's ``inputs``.
* The origin output's ``links`` list and the target input's ``link`` both
  carry the same id.
* Existing input indices are not shifted, so old target slots stay valid.
  New widget inputs are appended.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import sys
from pathlib import Path


NODE_TIMING = 61
NODE_DURATION_REPLACE = 60

EXPECTED_TYPES = {
    20: "MiniMaxH3ImageToVideo",
    28: "CreateVideo",
    40: "PrimitiveStringMultiline",
    42: "StringReplace",
    47: "ComfySwitchNode",
    49: "H3PromptValidate",
}

# Widget order inside widgets_values, skipping pure sockets (clip, vae, image).
H3_WIDGETS = ("prompt", "width", "height", "length")

DURATION_RE = re.compile(r"DURATION\s*=\s*\d+(?:\.\d+)?\s*seconds")
DURATION_PLACEHOLDER = "DURATION = {duration} seconds"
NOTE_OLD = "**帧数**：17k+5（192 = 8.00 s，124 ≈ 5.17 s，73 ≈ 3.04 s）。"
NOTE_NEW = (
    "**帧数**：只改「时长入口（只改秒）」的 seconds。"
    "H3Timing 会把秒吸附到 17k+5 网格后，同时驱动 length、校验用秒数、"
    "提示词 DURATION 和 CreateVideo.fps（192 帧 = 8.00 s，124 帧 ≈ 5.17 s）。"
)


class PatchError(Exception):
    """The workflow cannot be patched safely. Nothing is written."""


def load_workflow(path: Path):
    raw = path.read_bytes()
    text = raw.decode("utf-8")
    newline = "\n" if text.endswith("\n") else ""
    data = json.loads(text)
    if not isinstance(data, dict) or "nodes" not in data or "links" not in data:
        raise PatchError("不是前端格式工作流（缺少 nodes/links）")
    return data, newline


def dump_workflow(data, newline: str) -> str:
    return json.dumps(data, ensure_ascii=False, indent=2) + newline


def atomic_write(path: Path, text: str) -> None:
    tmp = path.with_name(path.name + ".tmp")
    try:
        tmp.write_text(text, encoding="utf-8")
        os.replace(tmp, path)
    finally:
        if tmp.exists():
            tmp.unlink()


def node_map(graph) -> dict:
    found = {}
    for node in graph.get("nodes") or []:
        nid = node.get("id")
        if nid in found:
            raise PatchError("节点 id %s 重复" % nid)
        found[nid] = node
    return found


def classify(graph) -> str:
    """Return ``fresh``, ``patched`` or ``conflict`` from nodes 60 and 61."""
    nodes = node_map(graph)
    node60 = nodes.get(NODE_DURATION_REPLACE)
    node61 = nodes.get(NODE_TIMING)
    if node60 is None and node61 is None:
        return "fresh"
    if (
        node60 is not None
        and node61 is not None
        and node60.get("type") == "StringReplace"
        and node61.get("type") == "H3Timing"
    ):
        return "patched"
    return "conflict"


def input_slot(node, name: str):
    for index, item in enumerate(node.get("inputs") or []):
        if item.get("name") == name:
            return index
    return None


def ensure_widget_input(node, name: str, type_name: str) -> int:
    """Return the input index for ``name``, appending it if it is absent.

    Appending keeps every existing target_slot stable. A widget conversion
    must carry ``widget.name``; the widgets_values entry is left untouched.
    """
    slot = input_slot(node, name)
    if slot is None:
        node.setdefault("inputs", []).append({
            "name": name,
            "type": type_name,
            "widget": {"name": name},
            "link": None,
        })
        return len(node["inputs"]) - 1
    item = node["inputs"][slot]
    widget = item.get("widget")
    if not isinstance(widget, dict) or widget.get("name") != name:
        item["widget"] = {"name": name}
    if "type" not in item:
        item["type"] = type_name
    return slot


def set_input_link(node, slot: int, link_id: int) -> None:
    item = node["inputs"][slot]
    current = item.get("link")
    if current not in (None, link_id):
        raise PatchError(
            "节点 %s 的输入 %s 已经连到 link %s，拒绝覆盖"
            % (node.get("id"), item.get("name"), current)
        )
    item["link"] = link_id


def add_output_link(node, slot: int, link_id: int) -> None:
    outputs = node.get("outputs") or []
    if not 0 <= slot < len(outputs):
        raise PatchError("节点 %s 没有输出槽 %s" % (node.get("id"), slot))
    links = outputs[slot].get("links")
    if not isinstance(links, list):
        outputs[slot]["links"] = [link_id]
        return
    if link_id not in links:
        links.append(link_id)


def remove_output_link(node, slot: int, link_id: int) -> None:
    outputs = node.get("outputs") or []
    links = outputs[slot].get("links")
    if not isinstance(links, list):
        return
    outputs[slot]["links"] = [item for item in links if item != link_id]


def require_node(nodes, nid: int):
    node = nodes.get(nid)
    if node is None:
        raise PatchError("缺少节点 %s (%s)" % (nid, EXPECTED_TYPES[nid]))
    expected = EXPECTED_TYPES[nid]
    if node.get("type") != expected:
        raise PatchError(
            "节点 %s 类型是 %s，期望 %s" % (nid, node.get("type"), expected)
        )
    return node


def widget_value(node, widget_names, widget_name: str):
    if widget_name not in widget_names:
        raise PatchError("内部错误：未知 widget %s" % widget_name)
    index = widget_names.index(widget_name)
    values = node.get("widgets_values") or []
    if index >= len(values):
        raise PatchError(
            "节点 %s 的 widgets_values 长度 %s，读不到 %s（下标 %s）"
            % (node.get("id"), len(values), widget_name, index)
        )
    return values[index]


def rewrite_duration_text(text: str) -> str:
    if not isinstance(text, str):
        raise PatchError("节点 40 的文本不是字符串")
    if DURATION_RE.search(text):
        return DURATION_RE.sub(DURATION_PLACEHOLDER, text)
    if DURATION_PLACEHOLDER in text:
        return text
    raise PatchError(
        "节点 40 里没有 `DURATION = <数字> seconds`，也没有已经改好的占位符"
    )


def align_target_slots(graph) -> list:
    """Make each link's target_slot equal the input that already holds its id.

    Some copied graphs keep the old slot number in ``links`` after an input
    was removed (the 讯飞 4B sample's links 4 and 5). ``inputs[i].link`` is
    the connection the node actually stores. Rewriting the tuple to that
    index does not change which named input is wired, and it satisfies the
    rule that target_slot is the inputs-array index.
    """
    nodes = node_map(graph)
    notes = []
    for link in graph.get("links") or []:
        if not isinstance(link, list) or len(link) != 6:
            continue
        link_id, _origin, _origin_slot, target, target_slot, _typ = link
        node = nodes.get(target)
        if node is None:
            continue
        owners = [
            index
            for index, item in enumerate(node.get("inputs") or [])
            if item.get("link") == link_id
        ]
        if len(owners) == 1 and owners[0] != target_slot:
            name = (node.get("inputs") or [])[owners[0]].get("name")
            notes.append(
                "link %s target_slot %s -> %s（节点 %s 输入 %s，inputs[].link 未改）"
                % (link_id, target_slot, owners[0], target, name)
            )
            link[4] = owners[0]
    return notes


def clean_createvideo(node) -> dict:
    """Drop the legacy second widget value ``8`` and keep the fps placeholder.

    Only the exact ``[fps, 8]`` shape is rewritten. A longer list is refused
    so later combo values cannot slide into the bit_depth slot.
    """
    values = list(node.get("widgets_values") or [])
    if not values or isinstance(values[0], bool) or not isinstance(values[0], (int, float)):
        raise PatchError("节点 28 CreateVideo 读不到 fps widget")
    fps = float(values[0])
    if fps <= 0:
        raise PatchError("节点 28 CreateVideo 的 fps 不是正数：%s" % values[0])
    note = "fps 占位 %s 保留" % values[0]
    if len(values) == 1:
        return {"fps": fps, "widgets_before": values, "widgets_after": values, "note": note}
    if len(values) == 2 and type(values[1]) is int and values[1] == 8:
        node["widgets_values"] = [values[0]]
        removed = _drop_unlinked_input(node, "bit_depth")
        named = node.get("widgets_values_named")
        if isinstance(named, dict) and named.get("bit_depth") == 8:
            named.pop("bit_depth", None)
        extra = "，并移除未连线的 bit_depth 输入" if removed else "，bit_depth 输入仍保留（有连线或未找到）"
        return {
            "fps": fps,
            "widgets_before": values,
            "widgets_after": list(node["widgets_values"]),
            "note": "widgets_values %s -> %s（清掉残留 bit_depth=8）%s" % (
                values, node["widgets_values"], extra,
            ),
        }
    raise PatchError(
        "节点 28 widgets_values 是 %s，不是已知的 [fps, 8]，拒绝改写以免错位" % values
    )


def _drop_unlinked_input(node, name: str) -> bool:
    inputs = node.get("inputs") or []
    slot = input_slot(node, name)
    if slot is None:
        return False
    if inputs[slot].get("link") not in (None,):
        return False
    # Only drop a tail input. Removing a middle slot would renumber later wires.
    if slot != len(inputs) - 1:
        return False
    del inputs[slot]
    return True


def next_link_id(graph) -> int:
    highest = int(graph.get("last_link_id") or 0)
    for link in graph.get("links") or []:
        if isinstance(link, list) and link and isinstance(link[0], int):
            highest = max(highest, link[0])
    return highest


def add_link(graph, origin, origin_slot, target, target_slot, type_name: str) -> int:
    graph["_next_link_id"] = int(graph.get("_next_link_id") or next_link_id(graph)) + 1
    link_id = graph["_next_link_id"]
    graph["links"].append([link_id, origin, origin_slot, target, target_slot, type_name])
    add_output_link(node_map(graph)[origin], origin_slot, link_id)
    set_input_link(node_map(graph)[target], target_slot, link_id)
    return link_id


def rewire_away_from_user_prompt(graph, user_node, duration_node) -> list:
    """Point every consumer of node 40 at node 60, except the new 40 -> 60 wire."""
    notes = []
    user_id = user_node["id"]
    duration_id = duration_node["id"]
    for link in graph["links"]:
        link_id, origin, origin_slot, target, target_slot, type_name = link
        if origin != user_id or origin_slot != 0 or target == duration_id:
            continue
        remove_output_link(user_node, origin_slot, link_id)
        link[1] = duration_id
        link[2] = 0
        add_output_link(duration_node, 0, link_id)
        target_node = node_map(graph)[target]
        target_name = target_node["inputs"][target_slot].get("name")
        notes.append(
            "link %s：源 %s:%s -> %s:0，目标仍是 %s:%s %s (%s)"
            % (link_id, user_id, origin_slot, duration_id, target, target_slot, target_name, type_name)
        )
    return notes


def update_note(graph) -> str:
    for node in graph["nodes"]:
        if node.get("type") != "MarkdownNote":
            continue
        values = node.get("widgets_values") or []
        if not values or not isinstance(values[0], str):
            continue
        if NOTE_OLD not in values[0]:
            continue
        values[0] = values[0].replace(NOTE_OLD, NOTE_NEW)
        node["widgets_values"] = values
        return "节点 %s 说明里的帧数句子已指向时长入口" % node.get("id")
    return "说明便签没有那句旧的帧数文字，未改"


def build_timing_node(seconds: float, fps: float, order: int) -> dict:
    return {
        "id": NODE_TIMING,
        "type": "H3Timing",
        "pos": [-980, -220],
        "size": [420, 200],
        "flags": {},
        "order": order,
        "mode": 0,
        "inputs": [],
        "outputs": [
            {"name": "length", "type": "INT", "links": [], "slot_index": 0},
            {"name": "fps", "type": "FLOAT", "links": [], "slot_index": 1},
            {"name": "seconds", "type": "FLOAT", "links": [], "slot_index": 2},
            {"name": "duration_text", "type": "STRING", "links": [], "slot_index": 3},
        ],
        "properties": {"Node name for S&R": "H3Timing"},
        "widgets_values": [seconds, fps, True, True],
        "widgets_values_named": {
            "seconds": seconds,
            "fps": fps,
            "snap_17k5": True,
            "clamp_trained": True,
        },
        "title": "时长入口（只改秒）",
        "color": "#232",
        "bgcolor": "#353",
    }


def build_duration_replace_node(order: int) -> dict:
    # string and replace are linked widgets. Their placeholders stay in
    # widgets_values so the frontend keeps positional alignment:
    # [string, find, replace]. ``find`` is not an input because it is not wired.
    return {
        "id": NODE_DURATION_REPLACE,
        "type": "StringReplace",
        "pos": [-900, 430],
        "size": [380, 140],
        "flags": {},
        "order": order,
        "mode": 0,
        "inputs": [
            {
                "localized_name": "string",
                "name": "string",
                "type": "STRING",
                "widget": {"name": "string"},
                "link": None,
            },
            {
                "localized_name": "replace",
                "name": "replace",
                "type": "STRING",
                "widget": {"name": "replace"},
                "link": None,
            },
        ],
        "outputs": [
            {
                "localized_name": "STRING",
                "name": "STRING",
                "type": "STRING",
                "links": [],
                "slot_index": 0,
            }
        ],
        "properties": {"Node name for S&R": "StringReplace"},
        "widgets_values": ["", "{duration}", ""],
        "widgets_values_named": {
            "string": "",
            "find": "{duration}",
            "replace": "",
        },
        "title": "填入时长（StringReplace）",
    }


def patch_graph(graph) -> dict:
    """Mutate ``graph`` in memory. Raise ``PatchError`` before returning on failure."""
    nodes = node_map(graph)
    for nid in EXPECTED_TYPES:
        require_node(nodes, nid)
    if not isinstance(graph.get("links"), list):
        raise PatchError("links 不是数组")

    slot_notes = align_target_slots(graph)
    nodes = node_map(graph)

    h3 = nodes[20]
    video = nodes[28]
    user = nodes[40]
    template_fill = nodes[42]
    switch = nodes[47]
    validate = nodes[49]

    length = widget_value(h3, H3_WIDGETS, "length")
    if isinstance(length, bool) or not isinstance(length, (int, float)):
        raise PatchError("节点 20 的 length 不是数字：%s" % (length,))
    if int(length) != length:
        raise PatchError("节点 20 的 length 不是整数：%s" % (length,))
    length = int(length)
    seconds = length / 24.0

    user_values = list(user.get("widgets_values") or [])
    if not user_values:
        raise PatchError("节点 40 没有 widgets_values")
    rewritten = rewrite_duration_text(user_values[0])
    user_values[0] = rewritten
    user["widgets_values"] = user_values
    named = user.get("widgets_values_named")
    if isinstance(named, dict) and isinstance(named.get("value"), str) and DURATION_RE.search(named["value"]):
        named["value"] = rewrite_duration_text(named["value"])

    video_note = clean_createvideo(video)
    fps = video_note["fps"]
    if abs(fps - 24.0) > 1e-6:
        video_note["note"] += "；警告：当前 fps 不是 24，seconds 仍按 length/24 填写，第一次运行可能会改帧数"

    length_slot = ensure_widget_input(h3, "length", "INT")
    fps_slot = ensure_widget_input(video, "fps", "FLOAT")
    duration_slot = ensure_widget_input(validate, "duration", "FLOAT")
    # Re-resolve after potential append. ensure_widget_input does not insert
    # in the middle, so previously recorded slots of other inputs stay put.
    if input_slot(template_fill, "replace") is None or input_slot(switch, "on_false") is None:
        raise PatchError("节点 42.replace 或 47.on_false 不存在")
    if input_slot(user, "STRING") is not None:
        raise PatchError("节点 40 出现了意外的输入")
    user_outputs = user.get("outputs") or []
    if not user_outputs:
        raise PatchError("节点 40 没有输出")

    orders = [int(node.get("order") or 0) for node in graph["nodes"]]
    next_order = max(orders) + 1 if orders else 0
    timing = build_timing_node(seconds, fps, next_order)
    duration = build_duration_replace_node(next_order + 1)
    graph["nodes"].append(timing)
    graph["nodes"].append(duration)
    nodes = node_map(graph)

    graph["_next_link_id"] = next_link_id(graph)
    added = []

    def record(link_id, origin, origin_slot, target, target_slot, type_name):
        added.append(
            "link %s：%s:%s -> %s:%s %s"
            % (link_id, origin, origin_slot, target, target_slot, type_name)
        )

    link_user = add_link(graph, 40, 0, NODE_DURATION_REPLACE, 0, "STRING")
    record(link_user, 40, 0, NODE_DURATION_REPLACE, 0, "STRING")
    link_text = add_link(graph, NODE_TIMING, 3, NODE_DURATION_REPLACE, 1, "STRING")
    record(link_text, NODE_TIMING, 3, NODE_DURATION_REPLACE, 1, "STRING")
    link_length = add_link(graph, NODE_TIMING, 0, 20, length_slot, "INT")
    record(link_length, NODE_TIMING, 0, 20, length_slot, "INT")
    link_fps = add_link(graph, NODE_TIMING, 1, 28, fps_slot, "FLOAT")
    record(link_fps, NODE_TIMING, 1, 28, fps_slot, "FLOAT")
    link_seconds = add_link(graph, NODE_TIMING, 2, 49, duration_slot, "FLOAT")
    record(link_seconds, NODE_TIMING, 2, 49, duration_slot, "FLOAT")

    rewired = rewire_away_from_user_prompt(graph, nodes[40], nodes[NODE_DURATION_REPLACE])
    if not rewired:
        raise PatchError("节点 40 没有任何下游可改接到节点 60")
    targets = {(link[3], link[4]) for link in graph["links"] if link[1] == NODE_DURATION_REPLACE}
    replace_slot = input_slot(nodes[42], "replace")
    false_slot = input_slot(nodes[47], "on_false")
    if (42, replace_slot) not in targets or (47, false_slot) not in targets:
        raise PatchError("42.replace 或 47.on_false 没有改接到节点 60")

    note = update_note(graph)
    highest_node = max(int(node["id"]) for node in graph["nodes"])
    graph["last_node_id"] = max(int(graph.get("last_node_id") or 0), highest_node)
    graph["last_link_id"] = max(int(graph.get("last_link_id") or 0), int(graph["_next_link_id"]))
    graph.pop("_next_link_id", None)

    problems = audit_graph(graph)
    problems.extend(audit_patch_contract(graph, length, seconds, fps))
    if problems:
        raise PatchError("自检失败：\n  " + "\n  ".join(problems))

    return {
        "seconds": seconds,
        "length": length,
        "fps": fps,
        "added": added,
        "rewired": rewired,
        "slot_repairs": slot_notes,
        "video": video_note["note"],
        "note": note,
        "nodes": len(graph["nodes"]),
        "links": len(graph["links"]),
    }


def audit_graph(graph) -> list:
    """Strict structural audit. Empty list means the graph is internally consistent."""
    errors = []
    nodes = {}
    for node in graph.get("nodes") or []:
        nid = node.get("id")
        if not isinstance(nid, int):
            errors.append("节点 id 不是 int：%r" % (nid,))
            continue
        if nid in nodes:
            errors.append("节点 id 重复：%s" % nid)
        nodes[nid] = node

    seen_links = {}
    for link in graph.get("links") or []:
        if not isinstance(link, list) or len(link) != 6:
            errors.append("link 不是 6 元组：%r" % (link,))
            continue
        link_id, origin, origin_slot, target, target_slot, type_name = link
        if not isinstance(link_id, int):
            errors.append("link id 不是 int：%r" % (link_id,))
            continue
        if link_id in seen_links:
            errors.append("link id 重复：%s" % link_id)
        seen_links[link_id] = link
        if not isinstance(type_name, str) or not type_name:
            errors.append("link %s 缺少类型" % link_id)
        origin_node = nodes.get(origin)
        target_node = nodes.get(target)
        if origin_node is None:
            errors.append("link %s 源节点 %s 不存在" % (link_id, origin))
        if target_node is None:
            errors.append("link %s 目标节点 %s 不存在" % (link_id, target))
        if origin_node is not None:
            outputs = origin_node.get("outputs") or []
            if not isinstance(origin_slot, int) or not 0 <= origin_slot < len(outputs):
                errors.append(
                    "link %s 源槽 %s 超出节点 %s 的 outputs（%s）"
                    % (link_id, origin_slot, origin, len(outputs))
                )
            else:
                origin_links = outputs[origin_slot].get("links") or []
                if link_id not in origin_links:
                    errors.append(
                        "link %s 不在源节点 %s 输出 %s 的 links %s 里"
                        % (link_id, origin, origin_slot, origin_links)
                    )
        if target_node is not None:
            inputs = target_node.get("inputs") or []
            if not isinstance(target_slot, int) or not 0 <= target_slot < len(inputs):
                errors.append(
                    "link %s 目标槽 %s 超出节点 %s 的 inputs（%s）"
                    % (link_id, target_slot, target, len(inputs))
                )
            else:
                bound = inputs[target_slot].get("link")
                if bound != link_id:
                    errors.append(
                        "link %s 目标节点 %s 输入 %s 的 link 是 %s"
                        % (link_id, target, target_slot, bound)
                    )

    claimed = {}
    for nid, node in nodes.items():
        for index, item in enumerate(node.get("inputs") or []):
            link_id = item.get("link")
            if link_id in (None,):
                continue
            if link_id not in seen_links:
                errors.append("节点 %s 输入 %s 引用了不存在的 link %s" % (nid, index, link_id))
                continue
            link = seen_links[link_id]
            if link[3] != nid or link[4] != index:
                errors.append(
                    "节点 %s 输入 %s 的 link %s 在 links 里指向 %s:%s"
                    % (nid, index, link_id, link[3], link[4])
                )
            if link_id in claimed:
                errors.append("link %s 被两个输入同时占用" % link_id)
            claimed[link_id] = (nid, index)
        for index, item in enumerate(node.get("outputs") or []):
            for link_id in item.get("links") or []:
                if link_id not in seen_links:
                    errors.append("节点 %s 输出 %s 引用了不存在的 link %s" % (nid, index, link_id))
                    continue
                link = seen_links[link_id]
                if link[1] != nid or link[2] != index:
                    errors.append(
                        "节点 %s 输出 %s 的 link %s 在 links 里源是 %s:%s"
                        % (nid, index, link_id, link[1], link[2])
                    )
    return errors


def _widget_input(node, name: str):
    slot = input_slot(node, name)
    if slot is None:
        return None, None
    return slot, node["inputs"][slot]


def audit_patch_contract(graph, length: int, seconds: float, fps: float) -> list:
    """The timing patch's own invariants, including widget placeholders."""
    errors = []
    nodes = node_map(graph)
    timing = nodes.get(NODE_TIMING)
    duration = nodes.get(NODE_DURATION_REPLACE)
    if timing is None or timing.get("type") != "H3Timing":
        errors.append("缺少 61 H3Timing")
        return errors
    if duration is None or duration.get("type") != "StringReplace":
        errors.append("缺少 60 StringReplace")
        return errors

    timing_values = timing.get("widgets_values") or []
    if len(timing_values) != 4:
        errors.append("H3Timing widgets_values 应为 [seconds, fps, snap, clamp]，实际 %s" % timing_values)
    else:
        if timing_values[0] != seconds:
            errors.append("H3Timing.seconds 占位 %s != %s" % (timing_values[0], seconds))
        if float(timing_values[1]) != float(fps):
            errors.append("H3Timing.fps 占位 %s != %s" % (timing_values[1], fps))
        if timing_values[2] is not True or timing_values[3] is not True:
            errors.append("H3Timing 的 snap/clamp 应为 true/true，实际 %s" % timing_values[2:])

    duration_values = duration.get("widgets_values") or []
    if duration_values != ["", "{duration}", ""]:
        errors.append(
            "节点 60 widgets_values 应为 ['', '{duration}', '']（连线占位保留），实际 %s"
            % duration_values
        )
    for widget_name in ("string", "replace"):
        _slot, item = _widget_input(duration, widget_name)
        if item is None or not isinstance(item.get("widget"), dict) or item["widget"].get("name") != widget_name:
            errors.append("节点 60 输入 %s 缺少 widget.name" % widget_name)
        elif item.get("link") in (None,):
            errors.append("节点 60 输入 %s 没有连线" % widget_name)

    h3 = nodes[20]
    h3_values = h3.get("widgets_values") or []
    if len(h3_values) < 4 or h3_values[3] != length:
        errors.append("节点 20 length 占位被改掉了：%s" % h3_values)
    _slot, length_input = _widget_input(h3, "length")
    if length_input is None or length_input.get("widget", {}).get("name") != "length":
        errors.append("节点 20.length 不是带 widget.name 的输入")
    elif _link_origin(graph, length_input.get("link")) != (NODE_TIMING, 0, "INT"):
        errors.append("节点 20.length 不是来自 H3Timing.length")

    video = nodes[28]
    video_values = video.get("widgets_values") or []
    if not video_values or isinstance(video_values[0], bool) or float(video_values[0]) != float(fps):
        errors.append("节点 28 fps 占位丢失：%s" % video_values)
    if len(video_values) != 1:
        errors.append("节点 28 widgets_values 清理后应为 [fps]，实际 %s" % video_values)
    _slot, fps_input = _widget_input(video, "fps")
    if fps_input is None or fps_input.get("widget", {}).get("name") != "fps":
        errors.append("节点 28.fps 不是带 widget.name 的输入")
    elif _link_origin(graph, fps_input.get("link")) != (NODE_TIMING, 1, "FLOAT"):
        errors.append("节点 28.fps 不是来自 H3Timing.fps")

    validate = nodes[49]
    validate_values = validate.get("widgets_values") or []
    if len(validate_values) < 1 or isinstance(validate_values[0], bool) or not isinstance(validate_values[0], (int, float)):
        errors.append("节点 49.duration 占位丢失：%s" % validate_values)
    _slot, duration_input = _widget_input(validate, "duration")
    if duration_input is None or duration_input.get("widget", {}).get("name") != "duration":
        errors.append("节点 49.duration 不是带 widget.name 的输入")
    elif _link_origin(graph, duration_input.get("link")) != (NODE_TIMING, 2, "FLOAT"):
        errors.append("节点 49.duration 不是来自 H3Timing.seconds")
    prompt_slot = input_slot(validate, "prompt")
    if prompt_slot != 0:
        errors.append("节点 49 的 prompt 槽被挤动到了 %s" % prompt_slot)

    user_text = (nodes[40].get("widgets_values") or [""])[0]
    if DURATION_PLACEHOLDER not in user_text or DURATION_RE.search(user_text):
        errors.append("节点 40 的 DURATION 行没有收成占位符")
    user_links = (nodes[40].get("outputs") or [{}])[0].get("links") or []
    if len(user_links) != 1:
        errors.append("节点 40 应只连向节点 60，实际 links %s" % user_links)
    else:
        origin = _link_record(graph, user_links[0])
        if origin is None or origin[1] != 40 or origin[3] != NODE_DURATION_REPLACE or origin[4] != 0:
            errors.append("节点 40 的唯一输出没有进节点 60.string")

    fill_values = nodes[42].get("widgets_values") or []
    if len(fill_values) != 3 or fill_values[1] != "{input text}":
        errors.append("节点 42 的 find 占位被改掉了：%s" % fill_values)
    replace_link = (nodes[42]["inputs"][input_slot(nodes[42], "replace")]).get("link")
    if _link_origin(graph, replace_link) != (NODE_DURATION_REPLACE, 0, "STRING"):
        errors.append("节点 42.replace 没有来自节点 60")
    false_link = (nodes[47]["inputs"][input_slot(nodes[47], "on_false")]).get("link")
    if _link_origin(graph, false_link) != (NODE_DURATION_REPLACE, 0, "STRING"):
        errors.append("节点 47.on_false 没有来自节点 60")
    text_link = duration["inputs"][input_slot(duration, "replace")].get("link")
    if _link_origin(graph, text_link) != (NODE_TIMING, 3, "STRING"):
        errors.append("节点 60.replace 没有来自 H3Timing.duration_text")
    return errors


def _link_record(graph, link_id):
    for link in graph.get("links") or []:
        if link[0] == link_id:
            return link
    return None


def _link_origin(graph, link_id):
    link = _link_record(graph, link_id)
    if link is None:
        return None
    return (link[1], link[2], link[5])


def format_summary(name: str, summary: dict, dry_run: bool) -> str:
    lines = [
        "[%s] %s" % ("dry-run" if dry_run else "patched", name),
        "  节点 %s，link %s；H3Timing.seconds 默认 %s（length %s / 24），fps %s"
        % (summary["nodes"], summary["links"], _num(summary["seconds"]), summary["length"], _num(summary["fps"])),
        "  新增节点：60 StringReplace，61 H3Timing",
    ]
    for item in summary["added"]:
        lines.append("  新增 " + item)
    for item in summary["rewired"]:
        lines.append("  改写 " + item)
    for item in summary["slot_repairs"]:
        lines.append("  对齐 " + item)
    lines.append("  CreateVideo：" + summary["video"])
    lines.append("  " + summary["note"])
    lines.append("  自检：通过（link 无悬空，节点/link id 无冲突，widget 占位仍在）")
    return "\n".join(lines)


def _num(value: float) -> str:
    if isinstance(value, float) and value.is_integer():
        return "%.1f" % value
    return repr(value)


def iter_workflows(directory: Path, suffix: str):
    files = []
    for path in sorted(directory.glob("*.json")):
        if not path.is_file():
            continue
        if suffix and path.stem.endswith(suffix):
            continue
        files.append(path)
    return files


def destination_for(path: Path, suffix: str) -> Path:
    if not suffix:
        return path
    return path.with_name(path.stem + suffix + path.suffix)


def process_file(path: Path, suffix: str, dry_run: bool) -> str:
    dest = destination_for(path, suffix)
    if suffix and dest.exists():
        existing, _newline = load_workflow(dest)
        state = classify(existing)
        if state == "patched":
            return "[skip] %s 已有 60 StringReplace 与 61 H3Timing，不重写" % dest.name
        if state == "conflict":
            raise PatchError("%s 已占用节点 60 或 61，但不是本脚本的改造结果" % dest.name)
        raise PatchError("%s 已存在且尚未完成本改造，拒绝覆盖" % dest.name)

    graph, newline = load_workflow(path)
    state = classify(graph)
    if state == "patched":
        return "[skip] %s 已有 60 StringReplace 与 61 H3Timing，不重写" % path.name
    if state == "conflict":
        raise PatchError("%s 已占用节点 60 或 61，但不是本脚本的改造结果" % path.name)

    before_nodes = len(graph["nodes"])
    before_links = len(graph["links"])
    summary = patch_graph(graph)
    summary["before_nodes"] = before_nodes
    summary["before_links"] = before_links
    text = format_summary(dest.name, summary, dry_run)
    if not dry_run:
        atomic_write(dest, dump_workflow(graph, newline))
    return text


def normalize_argv(argv):
    """Glue ``--suffix -timing`` into ``--suffix=-timing`` before argparse runs.

    A suffix that starts with ``-`` would otherwise be parsed as a new flag.
    """
    out = []
    index = 0
    while index < len(argv):
        token = argv[index]
        if token == "--suffix" and index + 1 < len(argv):
            out.append("--suffix=" + argv[index + 1])
            index += 2
            continue
        out.append(token)
        index += 1
    return out


def parse_args(argv):
    parser = argparse.ArgumentParser(description="把 PRISM2 扩写工作流的时长收成 H3Timing 单一入口")
    parser.add_argument("workflow_dir", help="放着工作流 JSON 的目录（只处理这一层）")
    parser.add_argument("--dry-run", action="store_true", help="只打印会改什么，不写文件")
    parser.add_argument(
        "--suffix",
        default="",
        help="写到 <原名><suffix>.json，不覆盖源文件。样本用 --suffix=-timing",
    )
    return parser.parse_args(normalize_argv(list(argv)))


def main(argv=None) -> int:
    args = parse_args(sys.argv[1:] if argv is None else argv)
    directory = Path(args.workflow_dir).expanduser().resolve()
    if not directory.is_dir():
        print("目录不存在：%s" % directory, file=sys.stderr)
        return 1
    suffix = args.suffix or ""
    files = iter_workflows(directory, suffix)
    if not files:
        print("目录里没有可处理的工作流 JSON：%s" % directory, file=sys.stderr)
        return 1

    failed = 0
    for path in files:
        try:
            print(process_file(path, suffix, args.dry_run))
        except (PatchError, UnicodeError, json.JSONDecodeError, OSError) as exc:
            failed += 1
            print("[fail] %s\n  %s" % (path.name, exc))
    if args.dry_run:
        mode = "dry-run，未写文件"
    elif failed:
        mode = "失败的文件未写入"
    else:
        mode = "已处理"
    print("合计 %s 份，失败 %s 份（%s）" % (len(files), failed, mode))
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())
