#!/usr/bin/env python3
"""
dreamina-safe: 即梦 (Dreamina) 工业级防重扣费与自动下片包装器
解决四大痛点：
  1. 强制绑定 HOME=/root，彻底杜绝 HOME=/home/node 引发的登录态丢失；
  2. 提交前/后自动写入 <project_dir>/metadata/shot_manifest.json，彻底解决 list_task 不返回 text2video prompt 导致的镜头混淆；
  3. 防重复扣费（Anti-Duplicate Spend）：当 dreamina CLI 内部因 get_history_by_ids / user_info 网络超时或 EOF 报错退出时，
     自动查询最近 90 秒内的 list_task 与 /root/.dreamina_cli/logs/dreamina.log，若服务端已创建任务则直接认领 submit_id，绝不二次扣费；
  4. 精准解析 .result_json.videos[0].video_url 并下载验证，绝不用脆弱的 .mp4 正则。

用法：
  dreamina-safe submit --shot-id g1 --out /data/.../shots/g1.mp4 -- <dreamina 子命令与参数>
  dreamina-safe download --submit-id <uuid> --out /data/.../shots/g1.mp4
"""
import argparse, json, os, re, subprocess, sys, time, urllib.request

os.environ["HOME"] = "/root"
DREAMINA_BIN = "/usr/local/bin/dreamina"
DREAMINA_LOG = "/root/.dreamina_cli/logs/dreamina.log"

def run_cmd(cmd, timeout=240):
    env = os.environ.copy()
    env["HOME"] = "/root"
    try:
        p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, env=env)
        return p.returncode, (p.stdout or "") + "\n" + (p.stderr or "")
    except subprocess.TimeoutExpired as e:
        out = (e.stdout.decode("utf-8", "replace") if isinstance(e.stdout, bytes) else (e.stdout or ""))
        err = (e.stderr.decode("utf-8", "replace") if isinstance(e.stderr, bytes) else (e.stderr or ""))
        return 124, out + "\n" + err + "\nTIMEOUT"

def parse_json_from_output(txt: str):
    idx = txt.find("{")
    ridx = txt.rfind("}")
    if idx != -1 and ridx != -1 and ridx > idx:
        try:
            return json.loads(txt[idx:ridx+1])
        except Exception:
            pass
    return None

def extract_video_url(data: dict) -> str:
    if not isinstance(data, dict):
        return ""
    rj = data.get("result_json") or {}
    if isinstance(rj, str):
        try:
            rj = json.loads(rj)
        except Exception:
            rj = {}
    vids = rj.get("videos") or data.get("videos") or []
    if vids and isinstance(vids[0], dict):
        u = vids[0].get("video_url") or vids[0].get("url") or ""
        if u:
            return u
    imgs = rj.get("images") or data.get("images") or []
    if imgs and isinstance(imgs[0], dict):
        u = imgs[0].get("image_url") or imgs[0].get("url") or ""
        if u:
            return u
    return data.get("video_url") or data.get("image_url") or ""

def recover_recent_submit_id(start_ts: float) -> str:
    if os.path.exists(DREAMINA_LOG):
        try:
            lines = open(DREAMINA_LOG, encoding="utf-8", errors="ignore").readlines()[-80:]
            for line in reversed(lines):
                m = re.search(r"submit_id=([0-9a-fA-F-]{36})", line)
                if m:
                    return m.group(1)
        except Exception:
            pass
    rc, out = run_cmd([DREAMINA_BIN, "list_task", "--limit=5"], timeout=45)
    data = parse_json_from_output(out)
    tasks = data if isinstance(data, list) else (data.get("tasks") or data.get("list") or []) if isinstance(data, dict) else []
    for t in tasks:
        if isinstance(t, dict) and t.get("submit_id"):
            ct = float(t.get("created_time") or t.get("create_time") or 0)
            if ct == 0 or ct >= start_ts - 15:
                return t["submit_id"]
    return ""

def load_manifest(manifest_path: str) -> dict:
    if manifest_path and os.path.exists(manifest_path):
        try:
            return json.load(open(manifest_path, encoding="utf-8"))
        except Exception:
            return {}
    return {}

