#!/bin/bash
# 🚀 FULL IMPORT PIPELINE
# Orchestrates the entire flow: Filter PBF -> Import JS -> Deduplicate DB

set -e # Stop on error

# Configuration
SOURCE_PBF="$HOME/overpass_data/europe-latest.osm.pbf" # Changed to Europe PBF
OUTPUT_PBF="europe-roadtrip.osm.pbf" # Changed output to Europe
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo "============================================="
echo "🌍 ROADTRIP DB IMPORT PIPELINE (Europe Edition)"
echo "============================================="

# 1. CHECK TOOLS
if ! command -v osmium &> /dev/null; then
    echo "❌ osmium-tool not found. Run 'brew install osmium-tool'"
    exit 1
fi

# 2. FILTER PBF (The "Ultra-Wide" Query for Europe)
echo ""
echo "🔍 Step 1: Filtering OSM Data (Extracting Roadtrip POIs for Europe)..."
echo "   Source: $SOURCE_PBF"
echo "   Target: $OUTPUT_PBF"

osmium tags-filter "$SOURCE_PBF" \
  n/natural \
  n/waterway=waterfall,dam \
  n/geological \
  n/tourism \
  n/historic \
  n/amenity=place_of_worship,theatre,cinema,marketplace,restaurant,cafe,bar,fuel,ferry_terminal \
  n/leisure \
  n/sport=climbing,swimming \
  n/craft \
  n/shop=antiques \
  n/aerialway \
  n/man_made=lighthouse,windmill,watermill,pier \
  n/mountain_pass=yes \
  n/bridge \
  n/railway=funicular,preserved,narrow_gauge \
  n/historic=wreck \
  n/leisure=marina,beach_resort \
  n/tourism=zoo,theme_park \
  -o "$OUTPUT_PBF" --overwrite

echo "✅ Filtering complete."

# 2. IMPORT TO FIRESTORE (DEPRECATED - Data is now extracted via GeoJSON for map tiles)
# echo ""
# echo "📥 Step 2: Importing to Firestore (Node.js)..."
# cd "$PROJECT_ROOT"
# node scripts/seed-local-pbf.mjs --file="$OUTPUT_PBF" --execute
# echo "✅ Import complete."


# 3. DEDUPLICATE & CLEANUP (Now Step 2)
echo ""
echo "🧹 Step 2: Deduplicating & Migrating Legacy IDs..."
node scripts/deduplicate-database.mjs --execute

echo ""
echo "============================================="
echo "🎉 PIPELINE FINISHED SUCCESSFULLY!"
echo "================================="
