#!/usr/bin/env bash
# Generiert die Logistik-Stadt-Bilder via DALL-E 3.
# Stil: Flat Scandinavian panoramic, an Heli-Pattern angelehnt (visuelle
# Kontinuitaet zwischen den Simulationen). Ohne Helikopter / Bergrettung —
# stattdessen ruhige, wiedererkennbare Stadt- und Landschafts-Panoramen.
#
# Voraussetzung:
#   - OPENAI_API_KEY als Env-Variable (aus App/.env.local)
#   - curl + python (fuer JSON-Handling; jq nicht verfuegbar auf Git Bash / Windows)
#
# Aufruf:
#   set -a; source App/.env.local; set +a
#   App/sims/logistik/scripts/generate-city-images.sh                   # alle
#   App/sims/logistik/scripts/generate-city-images.sh wien salzburg     # Auswahl
#   FORCE=1 ...                                                          # ueberschreibt bestehende
#
# Kosten: ~0.04 EUR pro Bild (DALL-E 3 standard, 1792x1024).
set -e
: "${OPENAI_API_KEY:?Env-Variable OPENAI_API_KEY muss gesetzt sein}"

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

PROMPT_BASE="Flat Scandinavian 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) tones, yellow-mustard (#e8c547) accents, beige (#e8e4d8) buildings and valleys, white highlights. Recognizable geographic landmarks and city silhouettes. No text, no watermark, no logos, no borders, no frame, no people close-up."

