#!/usr/bin/env python3
"""
Test per FMP e Finnhub providers
"""
import sys
import time

sys.path.insert(0, '/Users/faustobandini/Library/CloudStorage/OneDrive-Personale/Sviluppo/IA/fba_finance')

from fba_finance import Config
from fba_finance.providers.fmp_provider import FMPProvider
from fba_finance.providers.finnhub_provider import FinnhubProvider
from fba_finance.core.rate_limiter import ProviderRateLimiter

def test_fmp():
    """Test FMP provider (batch optimized)"""
    print("\n" + "="*70)
    print("TEST FMP PROVIDER (Batch Optimized)")
    print("="*70)
    
    if not Config.FMP_API_KEY:
        print("❌ FMP_API_KEY not configured")
        return
    
    rate_limiter = ProviderRateLimiter()
    provider = FMPProvider(rate_limiter=rate_limiter)
    
    if not provider.available:
        print(f"❌ Provider not available: {provider.last_error}")
        return
    
    print("✅ Provider available")
    
    # Test batch quotes (recommended for FMP)
    print("\n[BATCH TEST] Get multiple quotes (efficient)...")
    symbols = ["AAPL", "MSFT", "GOOGL", "AMZN", "META"]
    
    start = time.time()
    quotes = provider.get_multiple_quotes(symbols)
    elapsed = time.time() - start
    
    print(f"✅ Got {len(quotes)}/{len(symbols)} quotes in {elapsed:.2f}s")
    for quote in quotes:
        print(f"   {quote.symbol}: ${quote.price:.2f}")
    
    # Test historical
    print("\n[HISTORICAL TEST]...")
    from datetime import datetime, timedelta
    end = datetime.now()
    start_date = end - timedelta(days=7)
    
    start_time = time.time()
    hist = provider.get_historical("AAPL", start_date, end)
    elapsed = time.time() - start_time
    
    if hist and not hist.data.empty:
        print(f"✅ Historical: {len(hist.data)} records in {elapsed:.2f}s")
    else:
        print(f"❌ Historical failed")


def test_finnhub():
    """Test Finnhub provider"""
    print("\n" + "="*70)
    print("TEST FINNHUB PROVIDER")
    print("="*70)
    
    if not Config.FINNHUB_API_KEY:
        print("❌ FINNHUB_API_KEY not configured")
        return
    
    rate_limiter = ProviderRateLimiter()
    provider = FinnhubProvider(rate_limiter=rate_limiter)
    
    if not provider.available:
        print(f"❌ Provider not available: {provider.last_error}")
        return
    
    print("✅ Provider available")
    
    # Test single quote
    print("\n[SINGLE QUOTE TEST]...")
    start = time.time()
    quote = provider.get_quote("AAPL")
    elapsed = time.time() - start
    
    if quote:
        print(f"✅ AAPL: ${quote.price:.2f} ({elapsed:.2f}s)")
    else:
        print(f"❌ Quote failed")
    
    time.sleep(1)  # Rate limiting
    
    # Test batch quotes
    print("\n[BATCH TEST] Get multiple quotes...")
    symbols = ["AAPL", "MSFT", "GOOGL"]
    
    start = time.time()
    quotes = provider.get_multiple_quotes(symbols)
    elapsed = time.time() - start
    
    print(f"✅ Got {len(quotes)}/{len(symbols)} quotes in {elapsed:.2f}s")
    for quote in quotes:
        print(f"   {quote.symbol}: ${quote.price:.2f}")
    
    # Test historical
    print("\n[HISTORICAL TEST]...")
    from datetime import datetime, timedelta
    end = datetime.now()
    start_date = end - timedelta(days=7)
    
    start_time = time.time()
    hist = provider.get_historical("AAPL", start_date, end)
    elapsed = time.time() - start_time
    
    if hist and not hist.data.empty:
        print(f"✅ Historical: {len(hist.data)} records in {elapsed:.2f}s")
    else:
        print(f"❌ Historical failed")


def test_integration():
    """Test integration with FinanceClient"""
    print("\n" + "="*70)
    print("TEST INTEGRATION WITH FINANCECLIENT")
    print("="*70)
    
    from fba_finance import FinanceClient
    
    client = FinanceClient()
    
    # Get available providers
    providers = client.aggregator.get_available_providers()
    print(f"\nAvailable providers: {providers}")
    
    if "fmp" in providers:
        print("✅ FMP available")
    if "finnhub" in providers:
        print("✅ Finnhub available")
    
    # Test quote
    print("\n[QUOTE TEST] Get AAPL quote...")
    start = time.time()
    quote = client.get_quote("AAPL")
    elapsed = time.time() - start
    
    if quote:
        print(f"✅ AAPL: ${quote.price:.2f} from {quote.source} ({elapsed:.2f}s)")
    else:
        print(f"❌ Quote failed")


if __name__ == "__main__":
    print("="*70)
    print("FMP & FINNHUB PROVIDER TEST SUITE")
    print("="*70)
    
    try:
        test_fmp()
        time.sleep(2)
        test_finnhub()
        time.sleep(2)
        test_integration()
        
        print("\n" + "="*70)
        print("✅ ALL TESTS COMPLETED")
        print("="*70)
        
    except KeyboardInterrupt:
        print("\n\n⚠️  Tests interrupted")
    except Exception as e:
        print(f"\n\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
