#!/usr/bin/env python3
"""
Test realistico di fba_finance con yfinance 0.2.66
Simula l'uso reale della libreria per identificare il blocco
"""
import sys
import time
from datetime import datetime, timedelta

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

from fba_finance import FinanceClient, Config
from fba_finance.providers.yfinance_provider import YFinanceProvider
from fba_finance.core.rate_limiter import ProviderRateLimiter

def test_yfinance_provider_quotes():
    """Test diretto del provider yfinance"""
    print("\n" + "=" * 70)
    print("TEST 1: YFinanceProvider.get_quote() singolo")
    print("=" * 70)
    
    rate_limiter = ProviderRateLimiter()
    provider = YFinanceProvider(rate_limiter)
    
    test_symbols = ["AAPL", "MSFT", "GOOGL", "AMZN", "META"]
    
    for symbol in test_symbols:
        print(f"\n[{symbol}] Fetching quote...")
        start = time.time()
        quote = provider.get_quote(symbol)
        elapsed = time.time() - start
        
        if quote:
            print(f"  ✅ {symbol}: ${quote.price:.2f} ({elapsed:.2f}s)")
        else:
            print(f"  ❌ {symbol}: Failed ({elapsed:.2f}s)")
        
        time.sleep(0.5)


def test_yfinance_provider_batch():
    """Test batch del provider yfinance"""
    print("\n" + "=" * 70)
    print("TEST 2: YFinanceProvider.get_multiple_quotes() batch")
    print("=" * 70)
    
    rate_limiter = ProviderRateLimiter()
    provider = YFinanceProvider(rate_limiter)
    
    test_symbols = ["AAPL", "MSFT", "GOOGL", "AMZN", "META", "TSLA", "NVDA", "JPM", "V", "WMT"]
    
    print(f"\n[BATCH] Fetching {len(test_symbols)} quotes...")
    start = time.time()
    
    try:
        quotes = provider.get_multiple_quotes(test_symbols)
        elapsed = time.time() - start
        
        print(f"\n  ✅ Batch completato in {elapsed:.2f}s")
        print(f"  Ricevuti: {len(quotes)}/{len(test_symbols)} quotes")
        
        for quote in quotes:
            print(f"    {quote.symbol}: ${quote.price:.2f}")
            
    except Exception as e:
        elapsed = time.time() - start
        print(f"  ❌ Errore batch dopo {elapsed:.2f}s: {e}")


def test_finance_client_single():
    """Test FinanceClient con chiamate singole"""
    print("\n" + "=" * 70)
    print("TEST 3: FinanceClient.get_quote() via yfinance")
    print("=" * 70)
    
    # Forza solo yfinance
    Config.PROVIDER_PRIORITY = ["yfinance"]
    client = FinanceClient()
    
    test_symbols = ["AAPL", "MSFT", "GOOGL"]
    
    for symbol in test_symbols:
        print(f"\n[{symbol}] Via FinanceClient...")
        start = time.time()
        quote = client.get_quote(symbol)
        elapsed = time.time() - start
        
        if quote:
            print(f"  ✅ {symbol}: ${quote.price:.2f} from {quote.source} ({elapsed:.2f}s)")
        else:
            print(f"  ❌ {symbol}: Failed ({elapsed:.2f}s)")
        
        time.sleep(0.5)


def test_finance_client_batch():
    """Test FinanceClient con batch"""
    print("\n" + "=" * 70)
    print("TEST 4: FinanceClient batch via yfinance")
    print("=" * 70)
    
    Config.PROVIDER_PRIORITY = ["yfinance"]
    client = FinanceClient()
    
    test_symbols = ["AAPL", "MSFT", "GOOGL", "AMZN", "META", "TSLA", "NVDA", "JPM", "V", "WMT"]
    
    print(f"\n[BATCH] Fetching {len(test_symbols)} quotes via FinanceClient...")
    start = time.time()
    
    try:
        quotes_dict = client.get_quotes(test_symbols)
        elapsed = time.time() - start
        
        print(f"\n  ✅ Batch completato in {elapsed:.2f}s")
        print(f"  Ricevuti: {len(quotes_dict)}/{len(test_symbols)} quotes")
        
        for symbol, quote in list(quotes_dict.items())[:5]:
            print(f"    {symbol}: ${quote.price:.2f} from {quote.source}")
        if len(quotes_dict) > 5:
            print(f"    ... e altri {len(quotes_dict) - 5} quotes")
            
    except Exception as e:
        elapsed = time.time() - start
        print(f"  ❌ Errore batch dopo {elapsed:.2f}s: {e}")


def test_high_volume_stress():
    """Test ad alto volume per simulare scenario trading platform"""
    print("\n" + "=" * 70)
    print("TEST 5: Stress test - 50 ticker batch")
    print("=" * 70)
    
    Config.PROVIDER_PRIORITY = ["yfinance"]
    client = FinanceClient()
    
    # 50 ticker realistici
    test_symbols = [
        "AAPL", "MSFT", "GOOGL", "AMZN", "META", "TSLA", "NVDA", "JPM", "V", "WMT",
        "JNJ", "UNH", "XOM", "PG", "MA", "HD", "CVX", "LLY", "BAC", "ABBV",
        "PFE", "KO", "AVGO", "PEP", "TMO", "COST", "MRK", "CSCO", "ADBE", "ACN",
        "NKE", "DHR", "ABT", "TXN", "CRM", "VZ", "NEE", "PM", "LIN", "ORCL",
        "CMCSA", "INTC", "DIS", "WFC", "AMD", "QCOM", "RTX", "UNP", "INTU", "IBM"
    ]
    
    print(f"\n[STRESS] Fetching {len(test_symbols)} quotes...")
    start = time.time()
    
    try:
        quotes_dict = client.get_quotes(test_symbols)
        elapsed = time.time() - start
        
        print(f"\n  ✅ Stress test completato in {elapsed:.2f}s")
        print(f"  Ricevuti: {len(quotes_dict)}/{len(test_symbols)} quotes")
        print(f"  Velocità: {len(quotes_dict)/elapsed:.1f} quotes/sec")
        
        # Statistiche
        sources = {}
        for quote in quotes_dict.values():
            sources[quote.source] = sources.get(quote.source, 0) + 1
        
        print("\n  Provider utilizzati:")
        for source, count in sources.items():
            print(f"    {source}: {count}")
            
    except Exception as e:
        elapsed = time.time() - start
        print(f"  ❌ Errore stress test dopo {elapsed:.2f}s: {e}")


def main():
    """Esegue suite di test realistica"""
    print("=" * 70)
    print("TEST REALISTICO FBA_FINANCE + YFINANCE 0.2.66")
    print("=" * 70)
    print(f"\nData test: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    try:
        # Test 1: Provider diretto singolo
        test_yfinance_provider_quotes()
        
        # Test 2: Provider diretto batch
        test_yfinance_provider_batch()
        
        # Test 3: Client singolo
        test_finance_client_single()
        
        # Test 4: Client batch
        test_finance_client_batch()
        
        # Test 5: Stress test
        test_high_volume_stress()
        
        print("\n" + "=" * 70)
        print("TEST COMPLETATI CON SUCCESSO")
        print("=" * 70)
        
    except KeyboardInterrupt:
        print("\n\n⚠️  Test interrotto manualmente")
    except Exception as e:
        print(f"\n\n❌ Errore durante i test: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
