#!/usr/bin/env python3
"""
Test script for Brave API weather functionality.
This script demonstrates how to use Brave Search API for weather queries.
"""

import os
import sys
import json
import requests

def test_brave_api_key():
    """Check if Brave API key is configured."""
    api_key = os.environ.get('BRAVE_API_KEY')
    
    if not api_key:
        print("❌ BRAVE_API_KEY environment variable not set")
        print("Please set it with: export BRAVE_API_KEY='your_key_here'")
        return False
    
    print(f"✅ BRAVE_API_KEY found: {api_key[:10]}...")
    return True

def test_weather_query(location="Limassol Cyprus"):
    """Test weather query using Brave Search API."""
    api_key = os.environ.get('BRAVE_API_KEY')
    
    if not api_key:
        print("Skipping API test - no API key")
        return False
    
    # Brave Search API endpoint
    url = "https://api.search.brave.com/res/v1/web/search"
    
    # Query for weather
    params = {
        'q': f'weather {location}',
        'count': 5  # Get top 5 results
    }
    
    headers = {
        'Accept': 'application/json',
        'Accept-Encoding': 'gzip',
        'X-Subscription-Token': api_key
    }
    
    try:
        print(f"🌤️  Querying weather for: {location}")
        response = requests.get(url, params=params, headers=headers, timeout=10)
        
        if response.status_code == 200:
            data = response.json()
            print(f"✅ API request successful")
            
            # Extract and display relevant information
            if 'web' in data and 'results' in data['web']:
                results = data['web']['results']
                print(f"\n📊 Found {len(results)} search results")
                
                # Display first result (likely contains weather info)
                if results:
                    first_result = results[0]
                    print(f"\n🔍 First result:")
                    print(f"   Title: {first_result.get('title', 'N/A')}")
                    print(f"   URL: {first_result.get('url', 'N/A')}")
                    print(f"   Description: {first_result.get('description', 'N/A')[:100]}...")
                    
                    # Check if weather data is in description
                    desc = first_result.get('description', '').lower()
                    weather_terms = ['temperature', '°c', '°f', 'humidity', 'wind', 'weather', 'forecast']
                    if any(term in desc for term in weather_terms):
                        print("   ✅ Contains weather information")
                    else:
                        print("   ⚠️  May not contain weather data")
            
            return True
        else:
            print(f"❌ API request failed: {response.status_code}")
            print(f"Response: {response.text[:200]}")
            return False
            
    except requests.exceptions.RequestException as e:
        print(f"❌ Network error: {e}")
        return False
    except json.JSONDecodeError as e:
        print(f"❌ JSON decode error: {e}")
        return False

def test_fallback_open_meteo(location="Limassol"):
    """Test fallback to Open-Meteo API."""
    # Coordinates for Limassol, Cyprus
    latitude = 34.7071
    longitude = 33.0226
    
    url = f"https://api.open-meteo.com/v1/forecast"
    params = {
        'latitude': latitude,
        'longitude': longitude,
        'current_weather': True,
        'hourly': 'temperature_2m,relative_humidity_2m,wind_speed_10m'
    }
    
    try:
        print(f"\n🌍 Testing Open-Meteo fallback for {location}")
        response = requests.get(url, params=params, timeout=10)
        
        if response.status_code == 200:
            data = response.json()
            
            if 'current_weather' in data:
                current = data['current_weather']
                print(f"✅ Open-Meteo API working")
                print(f"   Temperature: {current.get('temperature', 'N/A')}°C")
                print(f"   Wind Speed: {current.get('windspeed', 'N/A')} km/h")
                print(f"   Weather Code: {current.get('weathercode', 'N/A')}")
                return True
        else:
            print(f"❌ Open-Meteo failed: {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ Open-Meteo error: {e}")
        return False

def main():
    """Main test function."""
    print("=" * 60)
    print("Brave API Weather Monitoring Test")
    print("=" * 60)
    
    # Test 1: Check API key
    api_key_ok = test_brave_api_key()
    
    # Test 2: Try Brave API (if key available)
    brave_ok = False
    if api_key_ok:
        brave_ok = test_weather_query("Limassol Cyprus")
    
    # Test 3: Always test Open-Meteo fallback
    open_meteo_ok = test_fallback_open_meteo("Limassol")
    
    # Summary
    print("\n" + "=" * 60)
    print("TEST SUMMARY")
    print("=" * 60)
    
    if api_key_ok:
        print(f"✅ BRAVE_API_KEY: Configured")
    else:
        print(f"❌ BRAVE_API_KEY: Not configured (required for Brave API)")
    
    if brave_ok:
        print(f"✅ Brave API: Working")
    elif api_key_ok:
        print(f"⚠️  Brave API: Failed (check key or network)")
    else:
        print(f"⏭️  Brave API: Skipped (no API key)")
    
    if open_meteo_ok:
        print(f"✅ Open-Meteo Fallback: Working")
    else:
        print(f"❌ Open-Meteo Fallback: Failed")
    
    # Recommendations
    print("\n" + "=" * 60)
    print("RECOMMENDATIONS")
    print("=" * 60)
    
    if not api_key_ok:
        print("1. Get free Brave API key from: https://brave.com/search/api/")
        print("2. Set environment variable: export BRAVE_API_KEY='your_key'")
    
    if not brave_ok and api_key_ok:
        print("1. Check API key validity in Brave dashboard")
        print("2. Verify network connectivity")
        print("3. Check rate limits")
    
    if not open_meteo_ok:
        print("1. Check network connectivity")
        print("2. Verify Open-Meteo service status")
    
    print("\nFor production use:")
    print("- Implement caching to reduce API calls")
    print("- Set up proper error handling")
    print("- Monitor API usage in Brave dashboard")
    print("- Use Open-Meteo as reliable fallback")

if __name__ == "__main__":
    # Check if requests module is available
    try:
        import requests
    except ImportError:
        print("❌ Required module 'requests' not installed")
        print("Install with: pip install requests")
        sys.exit(1)
    
    main()