#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""archive-all.py — 把《九九八十一》MV 可爱版全部产出归档进 ComfyUI 相册（http://192.168.31.76:8900）。

规则（用户 2026-09-14 起的要求）：即梦 CLI 出的图除落 dl-hub 外，也必须进相册，并补写
family/models/prompt/params 元数据；H3 片段本就在 GPU 机 ComfyUI/output 下，由 sync-agent 自动收录。
"""
import json, os, subprocess, sys, tempfile
from pathlib import Path

ROOT = Path("/home/zyw/Downloads/dl-hub/54-九九八十一MV")
GALLERY_ADD = Path("/home/zyw/Downloads/gallery-add.sh")
SUBDIR = "jj81-mv"
FAMILY = "即梦 5.0（Seedream 5.0）"
MODEL = "5.0"

MANIFESTS = [
    ("01-风格测试-可爱版.json", "风格测试（可爱版）"),
    ("02-人物设定-可爱版.json", "人物设定（可爱版·师徒与仙佛）"),
    ("03-妖怪设定-可爱版.json", "妖怪设定（可爱版·已全部萌化无恐怖元素）"),
    ("04-场景设定-可爱版.json", "场景设定（可爱版）"),
    ("分镜关键帧-可爱版.json", "分镜关键帧（可爱版·逐镜参考图）"),
]
VIDEOS = [
    ("07-成片/九九八十一-可爱版-MV-v1.mp4", "成片：全片 MV（1920×1080 / 236.84s / 原曲+简体字幕）", "H3 官方工作流 + 即梦"),
    ("07-成片/九九八十一-可爱版-预演版.mp4", "预演版：静态分镜预演（审节奏用）", "静帧运镜版"),
]


def add(files, prompt, note, family=FAMILY, model=MODEL):
    with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as f:
        f.write(prompt)
        pf = f.name
    cmd = ["bash", str(GALLERY_ADD), "--subdir", SUBDIR, "--family", family, "--model", model,
           "--credit", "0", "--prompt-file", pf, "--note", note] + [str(x) for x in files]
    r = subprocess.run(cmd, capture_output=True, text=True)
    os.unlink(pf)
    return r.returncode == 0, (r.stdout or r.stderr).strip().splitlines()[-1:] or [""]


def main():
    only = sys.argv[1] if len(sys.argv) > 1 else None
    n_ok = n_fail = 0
    for mf, note in MANIFESTS:
        p = ROOT / "prompts" / mf
        if not p.exists():
            continue
        items = json.load(open(p, encoding="utf-8"))
        print(f"=== {mf}（{len(items)} 张）", flush=True)
        for it in items:
            img = ROOT / it["outdir"] / (it["name"] + ".png")
            if not img.exists():
                print("  跳过(缺图)", it["name"], flush=True); continue
            if only and only not in it["name"]:
                continue
            ok, tail = add([img], it["prompt"], f"{note}｜{it['name']}")
            print(("  OK  " if ok else "  FAIL ") + it["name"] + "  " + (tail[0] if tail else ""), flush=True)
            n_ok += ok; n_fail += (not ok)
    for rel, note, fam in VIDEOS:
        v = ROOT / rel
        if v.exists():
            ok, tail = add([v], note, note, family="H3 MV（自产成片）", model="H3-official-12step")
            print(("OK  " if ok else "FAIL ") + v.name, flush=True)
            n_ok += ok; n_fail += (not ok)
    print(f"\n归档完成：成功 {n_ok}，失败 {n_fail}　相册：http://192.168.31.76:8900 → 目录 {SUBDIR}/", flush=True)
    return 1 if n_fail else 0


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