#!/usr/bin/env bash
# 🌍 FULL EUROPE POI PIPELINE
# 
# Master script that runs the complete pipeline:
# 1. Download Europe PBF from Geofabrik (~28 GB)
# 2. Filter POIs with Osmium (~300 MB output)
# 3. Build SQLite index (~350 MB)
# 4. Export GeoJSON for tiles
# 5. Generate Vector Tiles with Tippecanoe
# 6. Deploy everything to VPS
#
# Usage:
#   ./scripts/full-europe-pipeline.sh           # Run everything
#   ./scripts/full-europe-pipeline.sh --skip-download  # Skip download if already done
#   ./scripts/full-europe-pipeline.sh --tiles-only     # Only tiles (skip SQLite)
#   ./scripts/full-europe-pipeline.sh --deploy-only    # Only deploy existing files
#
# Time estimates:
#   Download: 2-4 hours (28 GB)
#   Filter: ~10 minutes
#   SQLite: ~30 seconds
#   GeoJSON: ~5 minutes
#   Tiles: ~15-30 minutes
#   Deploy: ~10-30 minutes (upload)
#
# Total: ~3-5 hours (mostly download)

set -euo pipefail

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

# --- CONFIGURATION ---
SOURCE_PBF="$HOME/overpass_data/europe-latest.osm.pbf"
FILTERED_PBF="europe-roadtrip.osm.pbf"
SQLITE_DB="poi-index.db"
GEOJSON_FILE="europe-pois-export.json"
TILES_DIR="public/tiles"

# --- COLORS ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log() { echo -e "${BLUE}[$(date +'%H:%M:%S')]${NC} $1"; }
success() { echo -e "${GREEN}✅ $1${NC}"; }
warn() { echo -e "${YELLOW}⚠️  $1${NC}"; }
error() { echo -e "${RED}❌ $1${NC}"; }

# --- PARSE ARGUMENTS ---
SKIP_DOWNLOAD=false
TILES_ONLY=false
DEPLOY_ONLY=false
DEPLOY_TARGET="vps"  # vps or firebase

for arg in "$@"; do
  case $arg in
    --skip-download) SKIP_DOWNLOAD=true ;;
    --tiles-only) TILES_ONLY=true ;;
    --deploy-only) DEPLOY_ONLY=true ;;
    --firebase) DEPLOY_TARGET="firebase" ;;
    *) ;;
  esac
done

# --- HEADER ---
echo ""
echo "============================================="
echo "🌍 FULL EUROPE POI PIPELINE"
echo "============================================="
echo ""
log "Configuration:"
echo "   Source PBF:    $SOURCE_PBF"
echo "   Filtered PBF:  $FILTERED_PBF"
echo "   SQLite DB:     $SQLITE_DB"
echo "   Tiles Dir:     $TILES_DIR"
echo "   Deploy Target: $DEPLOY_TARGET"
echo ""

# --- PRE-FLIGHT CHECKS ---
log "Running pre-flight checks..."

# Check tools
MISSING_TOOLS=""
command -v osmium &>/dev/null || MISSING_TOOLS="$MISSING_TOOLS osmium"
command -v tippecanoe &>/dev/null || MISSING_TOOLS="$MISSING_TOOLS tippecanoe"
command -v node &>/dev/null || MISSING_TOOLS="$MISSING_TOOLS node"
command -v sqlite3 &>/dev/null || MISSING_TOOLS="$MISSING_TOOLS sqlite3"

if [ -n "$MISSING_TOOLS" ]; then
    error "Missing tools:$MISSING_TOOLS"
    echo "   Install with: brew install osmium-tool tippecanoe sqlite"
    exit 1
fi
success "All tools installed"

# Check disk space (need ~50GB total)
FREE_SPACE_GB=$(df -g . | awk 'NR==2 {print $4}')
if [ "$FREE_SPACE_GB" -lt 50 ]; then
    warn "Low disk space: ${FREE_SPACE_GB}GB free (recommend 50GB+)"
fi

# --- DEPLOY ONLY MODE ---
if [ "$DEPLOY_ONLY" = true ]; then
    log "Deploy-only mode"
    
    # Deploy tiles
    if [ -d "$TILES_DIR" ]; then
        log "Deploying tiles..."
        if [ "$DEPLOY_TARGET" = "vps" ]; then
            ./scripts/deploy-tiles-vps.sh
        else
            ./scripts/deploy-tiles-firebase.sh
        fi
    else
        warn "No tiles directory found, skipping"
    fi
    
    # Deploy SQLite
    if [ -f "$SQLITE_DB" ]; then
        log "Deploying POI database..."
        ./scripts/deploy-poi-db.sh --file="$SQLITE_DB"
    else
        warn "No SQLite database found, skipping"
    fi
    
    success "Deployment complete!"
    exit 0
fi