declare -A PROMPTS=(
  # Test-Set (5 Staedte) — DACH + Italien, sofort brauchbar
  [wien]="$PROMPT_BASE Scene: Vienna cityscape with St. Stephen's Cathedral tower clearly visible in the center, Danube river curving on one side, Ferris wheel of Prater in the distance, Ringstrasse boulevard with historic buildings, Kahlenberg hill on the horizon."
  [salzburg]="$PROMPT_BASE Scene: Salzburg old town panorama with Hohensalzburg fortress on the hill dominating the skyline, Salzach river flowing through, Baroque church domes and towers (Salzburger Dom), surrounding Alpine foothills, narrow historic streets."
  [muenchen]="$PROMPT_BASE Scene: Munich skyline with the twin onion domes of Frauenkirche (Liebfrauenkirche) clearly visible, Rathaus tower, Alps on the southern horizon, Isar river, flat Bavarian plain, English Garden greenery."
  [hamburg]="$PROMPT_BASE Scene: Hamburg harbour and city with the Elbphilharmonie's wave-shaped roof on the Elbe river, harbour cranes and container stacks in the distance, Michel church tower (St. Michaelis) with dark copper dome, Alster lakes reflecting the sky."
  [mailand]="$PROMPT_BASE Scene: Milan cityscape with the Duomo cathedral's intricate spires and white marble facade in the center, Galleria Vittorio Emanuele II dome beside it, Castello Sforzesco walls, Po Valley flat landscape around, distant Alps on the northern horizon."

  # Erweiterung (12 weitere) — fuer spaetere Runs, wenn Pattern gefaellt
  [berlin]="$PROMPT_BASE Scene: Berlin skyline with Brandenburger Tor gate in foreground, TV tower (Fernsehturm) with its characteristic sphere in middle distance, Reichstag dome, Spree river curving through, flat North German plain."
  [paris]="$PROMPT_BASE Scene: Paris panorama with Eiffel Tower prominent on the left, Sacre-Coeur basilica white dome on Montmartre hill, Seine river with bridges, Notre-Dame cathedral towers, Haussmann boulevards, uniform rooftop silhouette."
  [rotterdam]="$PROMPT_BASE Scene: Rotterdam port skyline with the cable-stayed Erasmus Bridge, cube houses (Kubuswoningen), container terminal cranes in distance, Nieuwe Maas river, flat polder landscape."
  [rom]="$PROMPT_BASE Scene: Rome cityscape with Colosseum amphitheatre on the left, St. Peter's Basilica dome (Vatican) on the right, Tiber river curving through, cypress trees and umbrella pines, seven hills, warm ochre rooftops."
  [london]="$PROMPT_BASE Scene: London Thames panorama with Big Ben and Westminster Palace on one side, Tower Bridge suspension cables on the other, London Eye wheel, St. Paul's dome, modern skyscrapers (Gherkin, Shard) in background."
  [amsterdam]="$PROMPT_BASE Scene: Amsterdam canal belt with narrow gabled merchant houses in rows, bicycles parked on bridges, canal boats, Westerkerk church tower, tulip fields visible on horizon, windmill in the distance."
  [bruessel]="$PROMPT_BASE Scene: Brussels cityscape with Atomium spheres prominent, Grand-Place gothic guild halls, Palace of Justice dome, EU Parliament modern complex, flat Flemish landscape."
  [prag]="$PROMPT_BASE Scene: Prague panorama with Prague Castle and St. Vitus Cathedral on the hill, Charles Bridge with its stone towers crossing the Vltava river, red-tiled rooftops of Old Town, Bohemian rolling hills."
  [budapest]="$PROMPT_BASE Scene: Budapest with Parliament building's neo-gothic facade on the Danube, Chain Bridge with its lions, Buda Castle on hilltop, Fisherman's Bastion white turrets, Pannonian plain stretching east."
  [kopenhagen]="$PROMPT_BASE Scene: Copenhagen with the Little Mermaid statue on rocks by the waterfront, Nyhavn colourful canal houses, spires of Christiansborg and Rosenborg Castle, Oresund bridge arching over to Sweden in the distance."
  [stockholm]="$PROMPT_BASE Scene: Stockholm archipelago city on 14 islands, Gamla Stan old town with red-orange buildings, Royal Palace, Riddarholmen church spire, sailboats in the harbour, pine-covered rocky islands."
  [warschau]="$PROMPT_BASE Scene: Warsaw skyline with Palace of Culture and Science (Stalinist skyscraper) prominent, rebuilt Old Town market square with coloured townhouses, Vistula river, flat Mazovian plain."
  [madrid]="$PROMPT_BASE Scene: Madrid cityscape with Puerta de Alcalá triumphal arch, Gran Via avenue with early-20th-century buildings, Royal Palace with white facade, Plaza Mayor, dry Castilian meseta plateau around."
  [athen]="$PROMPT_BASE Scene: Athens with the Acropolis hill crowned by the Parthenon marble temple, Lycabettus hill with white chapel on top, whitewashed Plaka district below, Aegean sea glimpsed on the horizon, port of Piraeus in distance with container cranes."
  [oslo]="$PROMPT_BASE Scene: Oslo fjord panorama with modern white Opera House like a sloping iceberg at the waterfront, sailing boats on blue fjord, Akershus Fortress on a hilltop, pine-covered hills around, northern light over the water."
  [helsinki]="$PROMPT_BASE Scene: Helsinki harbour with Helsinki Cathedral's white facade and green dome on the hill above Senate Square, market square with colourful stalls, Baltic Sea ferries, pine islands in the archipelago beyond."
  [dublin]="$PROMPT_BASE Scene: Dublin with the Ha'penny Bridge arching over the River Liffey, Georgian terraced houses with colourful doors, Trinity College campanile, Dublin Bay with seagulls, green Irish countryside on horizon."
  [lissabon]="$PROMPT_BASE Scene: Lisbon with yellow tram #28 on a steep cobblestone street, Belém Tower limestone fortress by the Tagus river, 25 de Abril suspension bridge in the distance, red-tiled rooftops cascading down hills, Atlantic Ocean."
  [bern]="$PROMPT_BASE Scene: Bern old town on a peninsula in the Aare river, sandstone buildings with red-tiled roofs, Zytglogge clocktower, distant Bernese Alps with snowy Eiger/Mönch/Jungfrau peaks, green river bend."
  [hamburg_hafen]="$PROMPT_BASE Scene: Port of Hamburg with massive container terminal, rows of blue and orange shipping containers stacked high, gantry cranes loading a container ship, Köhlbrandbrücke cable-stayed bridge, Elbe river industrial waterfront."
  [rotterdam_hafen]="$PROMPT_BASE Scene: Port of Rotterdam Maasvlakte container terminal, huge container ships at deep-water berths, automated gantry cranes, container stacks, wind turbines on the seawall, North Sea waves beyond."

  # Tier 2 (Grossstaedte)
  [frankfurt]="$PROMPT_BASE Scene: Frankfurt am Main skyline with cluster of glass high-rises of the banking district (Mainhattan), Main river with bridges, half-timbered Roemer town hall at Paulskirche, Frankfurt airport control tower in distant haze."
  [koeln]="$PROMPT_BASE Scene: Cologne cityscape dominated by the twin black-gothic spires of the Koelner Dom cathedral, Hohenzollern railway bridge crossing the Rhine river, old town with gabled houses in foreground, Rhine barges on the water."
  [stuttgart]="$PROMPT_BASE Scene: Stuttgart valley city with Mercedes-Benz Museum curved modern building, vineyards climbing the surrounding hills (typical), TV tower Fernsehturm on Bopser hill, Swabian alb mountains on horizon."
  [leipzig]="$PROMPT_BASE Scene: Leipzig with the Voelkerschlachtdenkmal obelisk monument prominent, historic Hauptbahnhof station facade, modern Gewandhaus concert hall, flat Saxon plain stretching, tree-lined canals."
  [nuernberg]="$PROMPT_BASE Scene: Nuremberg with the Imperial Castle on a sandstone hill crowning the city, half-timbered medieval old town below, covered wooden Henkerbruecke bridge over the Pegnitz river, red-tiled rooftops."
  [innsbruck]="$PROMPT_BASE Scene: Innsbruck in Inn valley with the Nordkette mountain range rising steeply behind, Goldenes Dachl gold-roofed medieval balcony, Bergisel ski jump tower modern, Inn river, alpine meadows."
  [graz]="$PROMPT_BASE Scene: Graz Austria. ON TOP of the green forested Schlossberg hill stands the iconic Grazer UHRTURM clocktower (Renaissance, NOT a church, NOT a steeple): a STOUT SQUARE STANDALONE TOWER made of beige-cream stone, with a very wide WOODEN ROOFED GALLERY-BALCONY wrapping around all four sides at the top, crowned by a steep RED-SHINGLE PYRAMID ROOF, and each side shows one LARGE ROUND BLACK-AND-WHITE CLOCK FACE. The tower is wider at the gallery than at the base. NO crosses, NO bell tower, NO spire. Below the hill: red-tiled medieval old town along the Mur river, the dark glass blob-shaped Kunsthaus 'friendly alien' museum on the river bank, distant rolling Styrian vineyards."
  [zuerich]="$PROMPT_BASE Scene: Zurich lake with snow-capped Alps reflected in calm water, Grossmuenster twin romanesque towers and Fraumuenster spire in old town, Bahnhofstrasse, green hillsides, steamboats on the lake."
  [turin]="$PROMPT_BASE Scene: Turin grid-plan city with the Mole Antonelliana tall spire tower prominent, Palazzo Reale royal palace, snow-capped western Alps forming the backdrop, Po river, broad boulevards."
  [neapel]="$PROMPT_BASE Scene: Naples bay with Mount Vesuvius volcano looming behind the city, Castel dell'Ovo fortress on a small island, colorful stacked waterfront houses, fishing boats, blue Tyrrhenian sea, pines."
  [lyon]="$PROMPT_BASE Scene: Lyon peninsula between Rhone and Saone rivers, Notre-Dame de Fourviere white basilica on the hill, traboule alleys in old town, red-tiled rooftops, green Beaujolais hills in distance."
  [marseille]="$PROMPT_BASE Scene: Marseille Vieux-Port old harbor full of fishing boats, Notre-Dame de la Garde golden statue basilica on hilltop, Chateau d'If island fortress, Mediterranean calanques limestone cliffs, Provence sun."
  [barcelona]="$PROMPT_BASE Scene: Barcelona with Sagrada Familia towers with intricate spires and mosaics rising above the Eixample grid, Park Gueell tiled terraces in foreground, Mediterranean beach, Montjuic hill with castle."
  [valencia]="$PROMPT_BASE Scene: Valencia with the City of Arts and Sciences futuristic white Calatrava complex (Hemispheric eye-shape), orange groves surrounding the city, Turia riverbed turned into a park, Mediterranean coast."
  [porto]="$PROMPT_BASE Scene: Porto cascading down steep hills to the Douro river, Ribeira district colorful tile-fronted houses stacked, Ponte Luis I double-deck iron bridge, port wine cellars across in Vila Nova de Gaia."
  [manchester]="$PROMPT_BASE Scene: Manchester with red-brick Victorian industrial warehouses converted to lofts, Beetham Tower needle-thin glass skyscraper, tram lines, canals with narrowboats, Pennines hills on horizon."
  [krakau]="$PROMPT_BASE Scene: Krakow Wawel Royal Castle on a limestone hill above the Vistula river, Main Market Square with Cloth Hall Sukiennice gothic arcade, medieval town walls, distant snowy Tatra mountains."
  [thessaloniki]="$PROMPT_BASE Scene: Thessaloniki waterfront with the White Tower fortress at the harbor, Byzantine city ramparts on a hill, Mount Olympus distant across the Thermaic Gulf, port cranes, Aegean Sea blue."

  # Tier 3 (Haefen und Terminals)
  [antwerpen_hafen]="$PROMPT_BASE Scene: Port of Antwerp on the Scheldt river, massive container terminal with thousands of colorful containers, oil refineries and chemical storage tanks in the distance, gantry cranes, inland barges, flat Flemish landscape."
  [bremerhaven_hafen]="$PROMPT_BASE Scene: Port of Bremerhaven car terminal with thousands of new cars in long rows awaiting export, giant RoRo ship with ramp lowered to dock, container cranes, Weser river estuary, North Sea on horizon."
  [duisburg_terminal]="$PROMPT_BASE Scene: Duisburg inland harbor at the Rhine-Ruhr confluence, container stacks, railway tracks for trans-Eurasian freight trains, a Chinese cargo train in the foreground with logos, industrial Ruhr backdrop."
  [basel_terminal]="$PROMPT_BASE Scene: Rhine river harbor of Basel Switzerland, container terminal with gantry cranes, river barges pushing upstream, Three-Country-Corner monument, Alps distant on horizon, industrial Rhine-port infrastructure."
  [marseille_hafen]="$PROMPT_BASE Scene: Port of Marseille with massive container ships at berth, oil tankers, Mediterranean sea sparkling, Notre-Dame de la Garde distant on hill behind, pine trees, industrial harbor cranes and warehouses."
  [barcelona_hafen]="$PROMPT_BASE Scene: Port of Barcelona container terminal with cruise ships and cargo freighters side by side, gantry cranes, Mediterranean sea, Montjuic cable car line above, Columbus statue distant, industrial-urban edge."
  [genua_hafen]="$PROMPT_BASE Scene: Port of Genoa Italy with colorful old-town houses stacked on the hillside above the docks, container terminal, Lanterna old lighthouse tower (oldest working in Mediterranean), Italian Riviera mountains."
  [triest_hafen]="$PROMPT_BASE Scene: Port of Trieste with Piazza Unita d'Italia waterfront plaza, container terminal, Adriatic sea, Karst limestone hills behind, passage ships from the Balkans, Slovenian border hills in distance."
  [piraeus_hafen]="$PROMPT_BASE Scene: Port of Piraeus Greece with massive COSCO container terminal, Chinese cargo ships at berth, cruise ships, Saronic Gulf islands in distance, bright Aegean sunlight, industrial port infrastructure."
  [gdansk_hafen]="$PROMPT_BASE Scene: Port of Gdansk on the Baltic Sea, container terminal with gantry cranes, historic Solidarity shipyards with gantry structures, coal loading conveyors, red-brick Hanseatic old town tower visible in background."
  [goeteborg_hafen]="$PROMPT_BASE Scene: Port of Gothenburg Sweden, deep-water container terminal with a massive container ship at berth, gantry cranes, industrial waterfront, North Sea, Scandinavian pine forest hills on the far shore."
)

