#!/usr/bin/env python3
"""Resume pipeline from storyboard through pass2+verify (after pass0/director already done)."""
import os, sys, subprocess, json, time
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
workdir = sys.argv[1]
py = sys.executable
os.chdir(workdir)

def run(cmd, desc, timeout=10800):
    print(f"\n{'='*60}\n  {desc}\n  {cmd}", flush=True)
    t0 = time.time()
    try:
        proc = subprocess.run(cmd, cwd=workdir, timeout=timeout)
    except subprocess.TimeoutExpired:
        print(f"  ✗ TIMEOUT ({timeout}s, rodou {time.time()-t0:.0f}s)", flush=True)
        sys.exit(1)
    dt = time.time() - t0
    if proc.returncode != 0:
        print(f"  ✗ FALHOU rc={proc.returncode} ({dt:.0f}s)", flush=True)
        sys.exit(proc.returncode)
    print(f"  ✓ OK ({dt:.0f}s)", flush=True)

# placeholders required by some stages
for ph in ["missed_inserts.json","content_inserts.json","emotion_inserts.json",
           "variety_inserts.json","luma_switches.json","stab_switches.json",
           "judge_switches_ok.json","storyboard.json"]:
    if not os.path.exists(ph):
        open(ph,"w").write("[]")

run([py, os.path.join(SCRIPT_DIR, "storyboard_gen.py")], "5. STORYBOARD", 10800)
run([py, os.path.join(SCRIPT_DIR, "switch_judge_gen.py")], "6a. SWITCH", 10800)
run([py, os.path.join(SCRIPT_DIR, "stab_gen.py")], "6b. STAB", 10800)
if os.path.exists("spike_candidates.json") and os.path.getsize("spike_candidates.json") > 2:
    run([py, os.path.join(SCRIPT_DIR, "occlusion_judge.py")], "6c. OCCLUSION", 10800)
if os.path.exists("content_map_dense.json"):
    run([py, os.path.join(SCRIPT_DIR, "content_gen.py")], "6d. CONTENT", 10800)
    run([py, os.path.join(SCRIPT_DIR, "variety_cands.py")], "6e. VARIETY cands", 600)
    run([py, os.path.join(SCRIPT_DIR, "variety_judge.py")], "6f. VARIETY judge", 10800)
    run([py, os.path.join(SCRIPT_DIR, "missed_cands.py")], "6g. MISSED cands", 600)
    run([py, os.path.join(SCRIPT_DIR, "missed_judge.py")], "6h. MISSED judge", 10800)
run([py, os.path.join(SCRIPT_DIR, "unified.py")], "7. MOTOR pass2", 10800)
if os.path.exists(os.path.join(SCRIPT_DIR, "verify.py")):
    run([py, os.path.join(SCRIPT_DIR, "verify.py"), "UNI"], "8. VERIFY", 600)
uni = json.load(open("versions/UNI.json"))
print(f"\nPIPELINE RESUME OK: {len(uni.get('cutpoints',[]))} cutpoints", flush=True)
sb = json.load(open("storyboard.json"))
print(f"storyboard segments: {len(sb)}", flush=True)
