#!/usr/bin/env python3
"""
Test headless de la page web - vérifie que les données s'affichent correctement
"""

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import requests
import time
import json

BASE_URL = "http://localhost:8889"

def setup_driver():
    """Configure Chrome en mode headless"""
    options = Options()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--disable-gpu')
    
    try:
        driver = webdriver.Chrome(options=options)
        return driver
    except Exception as e:
        print(f"❌ Erreur Chrome: {e}")
        return None


def get_api_data(endpoint):
    """Récupère les données de l'API"""
    try:
        response = requests.get(f"{BASE_URL}{endpoint}", timeout=10)
        if response.status_code == 200:
            return response.json()
    except:
        pass
    return None


def test_web_page():
    """Test complet de la page web"""
    print("="*80)
    print("🌐 TEST DE LA PAGE WEB - APOLLO DEGEN BOT")
    print("="*80)
    print()
    
    # Setup driver
    print("🚀 Lancement du navigateur headless...")
    driver = setup_driver()
    
    if not driver:
        print("❌ Impossible de lancer Chrome")
        return
    
    try:
        # Charger la page
        print(f"📄 Chargement de {BASE_URL}...")
        driver.get(BASE_URL)
        
        # Attendre que la page charge
        print("⏳ Attente du chargement de la page...")
        time.sleep(5)  # Attendre que les APIs soient appelées
        
        print("\n" + "="*80)
        print("📊 VÉRIFICATION DES ÉLÉMENTS AFFICHÉS")
        print("="*80)
        
        # Test 1: Stats Widget
        print("\n1️⃣  Widget Statistiques")
        print("-"*40)
        
        try:
            total_trades = driver.find_element(By.ID, "total-trades").text
            wins = driver.find_element(By.ID, "wins").text
            losses = driver.find_element(By.ID, "losses").text
            win_rate = driver.find_element(By.ID, "win-rate").text
            total_pnl = driver.find_element(By.ID, "total-pnl").text
            
            print(f"   Affiché sur la page:")
            print(f"     Total trades: {total_trades}")
            print(f"     Wins: {wins}")
            print(f"     Losses: {losses}")
            print(f"     Win rate: {win_rate}")
            print(f"     Total PnL: {total_pnl}")
            
            # Comparer avec l'API
            api_data = get_api_data("/api/status")
            if api_data:
                stats = api_data.get('stats', {})
                print(f"\n   Depuis l'API /api/status:")
                print(f"     Total trades: {stats.get('total_trades', 0)}")
                print(f"     Wins: {stats.get('wins', 0)}")
                print(f"     Losses: {stats.get('losses', 0)}")
                print(f"     Win rate: {stats.get('win_rate', 0)}")
                print(f"     Total PnL: {stats.get('total_pnl', 0)}")
                
                # Vérifier concordance
                if total_trades != str(stats.get('total_trades', 0)):
                    print(f"\n   ❌ BUG: Total trades ne correspond pas!")
                    print(f"      Page: {total_trades} | API: {stats.get('total_trades', 0)}")
                else:
                    print(f"\n   ✅ Stats concordent avec l'API")
        except Exception as e:
            print(f"   ❌ Erreur lecture stats: {e}")
        
        # Test 2: Positions actives
        print("\n2️⃣  Positions Actives")
        print("-"*40)
        
        try:
            positions_container = driver.find_element(By.ID, "positions-container")
            positions_html = positions_container.get_attribute('innerHTML')
            
            if "Aucune position ouverte" in positions_html:
                print(f"   Affiché: Aucune position ouverte")
            elif "Loading" in positions_html or "pulse" in positions_html:
                print(f"   ⚠️  Affiche 'Loading...'")
            else:
                positions = driver.find_elements(By.CLASS_NAME, "position")
                print(f"   Affiché: {len(positions)} positions")
            
            # Comparer avec l'API
            api_data = get_api_data("/api/positions/open")
            if api_data:
                count = api_data.get('count', 0)
                print(f"\n   Depuis l'API /api/positions/open:")
                print(f"     Count: {count}")
                
                if count == 0 and "Aucune position ouverte" in positions_html:
                    print(f"\n   ✅ Affichage correct (0 positions)")
                elif count > 0:
                    positions_on_page = len(driver.find_elements(By.CLASS_NAME, "position"))
                    if positions_on_page != count:
                        print(f"\n   ❌ BUG: Nombre de positions ne correspond pas!")
                        print(f"      Page: {positions_on_page} | API: {count}")
                    else:
                        print(f"\n   ✅ Positions concordent avec l'API")
        except Exception as e:
            print(f"   ❌ Erreur lecture positions: {e}")
        
        # Test 3: Wallet
        print("\n3️⃣  Widget Wallet")
        print("-"*40)
        
        try:
            bnb_balance = driver.find_element(By.ID, "bnb-balance").text
            usdt_balance = driver.find_element(By.ID, "usdt-balance").text
            wallet_address = driver.find_element(By.ID, "wallet-address").text
            
            print(f"   Affiché sur la page:")
            print(f"     BNB: {bnb_balance}")
            print(f"     USDT: {usdt_balance}")
            print(f"     Address: {wallet_address[:20]}...")
            
            # Comparer avec l'API
            api_data = get_api_data("/api/status")
            if api_data:
                wallet = api_data.get('wallet', {})
                print(f"\n   Depuis l'API:")
                print(f"     BNB: {wallet.get('bnb', 0)}")
                print(f"     USDT: {wallet.get('usdt', 0)}")
                
                if str(wallet.get('bnb', 0)) in bnb_balance:
                    print(f"\n   ✅ Wallet concordent avec l'API")
                else:
                    print(f"\n   ❌ BUG: Balances ne correspondent pas!")
        except Exception as e:
            print(f"   ❌ Erreur lecture wallet: {e}")
        
        # Test 4: Logs
        print("\n4️⃣  Logs")
        print("-"*40)
        
        try:
            logs_container = driver.find_element(By.ID, "logs-container")
            logs_html = logs_container.get_attribute('innerHTML')
            
            if "Chargement" in logs_html or "Loading" in logs_html:
                print(f"   ⚠️  Affiche 'Chargement...'")
            elif "Aucun log" in logs_html:
                print(f"   Affiché: Aucun log disponible")
            else:
                log_lines = driver.find_elements(By.CLASS_NAME, "log-line")
                print(f"   Affiché: {len(log_lines)} lignes de log")
            
            # Comparer avec l'API
            api_data = get_api_data("/api/logs")
            if api_data:
                logs = api_data.get('logs', [])
                print(f"\n   Depuis l'API /api/logs:")
                print(f"     Logs: {len(logs)} lignes")
                
                if len(logs) == 0 and "Aucun log" in logs_html:
                    print(f"\n   ✅ Logs concordent (vides)")
                elif len(logs) > 0:
                    log_lines_on_page = len(driver.find_elements(By.CLASS_NAME, "log-line"))
                    if log_lines_on_page == 0:
                        print(f"\n   ❌ BUG: Logs ne s'affichent pas!")
                        print(f"      Page: 0 lignes | API: {len(logs)} lignes")
                    else:
                        print(f"\n   ✅ Logs s'affichent correctement")
        except Exception as e:
            print(f"   ❌ Erreur lecture logs: {e}")
        
        # Test 5: Market Data (BTC Chart)
        print("\n5️⃣  Market Data / BTC Chart")
        print("-"*40)
        
        try:
            btc_price = driver.find_element(By.ID, "btc-price").text
            btc_change = driver.find_element(By.ID, "btc-change").text
            market_regime = driver.find_element(By.ID, "market-regime").text
            
            print(f"   Affiché sur la page:")
            print(f"     BTC Price: {btc_price}")
            print(f"     Change 1h: {btc_change}")
            print(f"     Market Regime: {market_regime}")
            
            # Comparer avec l'API
            api_data = get_api_data("/api/market_data")
            if api_data:
                print(f"\n   Depuis l'API /api/market_data:")
                print(f"     Current price: ${api_data.get('current_price', 0):,.2f}")
                print(f"     Change 1h: {api_data.get('change_1h', 0):+.2f}%")
                print(f"     Regime: {api_data.get('regime', 'UNKNOWN')}")
                
                if str(api_data.get('current_price', 0)) in btc_price.replace(',', ''):
                    print(f"\n   ✅ Market data concordent")
                else:
                    print(f"\n   ⚠️  Market data peuvent différer (normal si mis à jour)")
        except Exception as e:
            print(f"   ❌ Erreur lecture market data: {e}")
        
        # Résumé
        print("\n" + "="*80)
        print("📋 RÉSUMÉ DU TEST")
        print("="*80)
        
        # Chercher les erreurs JavaScript
        print("\n🔍 Erreurs JavaScript:")
        logs = driver.get_log('browser')
        js_errors = [log for log in logs if log['level'] == 'SEVERE']
        
        if js_errors:
            print(f"   ❌ {len(js_errors)} erreurs JavaScript détectées:")
            for error in js_errors[:5]:
                print(f"      - {error['message'][:100]}")
        else:
            print(f"   ✅ Aucune erreur JavaScript")
        
        print("\n✅ Test terminé")
        
    except Exception as e:
        print(f"\n❌ Erreur durant le test: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        print("\n🔒 Fermeture du navigateur...")
        driver.quit()


if __name__ == '__main__':
    test_web_page()
