#!/usr/bin/env bash
# Generiert die 9 Mission-Card-Bilder via DALL-E 3.
# Stil: Flat Scandinavian Alpine, 1792x1024 landscape (später auf 1024x576 verkleinern).
#
# Voraussetzung:
#   - OPENAI_API_KEY als Env-Variable (aus App/.env.local)
#   - curl + python (für JSON-Handling; jq nicht verfügbar auf Git Bash / Windows)
#
# Aufruf:
#   set -a; source App/.env.local; set +a
#   App/sims/heli/scripts/generate-mission-images.sh            # alle
#   App/sims/heli/scripts/generate-mission-images.sh m1 m5 m7   # Auswahl
#   FORCE=1 …                                                    # überschreibt bestehende
set -e
: "${OPENAI_API_KEY:?Env-Variable OPENAI_API_KEY muss gesetzt sein}"

cd "$(dirname "$0")/../assets/missions"

PROMPT_BASE="Flat Scandinavian alpine illustration, wide panoramic landscape filling the entire 16:9 frame edge-to-edge, NOT a circular composition, painted style with clean vector shapes, dark forest green (#1f4b37) and sage green (#4a7c4e) mountains, yellow-mustard (#e8c547) sun accents, beige (#e8e4d8) valley, white snow highlights. Medium-sized rescue helicopter with orange and red markings clearly visible in the sky, recognizable shape with rotor. Recognizable geographic landmarks in the scene. No text, no watermark, no logos, no borders, no frame."