def save_manifest(manifest_path: str, data: dict):
    if not manifest_path:
        return
    os.makedirs(os.path.dirname(manifest_path), exist_ok=True)
    with open(manifest_path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def download_file(url: str, out_path: str) -> bool:
    os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
    tmp_path = out_path + ".part"
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(req, timeout=120) as resp, open(tmp_path, "wb") as f:
        while True:
            chunk = resp.read(65536)
            if not chunk:
                break
            f.write(chunk)
    if os.path.getsize(tmp_path) > 10000:
        os.replace(tmp_path, out_path)
        return True
    return False

def poll_and_download(submit_id: str, out_path: str, max_wait: int = 420) -> dict:
    t0 = time.time()
    while time.time() - t0 < max_wait:
        rc, out = run_cmd([DREAMINA_BIN, "query_result", f"--submit_id={submit_id}"], timeout=60)
        data = parse_json_from_output(out) or {}
        status = data.get("gen_status") or ""
        if status == "success":
            url = extract_video_url(data)
            if url and out_path:
                if download_file(url, out_path):
                    data["downloaded_path"] = out_path
            return data
        elif status == "fail":
            return data
        time.sleep(12)
    return {"submit_id": submit_id, "gen_status": "timeout"}

def main():
    sub = sys.argv[1] if len(sys.argv) > 1 else ""
    if sub not in ("submit", "download"):
        print(__doc__.strip())
        sys.exit(0)
    if sub == "download":
        p = argparse.ArgumentParser()
        p.add_argument("--submit-id", required=True)
        p.add_argument("--out", required=True)
        p.add_argument("--wait", type=int, default=420)
        args = p.parse_args(sys.argv[2:])
        res = poll_and_download(args.submit_id, args.out, args.wait)
        print(json.dumps(res, ensure_ascii=False, indent=2))
        sys.exit(0 if res.get("downloaded_path") else 1)

    if "--" in sys.argv:
        sep = sys.argv.index("--")
        our_argv = sys.argv[2:sep]
        cli_argv = sys.argv[sep+1:]
    else:
        print("Error: 请在 dreamina 参数前使用 '--' 分隔，例如: dreamina-safe submit --shot-id s1 --out s1.mp4 -- text2video ...", file=sys.stderr)
        sys.exit(2)

    p = argparse.ArgumentParser()
    p.add_argument("--shot-id", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--manifest", default="")
    p.add_argument("--wait", type=int, default=420)
    args = p.parse_args(our_argv)

    if os.path.exists(args.out) and os.path.getsize(args.out) > 50000:
        print(json.dumps({"shot_id": args.shot_id, "status": "skipped_existing", "path": args.out}, ensure_ascii=False))
        sys.exit(0)

    manifest_path = args.manifest or os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(args.out))), "metadata", "shot_manifest.json")
    manifest = load_manifest(manifest_path)

    existing = manifest.get(args.shot_id, {})
    if existing.get("submit_id") and existing.get("gen_status") not in ("fail",):
        sid = existing["submit_id"]
        print(f"[dreamina-safe] 发现已存在的任务 {sid} (shot={args.shot_id})，直接恢复轮询，避免重复扣费...", file=sys.stderr)
        res = poll_and_download(sid, args.out, args.wait)
        existing["gen_status"] = res.get("gen_status", "unknown")
        existing["downloaded_path"] = res.get("downloaded_path", "")
        manifest[args.shot_id] = existing
        save_manifest(manifest_path, manifest)
        print(json.dumps(res, ensure_ascii=False, indent=2))
        sys.exit(0 if res.get("downloaded_path") else 1)

    start_ts = time.time()
    manifest[args.shot_id] = {"shot_id": args.shot_id, "cmd": cli_argv, "started_at": start_ts, "gen_status": "submitting"}
    save_manifest(manifest_path, manifest)

    for attempt in range(1, 5):
        rc, out = run_cmd([DREAMINA_BIN] + cli_argv, timeout=210)
        if "ExceedConcurrencyLimit" in out or "1310" in out:
            print(f"[dreamina-safe] 触发账号并发上限 (1310)，等待 35s 后重试 (attempt {attempt})...", file=sys.stderr)
            time.sleep(35)
            continue
        data = parse_json_from_output(out) or {}
        sid = data.get("submit_id") or ""
        if not sid:
            m = re.search(r'"submit_id"\s*:\s*"([^"]+)"', out)
            if m:
                sid = m.group(1)
        if not sid:
            sid = recover_recent_submit_id(start_ts)
            if sid:
                print(f"[dreamina-safe] 捕获到网络超时/EOF，已从服务端日志成功找回已创建的 submit_id={sid}，避免重复扣费！", file=sys.stderr)
        if sid:
            manifest[args.shot_id]["submit_id"] = sid
            manifest[args.shot_id]["gen_status"] = data.get("gen_status", "querying")
            save_manifest(manifest_path, manifest)
            url = extract_video_url(data)
            if url and download_file(url, args.out):
                data["downloaded_path"] = args.out
                manifest[args.shot_id]["gen_status"] = "success"
                manifest[args.shot_id]["downloaded_path"] = args.out
                save_manifest(manifest_path, manifest)
                print(json.dumps(data, ensure_ascii=False, indent=2))
                sys.exit(0)
            res = poll_and_download(sid, args.out, args.wait)
            manifest[args.shot_id]["gen_status"] = res.get("gen_status", "unknown")
            manifest[args.shot_id]["downloaded_path"] = res.get("downloaded_path", "")
            save_manifest(manifest_path, manifest)
            print(json.dumps(res, ensure_ascii=False, indent=2))
            sys.exit(0 if res.get("downloaded_path") else 1)
        time.sleep(10)

    print(json.dumps({"shot_id": args.shot_id, "gen_status": "submit_failed"}, ensure_ascii=False))
    sys.exit(1)

if __name__ == "__main__":
    main()
