#!/bin/bash

# BestCDN C++ Tester Runner Script
# Builds and runs the high-performance C++ tester with optional provider selection

set -e

echo "🚀 BestCDN C++ High-Performance Tester"
echo "======================================"

# Show usage if help is requested
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
    echo "Usage: $0 [provider1] [provider2] ..."
    echo ""
    echo "Available providers:"
    echo "  cloudflare  - Test Cloudflare IPs"
    echo "  fastly      - Test Fastly IPs"
    echo "  edgeone     - Test EdgeOne (Tencent Cloud) IPs"
    echo "  esa         - Test ESA (Alibaba Cloud) IPs"
    echo ""
    echo "Examples:"
    echo "  $0                    # Test all providers"
    echo "  $0 edgeone           # Test only EdgeOne"
    echo "  $0 edgeone cloudflare # Test EdgeOne and Cloudflare"
    echo ""
    exit 0
fi

# Check if C++ tester is built
if [ ! -f "src/cpp/bestcdn_tester" ]; then
    echo "🔨 C++ tester not found. Building..."
    chmod +x build_cpp.sh
    ./build_cpp.sh
    
    if [ $? -ne 0 ]; then
        echo "❌ Build failed. Exiting."
        exit 1
    fi
fi

# Determine which providers to check/test
if [ $# -gt 0 ]; then
    SELECTED_PROVIDERS=("$@")
    echo "🎯 Selected providers: ${SELECTED_PROVIDERS[*]}"
else
    SELECTED_PROVIDERS=(cloudflare fastly edgeone esa)
    echo "🌐 Testing all available providers"
fi

# Check if IP lists exist for selected providers
missing_files=()
for provider in "${SELECTED_PROVIDERS[@]}"; do
    if [ ! -f "ip_lists/${provider}.txt" ]; then
        missing_files+=("ip_lists/${provider}.txt")
    fi
done

if [ ${#missing_files[@]} -gt 0 ]; then
    echo "⚠️  Warning: Missing IP list files:"
    for file in "${missing_files[@]}"; do
        echo "  - $file"
    done
    echo ""
    echo "Please add your IP lists to the ip_lists/ directory before running."
    echo "Each file should contain one IP per line or CIDR ranges."
    echo ""
    read -p "Continue anyway? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Create results directory
mkdir -p results

# Run the C++ tester with selected providers
echo ""
echo "🧪 Starting IP accessibility tests..."
echo "   Real-time results will be displayed below"
echo "   Press Ctrl+C to stop"
echo ""

cd src/cpp
if [ $# -gt 0 ]; then
    ./bestcdn_tester "$@"
else
    ./bestcdn_tester
fi
cd ../..

echo ""
echo "✅ Testing completed!"
echo "📊 Check the results/ directory for output files"
echo ""
echo "💡 To add geolocation data to results:"
echo "   ./enhance_results.sh"