#!/usr/bin/env python3
"""
Test script for offline geolocation functionality using qqwry-py3
"""

import sys
import os

def install_qqwry_library():
    """Install qqwry-py3 library if not available"""
    try:
        import qqwry
        return True
    except ImportError:
        print("📦 Installing qqwry-py3 library...")
        try:
            import subprocess
            subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'qqwry-py3'])
            print("✓ qqwry-py3 library installed successfully")
            return True
        except Exception as e:
            print(f"✗ Failed to install qqwry-py3: {e}")
            return False

def test_geolocation():
    """Test the offline geolocation functionality"""
    
    print("🧪 Testing Offline Geolocation with QQWry Database (qqwry-py3)")
    print("=" * 60)
    
    # Ensure library is available
    if not install_qqwry_library():
        return False
    
    # Import after installation
    try:
        from qqwry import QQwry
    except ImportError:
        print("✗ Failed to import qqwry library")
        return False
    
    # Test IPs from different regions
    test_ips = [
        "8.8.8.8",          # Google DNS (US)
        "114.114.114.114",  # China DNS
        "1.1.1.1",          # Cloudflare DNS
        "223.5.5.5",        # Alibaba DNS (China)
        "180.76.76.76",     # Baidu DNS (China)
        "208.67.222.222",   # OpenDNS (US)
        "119.29.29.29",     # Tencent DNS (China)
        "202.96.128.86",    # China Telecom
        "221.5.88.88",      # China Mobile
    ]
    
    try:
        # Check if database exists
        db_path = "qqwry.dat"
        if not os.path.exists(db_path):
            print(f"📥 QQWry database not found, downloading...")
            import urllib.request
            url = "https://github.com/metowolf/qqwry.dat/releases/latest/download/qqwry.dat"
            urllib.request.urlretrieve(url, db_path)
            print(f"✓ Database downloaded to {db_path}")
        
        # Initialize QQWry
        q = QQwry()
        q.load_file(db_path)
        
        print(f"✓ QQWry database loaded successfully")
        print()
        
        # Test each IP
        for ip in test_ips:
            try:
                country, area = q.lookup(ip)
                # Format location
                if country and area:
                    if area in country or country in area:
                        location = country if len(country) > len(area) else area
                    else:
                        location = f"{country}, {area}"
                elif country:
                    location = country
                elif area:
                    location = area
                else:
                    location = "Unknown"
                
                print(f"📍 {ip:<15} → {location}")
            except Exception as e:
                print(f"❌ {ip:<15} → Error: {e}")
        
        print()
        print("✅ All tests completed successfully!")
        print("🚀 Offline geolocation with qqwry-py3 is working perfectly!")
        
    except Exception as e:
        print(f"❌ Test failed: {e}")
        return False
    
    return True

if __name__ == "__main__":
    success = test_geolocation()
    sys.exit(0 if success else 1)