#!/bin/bash
# Queue a generation and poll for result
JOB_ID=$(curl -s -X POST http://localhost:8080/txt2img \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "a beautiful mountain landscape at sunset, photorealistic, 8k",
    "negative_prompt": "",
    "width": 512,
    "height": 512,
    "steps": 8,
    "cfg_scale": 1.0,
    "sampling_method": "euler",
    "seed": 42
  }' | python3 -c 'import sys,json; print(json.load(sys.stdin).get("job_id",""))')

echo "Job: $JOB_ID"
START=$(date +%s)

while true; do
  STATUS=$(curl -s "http://localhost:8080/queue/$JOB_ID")
  STATE=$(echo "$STATUS" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d.get("status","unknown"))' 2>/dev/null)
  PROGRESS=$(echo "$STATUS" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d.get("progress",0))' 2>/dev/null)
  NOW=$(date +%s)
  ELAPSED=$((NOW - START))
  echo "  ${ELAPSED}s: status=$STATE progress=$PROGRESS"
  
  if [ "$STATE" = "completed" ] || [ "$STATE" = "failed" ] || [ "$STATE" = "error" ]; then
    echo ""
    echo "=== FINAL STATUS (${ELAPSED}s) ==="
    echo "$STATUS" | python3 -c '
import sys, json
d = json.load(sys.stdin)
for k,v in d.items():
    if k in ("output_files", "images"):
        print(f"{k}: {len(v) if isinstance(v,list) else v}")
    elif k == "timing":
        print(f"timing: {json.dumps(v, indent=2)}")
    else:
        print(f"{k}: {v}")
' 2>/dev/null
    break
  fi
  sleep 2
done