declare -A PROMPTS=(
  [m1]="$PROMPT_BASE Scene: ski area at Damuels in Bregenzerwald, Vorarlberg — Damuels-Mittagsspitze mountain ridge in background, Uga ski lift towers, snowy slopes with ski tracks, small Alpine village in foreground valley."
  [m2]="$PROMPT_BASE Scene: A14 Rheintal motorway near Rankweil, Vorarlberg — wide valley floor with straight highway cutting through, small cars, Rhaetikon mountains in background, Feldkirch visible in distance."
  [m3]="$PROMPT_BASE Scene: Brandnertal with the Zimba peak (pyramid-shaped mountain) in Raetikon range, Vorarlberg — steep rocky cliff, alpine meadow at base, small climber figure, narrow valley road."
  [m4]="$PROMPT_BASE Scene: Rettenbachferner glacier ski area above Soelden in Otztal, Tyrol — high-altitude snow, ski lift towers, cable car station, vast glacier with mountain ridges."
  [m5]="$PROMPT_BASE Scene: Lake Constance (Bodensee) at Bregenz harbour — calm turquoise water, Pfander mountain silhouette on the right, Seebühne floating stage visible on the water, shoreline with town roofs."
  [m6]="$PROMPT_BASE Scene: Rappenloch canyon or Kanisfluh gorge near Mellau in Bregenzerwald, Vorarlberg — deep V-shaped valley with rushing river, green moss-covered cliffs on both sides, small waterfall."
  [m7]="$PROMPT_BASE Scene: Wilder Kaiser mountain range with Kufstein fortress on a rocky hill in the foreground valley, Tyrol — recognizable jagged Kaiser peaks in background, Inn river, hiking trails with small hiker figures."
  [m8]="$PROMPT_BASE Scene: Gaschurn village in hinteres Montafon valley, Vorarlberg — narrow valley with steep mountains on both sides (Silvretta range), village rooftops with church tower, alpine meadow, landing pad."
  [m9]="$PROMPT_BASE Scene: Zillertal near Mayrhofen, Tyrol — Penken mountain in background, fresh avalanche debris on steep slope, snow-covered forest, alpine village in valley."
  [m10]="$PROMPT_BASE Scene: A2 Suedautobahn motorway bridge near Baden south of Vienna — wide curved highway cutting through low wooded hills (Wienerwald), kurpark spa town rooftops in the middle distance, small cars on the road."
  [m11]="$PROMPT_BASE Scene: Donauinsel and Neue Donau in Vienna — long narrow island park between two river arms, reed and willow shoreline, city skyline with St. Stephens cathedral tower in background, calm blue water."
  [m12]="$PROMPT_BASE Scene: Schneeberg mountain north face in Lower Austria — pale limestone cliffs with snow patches, the Schneebergbahn cog railway visible on a ridge, forested foothills below, easternmost 2000er alpine summit."
  [m13]="$PROMPT_BASE Scene: Rax high plateau in Lower Austria — broad grassy karst plateau with limestone outcrops, hiking trail winding through, pine mountain scrub, deep valley Hoellental dropping off to one side."
  [m14]="$PROMPT_BASE Scene: Neusiedler See at Podersdorf in Burgenland — shallow steppe lake with tall reed belt, a windsurfer figure bent over in strong wind, horizon almost flat, pannonian plain stretching east."
  [m15]="$PROMPT_BASE Scene: A1 Westautobahn motorway intersection at Sattledt in Upper Austria — flat agricultural landscape, two highways crossing on overpasses, small cars, distant Alps on the southern horizon."
  [m16]="$PROMPT_BASE Scene: Traunsee lake at Gmunden in Salzkammergut — deep blue alpine lake, steep pyramid-shaped Traunstein peak rising directly from the shore, small sailing boat on the water, Gmunden town with castle Schloss Ort in foreground."
  [m17]="$PROMPT_BASE Scene: A10 Tauern motorway approaching Tauerntunnel north portal near Flachau-Zederhaus — highway curving into mountainside tunnel entrance, steep wooded Tauern mountains, snow on highest peaks, alpine valley."
  [m18]="$PROMPT_BASE Scene: Wolfgangsee at St. Wolfgang im Salzkammergut — alpine lake with the iconic St. Wolfgang pilgrimage church by the shore, Schafberg mountain in background with cog railway, traditional village houses."
  [m19]="$PROMPT_BASE Scene: Grossglockner summit pyramid from the north (Kaiser-Franz-Josefs-Hoehe viewpoint) — sharp snow-ice pyramid peak (highest mountain of Austria 3798m), Pasterze glacier tongue below, moraine ridges, thin cloud wisps."
  [m20]="$PROMPT_BASE Scene: Dachstein massif southern face in Styria — massive limestone cliff wall dropping 800 meters vertically, glacier plateau on top, mountaineer figures roped up, hanging valley in foreground with alpine meadow."
  [m21]="$PROMPT_BASE Scene: Hochschwab karst plateau in Styria — undulating limestone plateau with dwarf pine (Latschen), rocky outcrops, wild chamois grazing, distant view into Mariazell valley, source of Vienna spring water aqueduct."
  [m22]="$PROMPT_BASE Scene: A9 Pyhrn motorway near Bosrucktunnel south portal — highway emerging from tunnel into Ennstal valley, steep forested Bosruck mountain, traditional Styrian farmhouses with wooden shingle roofs."
  [m23]="$PROMPT_BASE Scene: Woerthersee at Poertschach in Carinthia — turquoise warm bathing lake with sailing boats and swimmers near the promenade, Karawanken mountain range in background, Mediterranean-style villas along the shore."
  [m24]="$PROMPT_BASE Scene: Grossglockner southern face from Heiligenblut side in Carinthia — view up to the glockner pyramid across the Pasterze glacier, historical Heiligenblut pilgrimage church with tall needle spire in foreground, Grossglockner panoramic road visible."
  [m25]="$PROMPT_BASE Scene: A2 Suedautobahn motorway near Klagenfurt with the Karawanken mountain range in background — wide valley with highway curving south toward the Slovenian border Karawanken tunnel, Woerthersee visible to the west."
)

TARGETS=("$@")
if [ ${#TARGETS[@]} -eq 0 ]; then
  TARGETS=(m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13 m14 m15 m16 m17 m18 m19 m20 m21 m22 m23 m24 m25)
fi

for id in "${TARGETS[@]}"; do
  prompt="${PROMPTS[$id]}"
  if [ -z "$prompt" ]; then
    echo "✗ $id: kein Prompt definiert, überspringe"
    continue
  fi
  if [ -f "${id}.png" ] && [ -z "$FORCE" ]; then
    echo "✓ ${id}.png schon vorhanden (FORCE=1 zum Überschreiben)"
    continue
  fi
  echo "→ ${id}: generiere …"
  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 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
d=json.load(sys.stdin)
print(d.get("data",[{}])[0].get("url",""))' 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","?"))
except: print("unparseable response")' 2>/dev/null)
    echo "✗ ${id}: Fehler — $err"
    continue
  fi
  curl -s "$url" -o "${id}.png"
  echo "✓ ${id}.png gespeichert ($(du -h "${id}.png" | cut -f1))"
  sleep 2
done

echo
echo "Fertig. Optional auf 1024x576 verkleinern:"
echo "  for f in *.png; do magick \"\$f\" -resize 1024x576 -strip \"\$f\"; done"
