#!/usr/bin/env bash
# 🧪 TEST POI PIPELINE
# Quick test to validate the pipeline on France data

set -euo pipefail

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

echo ""
echo "============================================="
echo "🧪 TESTING POI PIPELINE (France subset)"
echo "============================================="
echo ""

# --- CHECK TOOLS ---
echo "1. Checking tools..."
command -v osmium &>/dev/null || { echo "❌ osmium not found"; exit 1; }
command -v tippecanoe &>/dev/null || { echo "❌ tippecanoe not found"; exit 1; }
command -v node &>/dev/null || { echo "❌ node not found"; exit 1; }
command -v sqlite3 &>/dev/null || { echo "❌ sqlite3 not found"; exit 1; }
echo "   ✅ All tools installed"
echo ""

# --- CHECK SOURCE PBF ---
echo "2. Checking source PBF..."
if [ -f "france-roadtrip.osm.pbf" ]; then
    echo "   ✅ france-roadtrip.osm.pbf exists ($(ls -lh france-roadtrip.osm.pbf | awk '{print $5}'))"
    PBF_FILE="france-roadtrip.osm.pbf"
else
    echo "   ❌ france-roadtrip.osm.pbf not found"
    echo "   Run: ./scripts/run-full-import.sh (with France PBF)"
    exit 1
fi
echo ""

# --- BUILD SQLITE ---
echo "3. Building SQLite index..."
rm -f test-poi-index.db
node scripts/build-poi-index.mjs --file="$PBF_FILE" --output=test-poi-index.db

if [ -f "test-poi-index.db" ]; then
    DB_SIZE=$(ls -lh test-poi-index.db | awk '{print $5}')
    POI_COUNT=$(sqlite3 test-poi-index.db "SELECT COUNT(*) FROM pois" 2>/dev/null || echo "?")
    echo "   ✅ Created test-poi-index.db ($DB_SIZE, $POI_COUNT POIs)"
else
    echo "   ❌ Failed to create SQLite database"
    exit 1
fi
echo ""

# --- TEST QUERIES ---
echo "4. Testing SQLite queries..."

# Test single lookup
echo -n "   - Lookup by OSM ID: "
RESULT=$(sqlite3 test-poi-index.db "SELECT name FROM pois LIMIT 1" 2>/dev/null)
if [ -n "$RESULT" ]; then
    echo "✅ ($RESULT)"
else
    echo "❌"
fi

# Test search
echo -n "   - Search by name 'tour': "
COUNT=$(sqlite3 test-poi-index.db "SELECT COUNT(*) FROM pois WHERE name LIKE '%tour%'" 2>/dev/null)
echo "✅ ($COUNT results)"

# Test category
echo -n "   - Category 'nature': "
COUNT=$(sqlite3 test-poi-index.db "SELECT COUNT(*) FROM pois WHERE category = 'nature'" 2>/dev/null)
echo "✅ ($COUNT results)"

# Test performance
echo -n "   - Performance (100 random lookups): "
START=$(node -e "console.log(Date.now())")
for i in {1..100}; do
    sqlite3 test-poi-index.db "SELECT * FROM pois WHERE osm_id = (SELECT osm_id FROM pois ORDER BY RANDOM() LIMIT 1)" > /dev/null 2>&1
done
END=$(node -e "console.log(Date.now())")
DURATION=$((END - START))
AVG=$(echo "scale=2; $DURATION / 100" | bc)
echo "✅ (${AVG}ms average)"
echo ""

# --- GENERATE SMALL TILES ---
echo "5. Generating test tiles (zoom 0-8 only)..."
rm -rf test-tiles
mkdir -p test-tiles

# Export small GeoJSON
node scripts/export-pbf-to-geojson.mjs --file="$PBF_FILE" --output=test-pois.json 2>/dev/null || true

if [ -f "test-pois.json" ]; then
    tippecanoe \
        -e test-tiles \
        -z8 -Z0 \
        --drop-densest-as-needed \
        -l pois \
        test-pois.json \
        --force \
        --quiet
    
    TILE_COUNT=$(find test-tiles -name "*.pbf" 2>/dev/null | wc -l | tr -d ' ')
    echo "   ✅ Generated $TILE_COUNT test tiles"
    rm -f test-pois.json
else
    echo "   ⚠️  Skipped tiles (GeoJSON export failed)"
fi
echo ""

# --- SUMMARY ---
echo "============================================="
echo "✅ PIPELINE TEST PASSED"
echo "============================================="
echo ""
echo "📊 Results:"
echo "   SQLite DB:    test-poi-index.db ($DB_SIZE)"
echo "   POI Count:    $POI_COUNT"
echo "   Avg Lookup:   ${AVG}ms"
echo "   Test Tiles:   $TILE_COUNT files"
echo ""
echo "🚀 Ready for Europe pipeline:"
echo "   ./scripts/full-europe-pipeline.sh"
echo ""

# Cleanup
rm -f test-poi-index.db
rm -rf test-tiles
echo "🧹 Cleaned up test files"
