#!/bin/bash
# 새 아웃룩 카탈로그에 맞는 인물+아웃룩 합성 참조를 만들고 → 8샷 이미지 → 갤러리.
#
# 아웃룩을 다시 만들자 카탈로그가 새로 생겼고(35개), 합성 참조는 옛 카탈로그
# 기준이라 30개 조합에 참조가 없다. `check_scene_images_ready` 가 그걸 막는다 —
# 참조 없이 그리면 인물 외형이 무너지므로 막는 게 맞다.
#
# force 를 쓴다: 기존 결과가 있는 스텝은 force 만 재실행한다(resume 는 보관본에서
# 자동 복원할 뿐이다 — 실측). 하류 삭제분은 뒤에서 되돌린다.
set -u
cd /Users/manta/Documents/Projects/TheRoad-I1/backend
PY=.venv/bin/python
P=e716bafb-24bb-42b7-aea0-fdb383844ee8
E=d6a9aa85-b75e-400c-980c-4ee7e876a15b
CPD=/Users/manta/Documents/Projects/TheRoad-I1/projects/$P/checkpoints/episodes/$E

curl -s -c /tmp/th.cookie -X POST http://localhost:8000/api/v1/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"admin","password":"admin123"}' > /dev/null

BEFORE=$(date +%s)
echo "① 합성 참조 생성 (composite_image_gen, force)"
curl -s -b /tmp/th.cookie -X POST \
  "http://localhost:8000/api/v1/projects/$P/episodes/$E/steps/composite_image_gen?mode=force" | head -c 200
echo

echo "   완료 대기 (mtime 갱신 확인 — 존재만 보면 자동 복원본을 완료로 오독한다)"
for i in $(seq 1 180); do
  if [ -f "$CPD/composite_image_gen/manifest.json" ]; then
    M=$(stat -f %m "$CPD/composite_image_gen/manifest.json")
    [ "$M" -gt "$BEFORE" ] && break
  fi
  sleep 20
done
$PY -c "
import json,pathlib
p=pathlib.Path('$CPD/composite_image_gen/manifest.json')
d=json.loads(p.read_text())
print(f\"   composite_image_gen: status={d.get('status')} completed={d.get('completed_count')}/{d.get('applicable_count')} failed={d.get('failed_count')} updated={d.get('updated_at','')[:19]}\")"

echo "② force 가 지운 하류 되돌리기"
$PY - <<'PYEOF'
import pathlib, shutil
cp = pathlib.Path('/Users/manta/Documents/Projects/TheRoad-I1/projects/e716bafb-24bb-42b7-aea0-fdb383844ee8/checkpoints/episodes/d6a9aa85-b75e-400c-980c-4ee7e876a15b')
stamps = {a.name[len("manifest_"):-len(".json")]
          for d in cp.iterdir() if d.is_dir() for a in d.glob("manifest_2*.json")}
stamp = max(stamps) if stamps else ""
restored = []
for d in sorted(p for p in cp.iterdir() if p.is_dir()):
    if d.name == "composite_image_gen":
        continue
    live, arch = d / "manifest.json", d / f"manifest_{stamp}.json"
    if live.exists() or not arch.exists():
        continue
    shutil.copy2(arch, live)          # 추가 전용
    restored.append(d.name)
print(f"   보관본 {stamp} 에서 되돌림 {len(restored)}개: {restored}")
missing = [p.name for p in cp.iterdir() if p.is_dir() and not (p/'manifest.json').exists()]
print(f"   아직 manifest 없는 스텝: {missing or '없음'}")
PYEOF

echo "③ 8샷 이미지 생성"
$PY regen_drift_fixed_shots.py --images-only 2>&1 | tail -16

echo "④ 갤러리 갱신"
$PY build_drift_fix_gallery.py
echo "http://192.168.35.42:8940/artifact/20260807_scene_director_drift/index.html"
