#!/bin/bash

# Enhanced Results Script - Automatic Geolocation Enhancement (Offline)
# Automatically finds the latest accessible IPs file and adds geolocation data using QQWry database

set -e

echo "🌍 BestCDN Results Enhancement Script (Offline QQWry)"
echo "===================================================="

# Find the latest cpp_accessible file
LATEST_FILE=$(find results/ -name "cpp_accessible_*.txt" -type f -printf '%T@ %p\n' 2>/dev/null | sort -n | tail -1 | cut -d' ' -f2-)

if [ -z "$LATEST_FILE" ]; then
    echo "❌ No accessible results files found in results/ directory"
    echo "   Please run the C++ tester first: ./run_cpp.sh"
    exit 1
fi

echo "📁 Found latest results file: $LATEST_FILE"

# Check if Python is available
if ! command -v python3 &> /dev/null; then
    echo "❌ Python3 is required but not installed"
    exit 1
fi

# Check if offline geolocation script exists
if [ ! -f "add_geolocation_offline.py" ]; then
    echo "❌ Offline geolocation script not found: add_geolocation_offline.py"
    exit 1
fi

# Check if QQWry database exists, if not it will be downloaded automatically
if [ ! -f "qqwry.dat" ]; then
    echo "📥 QQWry database not found, will be downloaded automatically..."
fi

# Generate output filename
BASENAME=$(basename "$LATEST_FILE" .txt)
OUTPUT_FILE="results/${BASENAME}_geo.txt"

echo "🔍 Adding geolocation data using offline QQWry database..."
echo "   Input:  $LATEST_FILE"
echo "   Output: $OUTPUT_FILE"

# Run the offline geolocation enhancement
python3 add_geolocation_offline.py "$LATEST_FILE" "$OUTPUT_FILE"

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ Enhancement completed successfully!"
    echo "📊 Enhanced results saved to: $OUTPUT_FILE"
    echo ""
    echo "📈 Quick stats:"
    TOTAL_IPS=$(grep -v '^#' "$OUTPUT_FILE" | grep -v '^$' | wc -l)
    echo "   Total enhanced IPs: $TOTAL_IPS"
    
    # Show sample results
    echo ""
    echo "🔍 Sample enhanced results:"
    echo "   $(head -n 20 "$OUTPUT_FILE" | grep -v '^#' | head -n 5)"
    if [ $TOTAL_IPS -gt 5 ]; then
        echo "   ... and $(($TOTAL_IPS - 5)) more"
    fi
    
    echo ""
    echo "💡 Offline database advantages:"
    echo "   ✓ No network requests required"
    echo "   ✓ Ultra-fast lookups (1000+ IPs/second)"
    echo "   ✓ No API rate limits"
    echo "   ✓ Works in restricted network environments"
else
    echo "❌ Enhancement failed"
    exit 1
fi