#!/usr/bin/env python3
"""Monitoring IA en temps réel - Version simple"""

import time
import os
from datetime import datetime
import re

LOG_FILE = "dashboard_stdout.txt"

def colorize(text, color):
    """Coloriser le texte pour terminal"""
    colors = {
        'red': '\033[91m',
        'green': '\033[92m',
        'yellow': '\033[93m',
        'blue': '\033[94m',
        'cyan': '\033[96m',
        'white': '\033[97m',
        'gray': '\033[90m',
        'reset': '\033[0m'
    }
    return f"{colors.get(color, '')}{text}{colors['reset']}"

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def monitor():
    clear_screen()
    
    print(colorize("\n" + "="*70, 'cyan'))
    print(colorize("             🤖 SURVEILLANCE IA EN TEMPS RÉEL", 'green'))
    print(colorize("="*70 + "\n", 'cyan'))
    
    print(colorize(f"📡 Monitoring: {LOG_FILE}", 'yellow'))
    print(colorize(f"⏰ Démarré: {datetime.now().strftime('%H:%M:%S')}\n", 'gray'))
    print(colorize("-"*70 + "\n", 'gray'))
    
    last_pos = 0
    cycle_count = 0
    
    if os.path.exists(LOG_FILE):
        with open(LOG_FILE, 'r', encoding='utf-8', errors='ignore') as f:
            f.seek(0, 2)  # Aller à la fin
            last_pos = f.tell()
    
    while True:
        try:
            time.sleep(1)
            
            if not os.path.exists(LOG_FILE):
                continue
            
            with open(LOG_FILE, 'r', encoding='utf-8', errors='ignore') as f:
                f.seek(last_pos)
                new_lines = f.readlines()
                last_pos = f.tell()
            
            for line in new_lines:
                line = line.strip()
                timestamp = datetime.now().strftime('%H:%M:%S')
                
                # Cycles
                if 'CYCLE IA #' in line and 'Analyse' in line:
                    match = re.search(r'CYCLE IA #(\d+).*?(\d+:\d+:\d+).*?(\d+) symboles', line)
                    if match:
                        cycle_count += 1
                        print(colorize("\n╔" + "="*66 + "╗", 'cyan'))
                        print(colorize(f"║  🔄 CYCLE #{match.group(1)} - {match.group(2)} - {match.group(3)} symboles", 'yellow') + colorize("       ║", 'cyan'))
                        print(colorize("╚" + "="*66 + "╝", 'cyan'))
                
                # Résultats
                if 'Resultats' in line or 'Résultats' in line:
                    match = re.search(r'(\d+)/(\d+).*?(\d+) signaux.*?(\d+\.\d+)s', line)
                    if match:
                        print(colorize(f"  📊 Analysé: ", 'blue') + 
                              colorize(f"{match.group(1)}/{match.group(2)}", 'green') +
                              colorize(f" | Signaux: ", 'white') +
                              colorize(match.group(3), 'yellow') +
                              colorize(f" | Durée: ", 'white') +
                              colorize(f"{match.group(4)}s", 'cyan'))
                
                # Opportunités
                if 'opportunit' in line.lower() and 'tect' in line.lower():
                    match = re.search(r'(\d+) opportunit', line)
                    if match:
                        print(colorize(f"  🎯 {match.group(1)} OPPORTUNITÉ(S) DÉTECTÉE(S)!", 'green'))
                
                # Fin de cycle
                if 'TERMIN' in line or 'TERMINE' in line:
                    match = re.search(r'CYCLE #(\d+).*?(\d+\.\d+)s.*?(\d+)s', line)
                    if match:
                        print(colorize(f"  ✅ Terminé en ", 'green') +
                              colorize(f"{match.group(2)}s", 'cyan') +
                              colorize(f" - Prochain dans ", 'gray') +
                              colorize(f"{match.group(3)}s\n", 'yellow'))
                
                # Erreurs
                if any(x in line for x in ['ERROR', 'ERREUR', '❌', 'CRASH']):
                    if 'performance_analyzer' not in line:  # Filtrer le spam
                        print(colorize(f"  ❌ {line[line.find(']')+2:][:80]}", 'red'))
                
        except KeyboardInterrupt:
            print(colorize("\n\n👋 Monitoring arrêté\n", 'yellow'))
            break
        except Exception as e:
            print(colorize(f"⚠️  Erreur: {e}", 'red'))
            time.sleep(5)

if __name__ == '__main__':
    try:
        monitor()
    except Exception as e:
        print(f"❌ Erreur fatale: {e}")
