"""
Vérification des performances du dashboard
"""
import re
from collections import Counter

def analyze_dashboard_performance():
    print("="*70)
    print("🔍 ANALYSE PERFORMANCE DASHBOARD")
    print("="*70)
    
    with open('dashboard.html', 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 1. Analyser les setInterval
    print("\n📊 INTERVALLES DE MISE À JOUR:")
    print("-" * 70)
    
    intervals = re.findall(r'setInterval\([^,]+,\s*(\d+)\)', content)
    interval_stats = Counter(intervals)
    
    total_calls_per_hour = 0
    for interval_ms, count in sorted(interval_stats.items(), key=lambda x: int(x[0])):
        interval_s = int(interval_ms) / 1000
        calls_per_hour = (3600 / interval_s) * count
        total_calls_per_hour += calls_per_hour
        
        print(f"   {interval_ms:>6}ms ({interval_s:>4.0f}s) × {count:>2} timers = {calls_per_hour:>6.0f} appels/h")
    
    print(f"\n   📈 TOTAL: ~{total_calls_per_hour:.0f} requêtes/heure")
    
    if total_calls_per_hour < 1000:
        print("   ✅ Performance EXCELLENTE (< 1000 req/h)")
    elif total_calls_per_hour < 2000:
        print("   ⚠️ Performance CORRECTE (1000-2000 req/h)")
    else:
        print("   ❌ Performance FAIBLE (> 2000 req/h)")
    
    # 2. Analyser les animations CSS
    print("\n🎨 ANIMATIONS CSS:")
    print("-" * 70)
    
    active_animations = len(re.findall(r'animation:\s*[^;]+;(?!\s*/\*)', content))
    commented_animations = len(re.findall(r'/\*\s*animation:', content))
    
    print(f"   Animations actives:     {active_animations}")
    print(f"   Animations désactivées: {commented_animations}")
    
    if active_animations < 5:
        print("   ✅ Animations optimisées")
    else:
        print(f"   ⚠️ Trop d'animations ({active_animations})")
    
    # 3. Mode Debug
    print("\n🐛 MODE DEBUG:")
    print("-" * 70)
    
    debug_mode_match = re.search(r'const\s+DEBUG_MODE\s*=\s*(true|false)', content)
    if debug_mode_match:
        debug_mode = debug_mode_match.group(1)
        if debug_mode == 'false':
            print("   ✅ Mode production (console.log désactivés)")
        else:
            print("   ⚠️ Mode debug actif (console.log visibles)")
    else:
        print("   ❌ DEBUG_MODE non trouvé")
    
    # 4. Optimisations boucles
    print("\n🔄 OPTIMISATIONS BOUCLES:")
    print("-" * 70)
    
    symbols_foreach = content.count('SYMBOLS.forEach')
    positions_check = content.count('Object.keys(openPositions)')
    
    print(f"   Boucles SYMBOLS.forEach:  {symbols_foreach}")
    print(f"   Checks positions:         {positions_check}")
    
    if 'symbolsToUpdate' in content and 'Object.keys(openPositions)' in content:
        print("   ✅ Optimisation positions détectée")
    else:
        print("   ⚠️ Boucles non optimisées")
    
    # 5. Score global
    print("\n" + "="*70)
    print("📊 SCORE GLOBAL DE PERFORMANCE")
    print("="*70)
    
    score = 0
    max_score = 100
    
    # Critère 1: Requêtes/heure (40 points)
    if total_calls_per_hour < 600:
        score += 40
        perf_req = "EXCELLENT"
    elif total_calls_per_hour < 1200:
        score += 30
        perf_req = "BON"
    elif total_calls_per_hour < 2000:
        score += 20
        perf_req = "MOYEN"
    else:
        score += 10
        perf_req = "FAIBLE"
    
    # Critère 2: Animations (20 points)
    if active_animations < 5:
        score += 20
    elif active_animations < 10:
        score += 10
    
    # Critère 3: Debug mode (20 points)
    if debug_mode_match and debug_mode_match.group(1) == 'false':
        score += 20
    
    # Critère 4: Optimisations (20 points)
    if 'symbolsToUpdate' in content:
        score += 20
    
    print(f"\n   Score: {score}/{max_score} points")
    print(f"\n   Niveau requêtes:  {perf_req} ({total_calls_per_hour:.0f} req/h)")
    
    if score >= 80:
        print("\n   ✅ DASHBOARD OPTIMISÉ - Performance excellente !")
        print("   💡 Fluidité maximale garantie")
    elif score >= 60:
        print("\n   ⚠️ Dashboard correct - Améliorations possibles")
        print("   💡 Quelques optimisations manquantes")
    else:
        print("\n   ❌ Dashboard non optimisé - Ralentissements possibles")
        print("   💡 Appliquer les optimisations recommandées")
    
    print("\n" + "="*70)

if __name__ == "__main__":
    try:
        analyze_dashboard_performance()
    except FileNotFoundError:
        print("❌ Fichier dashboard.html non trouvé")
    except Exception as e:
        print(f"❌ Erreur: {e}")
