#!/usr/bin/env python3
"""storyboard #10 결과 31장 → dataset/cropped/{stem}.png + {stem}.txt 로 정리.

생성 순서가 ITEMS 순서와 동일 (storyboard_submit.py 가 그 순서로 push).
"""
import json, shutil, sys, urllib.request
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from generate import ITEMS, build_caption, DATASET_DIR

SB = 10
res = urllib.request.urlopen(f"http://100.92.197.73:9100/api/storyboards/{SB}").read()
items = json.loads(res)["items"]
items.sort(key=lambda x: x["item_index"])

assert len(items) == len(ITEMS), f"item count mismatch: storyboard={len(items)} ITEMS={len(ITEMS)}"

# 기존 4 stale (closeup_01-04 from 구 generate.py) 정리
for f in DATASET_DIR.glob("*.png"):
    f.unlink()
for f in DATASET_DIR.glob("*.txt"):
    f.unlink()

DATASET_DIR.mkdir(parents=True, exist_ok=True)

done = 0
for sb_item, (stem, comp, _size, _expr, _scene, tail) in zip(items, ITEMS):
    src = sb_item["image_artifact_path"]
    if not Path(src).exists():
        print(f"  MISS {src}", file=sys.stderr)
        continue
    caption = build_caption(comp, tail)
    shutil.copy(src, DATASET_DIR / f"{stem}.png")
    (DATASET_DIR / f"{stem}.txt").write_text(caption + "\n")
    done += 1

print(f"collected {done}/31 → {DATASET_DIR}")
