#!/usr/bin/env bash
# Stadt-Symbolbilder fuer Busfahrt — liest cities.json, generiert via DALL-E.
#
# Aufruf:
#   set -a; source App/.env.local; set +a
#   App/sims/busfahrt/scripts/generate-city-images.sh           # alles fehlende
#   App/sims/busfahrt/scripts/generate-city-images.sh tokio rom # gezielt
#
# Ueberschreiben:  FORCE=1 ./generate-city-images.sh tokio
set -e
: "${OPENAI_API_KEY:?OPENAI_API_KEY env var nicht gesetzt}"

cd "$(dirname "$0")/.."
mkdir -p assets/cities
IMG_DIR="$(pwd)/assets/cities"

# Hole Liste id|prompt fuer alle Staedte mit imagePrompt (relativer Pfad)
mapfile -t ALL_LINES < <(python -c "
import json
with open('assets/data/cities.json', encoding='utf-8') as f:
    cities = json.load(f)
for c in cities:
    if c.get('imagePrompt'):
        print(c['id'] + '|||' + c['imagePrompt'])
")

# Filter: nur Argumente, falls angegeben
TARGETS=("$@")

TOTAL=${#ALL_LINES[@]}
i=0
ok=0
fail=0

for line in "${ALL_LINES[@]}"; do
  i=$((i+1))
  id="${line%%|||*}"
  prompt="${line#*|||}"

  # Filter
  if [ ${#TARGETS[@]} -gt 0 ]; then
    skip=1
    for t in "${TARGETS[@]}"; do
      if [ "$t" = "$id" ]; then skip=0; break; fi
    done
    [ $skip -eq 1 ] && continue
  fi

  out="$IMG_DIR/$id.png"
  if [ -f "$out" ] && [ -z "$FORCE" ]; then
    echo "[$i/$TOTAL] $id: ok (existiert, FORCE=1 zum Ueberschreiben)"
    continue
  fi

  echo -n "[$i/$TOTAL] $id: "
  payload=$(PROMPT="$prompt" python -c 'import json,os; print(json.dumps({"model":"dall-e-3","prompt":os.environ["PROMPT"],"n":1,"size":"1792x1024","quality":"standard"}))')

  resp=$(curl -s --max-time 180 https://api.openai.com/v1/images/generations \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -H "Content-Type: application/json" \
    -d "$payload")

  url=$(echo "$resp" | python -c 'import sys,json
try:
    d=json.load(sys.stdin)
    print(d.get("data",[{}])[0].get("url",""))
except: print("")' 2>/dev/null)

  if [ -z "$url" ]; then
    err=$(echo "$resp" | python -c 'import sys,json
try: print(json.load(sys.stdin).get("error",{}).get("message","?")[:200])
except: print("unparseable: " + sys.stdin.read()[:200])' 2>/dev/null)
    echo "x $err"
    fail=$((fail+1))
    sleep 5
    continue
  fi

  if curl -s --max-time 60 "$url" -o "$out"; then
    sz=$(stat -c%s "$out" 2>/dev/null || stat -f%z "$out" 2>/dev/null)
    echo "ok ($((sz/1024)) KB)"
    ok=$((ok+1))
  else
    echo "x download failed"
    rm -f "$out"
    fail=$((fail+1))
  fi
  sleep 2
done

echo ""
echo "Fertig: $ok ok, $fail Fehler"