TARGETS=("$@")
if [ ${#TARGETS[@]} -eq 0 ]; then
  # Default: alle definierten Staedte + Haefen. Bereits generierte Bilder
  # werden uebersprungen (FORCE=1 zum Ueberschreiben).
  TARGETS=(
    # Tier 1: Hauptstaedte und Kern-Haefen
    wien salzburg muenchen hamburg hamburg_hafen rotterdam rotterdam_hafen
    paris mailand berlin warschau madrid kopenhagen rom london
    bruessel amsterdam prag budapest athen stockholm oslo helsinki
    dublin lissabon bern
    # Tier 2: Grossstaedte
    frankfurt koeln stuttgart leipzig nuernberg innsbruck graz zuerich
    turin neapel lyon marseille barcelona valencia porto manchester
    krakau thessaloniki
    # Tier 3: Haefen und Terminals
    antwerpen_hafen bremerhaven_hafen duisburg_terminal basel_terminal
    marseille_hafen barcelona_hafen genua_hafen triest_hafen
    piraeus_hafen gdansk_hafen goeteborg_hafen
  )
fi

for id in "${TARGETS[@]}"; do
  prompt="${PROMPTS[$id]}"
  if [ -z "$prompt" ]; then
    echo "x $id: kein Prompt definiert, ueberspringe"
    continue
  fi
  if [ -f "${id}.png" ] && [ -z "$FORCE" ]; then
    echo "ok ${id}.png schon vorhanden (FORCE=1 zum Ueberschreiben)"
    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 "x ${id}: Fehler - $err"
    continue
  fi
  curl -s "$url" -o "${id}.png"
  echo "ok ${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"
