#!/bin/bash
# 🚀 LAUNCH LOCAL OVERPASS (Docker)
# Launches the Overpass API container locally.

set -euo pipefail

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

# 1. Check Docker
if ! command -v docker &> /dev/null; then
    log "❌ Docker is not installed. Install Docker Desktop for Mac first."
    exit 1
fi

# 2. Configuration
DATA_DIR="$HOME/overpass_data"
PLANET_FILE="$DATA_DIR/europe-latest.osm.pbf"
CONTAINER_NAME="overpass_local"

# 3. Check if PBF file exists
if [ ! -f "$PLANET_FILE" ] || [ ! -s "$PLANET_FILE" ]; then
    log "❌ Europe PBF file not found or is empty. Please run Download Europe PBF first."
    exit 1
fi

# 4. Stop and remove existing container (if any)
log "Stopping and removing any existing Overpass container..."
docker stop $CONTAINER_NAME 2>/dev/null || true
docker rm $CONTAINER_NAME 2>/dev/null || true

# 5. Launch Container
log "🚀 Starting Overpass Container (INIT MODE)..."
log "ℹ️  Mounting local PBF: $PLANET_FILE"
log "ℹ️  Indexing will take time (hours) on M-Series chips for Europe."

docker run \
  --platform linux/amd64 \
  -e OVERPASS_META=no \
  -e OVERPASS_MODE=init \
  -e OVERPASS_PLANET_URL=file:///input_file.osm.pbf \
  -e OVERPASS_DIFF_URL=http://download.openstreetmap.fr/replication/europe/france/minute/ \
  -e OVERPASS_RULES_LOAD=10 \
  -v "$DATA_DIR":/db \
  -v "$PLANET_FILE":/input_file.osm.pbf \
  -p 8080:80 \
  --name $CONTAINER_NAME \
  -d \
  wiktorn/overpass-api

log "✅ Container started in background!"
log "📜 Monitor progress with: docker logs -f $CONTAINER_NAME"
log "⏳ Indexing in progress... Wait for Ready to serve requests before using."
log "Overpass local server will be accessible at http://localhost:8080"

