#!/usr/bin/env bash
# 批量用即梦复现作者提示词：逐条提交 → 轮询 → 下载成品 → 记录积分
# 用法: bash run_repro.sh [起始序号] [结束序号]
set -u
D="/home/zyw/Downloads/dl-hub/85-AI生图提示词知识库-桀克AIShotLab/07-即梦复现对比"
DJ=/home/zyw/.local/bin/dreamina
mkdir -p "$D/outputs" "$D/logs"

credit() { timeout 60 $DJ user_credit 2>/dev/null | python3 -c "import sys,json;print(json.load(sys.stdin)['total_credit'])" 2>/dev/null || echo "?"; }

START=${1:-0}
END=${2:-9999}
N=$(python3 -c "import json;print(len(json.load(open('$D/prompts/batch.json'))))")

before=$(credit)
echo "=== 开始，当前积分 $before ==="

for k in $(seq "$START" $((N-1))); do
  [ "$k" -gt "$END" ] && break
  IID=$(python3 -c "import json;print(json.load(open('$D/prompts/batch.json'))[$k]['iid'])")
  RATIO=$(python3 -c "import json;print(json.load(open('$D/prompts/batch.json'))[$k]['ratio'])")
  P="$D/prompts/$IID.txt"
  python3 -c "
import json
b=json.load(open('$D/prompts/batch.json'))[$k]
open('$P','w').write(b['prompt'])
"
  echo "--- [$((k+1))/$N] $IID  ratio=$RATIO ---"
  out=$(timeout 900 $DJ text2image --prompt "$(cat "$P")" --model_version 5.0 \
        --resolution_type 2k --ratio "$RATIO" --poll 300 2>/dev/null)
  echo "$out" > "$D/logs/$IID.submit.json"
  sid=$(echo "$out" | python3 -c "
import sys,json
try:
    d=json.load(sys.stdin); print(d.get('submit_id',''))
except Exception: print('')
")
  if [ -z "$sid" ]; then echo "  ✗ 未取到 submit_id"; continue; fi
  echo "  submit_id=$sid"
  timeout 300 $DJ query_result --submit_id "$sid" --download_dir "$D/outputs" > "$D/logs/$IID.result.json" 2>/dev/null
  got=$(ls "$D/outputs" 2>/dev/null | grep -c "$sid" || true)
  echo "  已落盘文件数(含 sid 命名): $got"
done

after=$(credit)
if [[ "$before" =~ ^[0-9]+$ && "$after" =~ ^[0-9]+$ ]]; then echo "=== 结束，积分 $before → $after （消耗 $((before-after))）==="; else echo "=== 结束，积分 $before → $after ==="; fi
ls -la "$D/outputs" | tail -20