# --- STEP 1: DOWNLOAD ---
if [ "$SKIP_DOWNLOAD" = false ] && [ ! -f "$SOURCE_PBF" ]; then
    echo ""
    echo "============================================="
    log "STEP 1/6: Downloading Europe PBF (~28 GB)"
    echo "============================================="
    echo ""
    warn "This will take 2-4 hours depending on your connection"
    
    ./scripts/local-overpass/download-europe-pbf.sh
    
    success "Download complete"
else
    if [ -f "$SOURCE_PBF" ]; then
        success "Step 1: Source PBF exists ($(ls -lh "$SOURCE_PBF" | awk '{print $5}'))"
    else
        warn "Step 1: Skipped (--skip-download)"
    fi
fi

# Check source exists before continuing
if [ ! -f "$SOURCE_PBF" ]; then
    error "Source PBF not found: $SOURCE_PBF"
    echo "   Run without --skip-download or download manually"
    exit 1
fi

# --- STEP 2: FILTER ---
echo ""
echo "============================================="
log "STEP 2/6: Filtering POIs with Osmium (~10 min)"
echo "============================================="
echo ""

if [ -f "$FILTERED_PBF" ] && [ "$FILTERED_PBF" -nt "$SOURCE_PBF" ]; then
    success "Filtered PBF is up-to-date ($(ls -lh "$FILTERED_PBF" | awk '{print $5}'))"
else
    ./scripts/run-full-import.sh
    success "Filtering complete: $(ls -lh "$FILTERED_PBF" | awk '{print $5}')"
fi

# --- STEP 3: BUILD SQLITE INDEX ---
if [ "$TILES_ONLY" = false ]; then
    echo ""
    echo "============================================="
    log "STEP 3/6: Building SQLite Index (~30 sec)"
    echo "============================================="
    echo ""
    
    node scripts/build-poi-index.mjs --file="$FILTERED_PBF" --output="$SQLITE_DB"
    success "SQLite index built: $(ls -lh "$SQLITE_DB" | awk '{print $5}')"
else
    warn "Step 3: Skipped (--tiles-only)"
fi

# --- STEP 4: EXPORT GEOJSON ---
echo ""
echo "============================================="
log "STEP 4/6: Exporting GeoJSON (~5 min)"
echo "============================================="
echo ""

node scripts/export-pbf-to-geojson.mjs --file="$FILTERED_PBF" --output="$GEOJSON_FILE"
success "GeoJSON exported: $(ls -lh "$GEOJSON_FILE" | awk '{print $5}')"

# --- STEP 5: GENERATE TILES ---
echo ""
echo "============================================="
log "STEP 5/6: Generating Vector Tiles (~15-30 min)"
echo "============================================="
echo ""

rm -rf "$TILES_DIR"
mkdir -p "$TILES_DIR"

tippecanoe \
  -e "$TILES_DIR" \
  -z14 -Z0 \
  --drop-densest-as-needed \
  --extend-zooms-if-still-dropping \
  -l pois \
  "$GEOJSON_FILE" \
  --force

TILE_COUNT=$(find "$TILES_DIR" -name "*.pbf" | wc -l | tr -d ' ')
success "Tiles generated: $TILE_COUNT files"

# Cleanup GeoJSON (no longer needed)
rm -f "$GEOJSON_FILE"
log "Cleaned up temporary GeoJSON"

# --- STEP 6: DEPLOY ---
echo ""
echo "============================================="
log "STEP 6/6: Deploying to $DEPLOY_TARGET"
echo "============================================="
echo ""

# Deploy tiles
if [ "$DEPLOY_TARGET" = "vps" ]; then
    ./scripts/deploy-tiles-vps.sh
else
    ./scripts/deploy-tiles-firebase.sh
fi

# Deploy SQLite (VPS only)
if [ "$TILES_ONLY" = false ] && [ "$DEPLOY_TARGET" = "vps" ]; then
    ./scripts/deploy-poi-db.sh --file="$SQLITE_DB"
fi

# --- SUMMARY ---
echo ""
echo "============================================="
echo "🎉 PIPELINE COMPLETE!"
echo "============================================="
echo ""
echo "📊 Generated Files:"
echo "   Filtered PBF:  $(ls -lh "$FILTERED_PBF" 2>/dev/null | awk '{print $5}' || echo 'N/A')"
echo "   SQLite DB:     $(ls -lh "$SQLITE_DB" 2>/dev/null | awk '{print $5}' || echo 'N/A')"
echo "   Tiles:         $TILE_COUNT files"
echo ""
echo "🌐 Deployed to $DEPLOY_TARGET:"
if [ "$DEPLOY_TARGET" = "vps" ]; then
    echo "   Tiles: https://tiles.roadtripper.io/{z}/{x}/{y}.pbf"
    echo "   API:   https://api.roadtripper.io/api/pois/health"
else
    echo "   Tiles: https://[your-app].web.app/tiles/{z}/{x}/{y}.pbf"
fi
echo ""
echo "🧪 Test commands:"
echo "   curl -I https://tiles.roadtripper.io/0/0/0.pbf"
echo "   curl https://api.roadtripper.io/api/pois/stats"
echo "   curl https://api.roadtripper.io/api/pois/137929"
echo ""
