#!/usr/bin/env python3
"""
把 9 套排查流程图 JSON 合并到一个数组,输出 00-all.json(便于一次性 import)。
用法:python build_all.py
"""
import json
import glob
import os
import sys
from pathlib import Path

HERE = Path(__file__).parent

def main():
    # 1. 找 9 个单文件(排除 00-all.json 和 build_all.py)
    files = sorted(HERE.glob("[0-9][0-9]-*.json"))
    if not files:
        print("❌ 没找到任何 0X-*.json 文件")
        sys.exit(1)

    print(f"📦 找到 {len(files)} 个模板文件:")
    for f in files:
        print(f"   - {f.name}")

    # 2. 逐个读 + 校验
    templates = []
    for f in files:
        try:
            with open(f, "r", encoding="utf-8") as fp:
                tpl = json.load(fp)
            # 简单校验
            for required in ("name", "category", "root_node"):
                if required not in tpl:
                    raise ValueError(f"缺少必要字段: {required}")
            templates.append(tpl)
            print(f"   ✅ {f.name}: {tpl['name']} ({len(json.dumps(tpl, ensure_ascii=False))} 字符)")
        except Exception as e:
            print(f"   ❌ {f.name}: {e}")
            sys.exit(1)

    # 3. 输出汇总文件
    out = HERE / "00-all.json"
    with open(out, "w", encoding="utf-8") as fp:
        json.dump(templates, fp, ensure_ascii=False, indent=2)

    print(f"\n✅ 已生成 {out.name} (共 {len(templates)} 套)")
    print(f"\n💡 接下来你可以:")
    print(f"   1. 打开 {out.name} 预览 9 套完整内容")
    print(f"   2. 在 Admin 后台的「排查流程图」页 → 「导入 JSON」选择此文件")
    print(f"   3. 或调用后端 API:")
    print(f"      for tpl in templates: POST /api/troubleshooting-templates")

if __name__ == "__main__":
    main()
