#!/usr/bin/env python3
"""
Script de monitoring de l'optimisation
Affiche la progression et les meilleurs résultats
"""

import json
import os
from pathlib import Path
from datetime import datetime

def main():
    print("=" * 80)
    print("🔍 ÉTAT OPTIMISATION HYBRID STRATEGY")
    print("=" * 80)
    print()

    # Vérifier si le processus tourne
    import subprocess
    try:
        result = subprocess.run(
            ['pgrep', '-f', 'optimize_hybrid_massive.py'],
            capture_output=True,
            text=True
        )
        if result.stdout.strip():
            print("✅ Processus en cours (PID:", result.stdout.strip(), ")")
        else:
            print("⏹️  Processus terminé")
    except:
        print("❓ État processus inconnu")

    print()

    # Lire résultats partiels
    results_file = 'hybrid_optimization_results.json'

    if not Path(results_file).exists():
        print(f"⏳ Aucun résultat pour l'instant")
        print(f"   Fichier {results_file} n'existe pas encore")
        return

    try:
        with open(results_file, 'r') as f:
            results = json.load(f)
    except:
        print(f"⚠️  Fichier {results_file} vide ou corrompu")
        return

    if not results:
        print("⏳ Tests en cours, aucun résultat sauvegardé")
        return

    print(f"📊 PROGRESSION")
    print(f"Tests effectués: {len(results)}/100")
    print()

    # Statistiques
    profitable = [r for r in results if r['pnl_pct'] > 0 and r['profit_factor'] > 1.0]
    print(f"Configs profitables: {len(profitable)} ({len(profitable)/len(results)*100:.0f}%)")
    print()

    if profitable:
        # Meilleur par PnL
        best_pnl = max(profitable, key=lambda x: x['pnl_pct'])
        print("🏆 MEILLEUR PnL:")
        print(f"  PnL: {best_pnl['pnl_pct']:+.1f}%")
        print(f"  Profit Factor: {best_pnl['profit_factor']:.2f}")
        print(f"  Win Rate: {best_pnl['win_rate']:.0f}%")
        print(f"  Trades: {best_pnl['trades']}")
        print(f"  Max DD: {best_pnl['max_dd']:.1f}%")
        print(f"  Répartition: {best_pnl['trades_by_strategy']}")
        print()

        # Meilleur par PF
        best_pf = max(profitable, key=lambda x: x['profit_factor'])
        print("🏆 MEILLEUR PROFIT FACTOR:")
        print(f"  Profit Factor: {best_pf['profit_factor']:.2f}")
        print(f"  PnL: {best_pf['pnl_pct']:+.1f}%")
        print(f"  Win Rate: {best_pf['win_rate']:.0f}%")
        print(f"  Trades: {best_pf['trades']}")
        print(f"  Max DD: {best_pf['max_dd']:.1f}%")
        print(f"  Répartition: {best_pf['trades_by_strategy']}")
        print()

        # Derniers tests
        print("📋 DERNIERS 5 TESTS:")
        for r in results[-5:]:
            print(f"  PnL: {r['pnl_pct']:+.1f}% | PF: {r['profit_factor']:.2f} | WR: {r['win_rate']:.0f}% | Trades: {r['trades']}")
    else:
        print("❌ Aucune config profitable pour l'instant")
        print()
        print("📋 DERNIERS 5 TESTS:")
        for r in results[-5:]:
            pnl = r.get('pnl_pct', 0)
            pf = r.get('profit_factor', 0)
            wr = r.get('win_rate', 0)
            trades = r.get('trades', 0)
            print(f"  PnL: {pnl:+.1f}% | PF: {pf:.2f} | WR: {wr:.0f}% | Trades: {trades}")

    print()
    print("=" * 80)
    print("💡 Pour suivre en temps réel: tail -f hybrid_optimization.log")
    print("=" * 80)

if __name__ == '__main__':
    main()
