#!/usr/bin/env bash
# 🚀 GENERATE & DEPLOY TILES MASTER SCRIPT
# 1. Export PBF -> GeoJSON
# 2. Generate Tiles (Tippecanoe)
# 3. Deploy to VPS or Firebase

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_ROOT"

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

log "============================================="
log "🗺️ EUROPE TILES GENERATION PIPELINE"
log "============================================="

# 0. PRE-FLIGHT CHECK
log "🔍 Checking environment..."

# Check PBF file
PBF_FILE="$PROJECT_ROOT/europe-roadtrip.osm.pbf"
if [ ! -f "$PBF_FILE" ]; then
    log "❌ Error: Filtered PBF file not found: $PBF_FILE"
    log "   Run the filter step first (Step 2 in pipeline)."
    exit 1
fi
log "✅ PBF file found: $(ls -lh "$PBF_FILE" | awk '{print $5}')"

# Check tippecanoe
if ! command -v tippecanoe &> /dev/null; then
    log "❌ Error: tippecanoe not found. Run 'brew install tippecanoe'"
    exit 1
fi
log "✅ Tippecanoe installed"

# Check disk space (need at least 5GB free for tiles)
FREE_SPACE=$(df -k . | awk 'NR==2 {print $4}')
if [ "$FREE_SPACE" -lt 5000000 ]; then
    log "❌ Error: Not enough disk space (need ~5GB for Europe tiles)."
    exit 1
fi
log "✅ Disk space OK"

# 1. EXPORT
log ""
log "📤 Step 1: Exporting PBF to GeoJSON..."
GEOJSON_FILE="$PROJECT_ROOT/europe-pois-export.json"
node scripts/export-pbf-to-geojson.mjs --file="$PBF_FILE" --output="$GEOJSON_FILE"

if [ ! -f "$GEOJSON_FILE" ]; then
    log "❌ Error: GeoJSON export failed."
    exit 1
fi
log "✅ GeoJSON exported: $(ls -lh "$GEOJSON_FILE" | awk '{print $5}')"

# 2. GENERATE TILES
log ""
log "🧱 Step 2: Generating Vector Tiles (Tippecanoe)..."
log "   This may take 15-30 minutes for Europe..."
mkdir -p public/tiles
tippecanoe \
  -e public/tiles \
  -z14 -Z0 \
  --drop-densest-as-needed \
  --extend-zooms-if-still-dropping \
  -l pois \
  "$GEOJSON_FILE" \
  --force

TILE_COUNT=$(find public/tiles -name "*.pbf" | wc -l | tr -d ' ')
log "✅ Tiles generated: $TILE_COUNT files"

# 3. CLEANUP
log ""
log "🧹 Cleaning up temporary files..."
rm -f "$GEOJSON_FILE"

# 4. DEPLOY (ask which target)
log ""
log "============================================="
log "🚀 DEPLOYMENT"
log "============================================="

# Default to Firebase, but can be overridden
DEPLOY_TARGET="${DEPLOY_TARGET:-firebase}"

if [ "$DEPLOY_TARGET" = "vps" ]; then
    log "Deploying to VPS..."
    ./scripts/deploy-tiles-vps.sh
else
    log "Deploying to Firebase Hosting..."
    ./scripts/deploy-tiles-firebase.sh
fi

log ""
log "🎉 ALL DONE!"
log "============================================="
