#!/usr/bin/env python3
"""
Live monitoring du Smart Optimizer
Rafraîchit automatiquement toutes les 5 secondes
"""
import json
import time
import os
from pathlib import Path
from datetime import datetime

def clear_screen():
    """Clear terminal"""
    os.system('clear' if os.name == 'posix' else 'cls')

def format_duration(seconds):
    """Format duration nicely"""
    if seconds < 60:
        return f"{int(seconds)}s"
    elif seconds < 3600:
        return f"{int(seconds/60)}m {int(seconds%60)}s"
    else:
        h = int(seconds/3600)
        m = int((seconds%3600)/60)
        return f"{h}h {m}m"

def display_stats():
    """Affiche stats actuelles"""
    results_file = Path('smart_optimizer_results.json')

    clear_screen()

    print("="*80)
    print("🧠 SMART OPTIMIZER - LIVE MONITORING")
    print("="*80)
    print(f"⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("="*80)

    if not results_file.exists():
        print("\n⏳ En attente des premiers résultats...\n")
        print("Le premier backtest peut prendre 1-2 minutes.")
        return

    with open(results_file) as f:
        results = json.load(f)

    if not results:
        print("\n⏳ Aucun résultat encore...\n")
        return

    # Stats globales
    profitable = [r for r in results if r['results']['total_pnl_pct'] > 0 and r['results']['profit_factor'] > 1.0]

    print(f"\n📊 STATISTIQUES GLOBALES")
    print("-" * 80)
    print(f"Tests complétés: {len(results)}")
    print(f"Profitables: {len(profitable)}/{len(results)} ({len(profitable)/len(results)*100:.1f}%)")

    if results:
        # Dernière màj
        latest = max(results, key=lambda x: x['timestamp'])
        latest_time = datetime.fromisoformat(latest['timestamp'])
        time_ago = (datetime.now() - latest_time).total_seconds()
        print(f"Dernier test: il y a {format_duration(time_ago)}")

    # Meilleur résultat
    if profitable:
        print(f"\n{'='*80}")
        print(f"🏆 MEILLEUR SETUP (par PnL)")
        print("="*80)

        best = max(profitable, key=lambda x: x['results']['total_pnl_pct'])
        res = best['results']
        p = best['params']

        print(f"\n💰 PERFORMANCE:")
        print(f"   PnL Total:        {res['total_pnl_pct']:>+8.2f}%")
        print(f"   Profit Factor:    {res['profit_factor']:>8.2f}")
        print(f"   Capital Final:    ${res['final_capital']:>7.2f}")
        print(f"   Total Trades:     {res['total_trades']:>8}")
        print(f"   Win Rate:         {res['win_rate']:>7.1f}%")
        print(f"   Avg Win:          ${res['avg_win']:>7.2f}")
        print(f"   Avg Loss:         ${res['avg_loss']:>7.2f}")

        print(f"\n⚙️  PARAMÈTRES:")
        print(f"   Trailing Stop:    {int(p['trailing_pct']*100):>8}%")
        print(f"   Leverage:         {p['leverage']:>8}x")
        print(f"   RSI:              {p['rsi_oversold']:>3} / {p['rsi_overbought']:<3}")
        print(f"   ATR Threshold:    {p['range_atr_threshold']:>8.2f}")
        print(f"   Min Confidence:   {p['min_confidence']:>8}")
        print(f"   SL Multiplier:    {p['sl_atr_mult']:>8.2f}")

        # Top 5
        print(f"\n{'='*80}")
        print(f"📈 TOP 5 CONFIGS")
        print("="*80)
        print(f"\n{'#':<4} {'PnL':<10} {'PF':<7} {'Trades':<8} {'Trail':<7} {'Lev':<6} {'RSI'}")
        print("-" * 80)

        profitable.sort(key=lambda x: x['results']['total_pnl_pct'], reverse=True)

        for i, r in enumerate(profitable[:5], 1):
            res = r['results']
            p = r['params']

            print(f"{i:<4} {res['total_pnl_pct']:>+8.2f}% "
                  f"{res['profit_factor']:>5.2f}  "
                  f"{res['total_trades']:>5}   "
                  f"{int(p['trailing_pct']*100):>3}%   "
                  f"{p['leverage']:>4}x  "
                  f"{p['rsi_oversold']:>2}/{p['rsi_overbought']:<2}")

        # Distribution trailing stop
        print(f"\n{'='*80}")
        print(f"📊 DISTRIBUTION TRAILING STOP %")
        print("="*80)

        trail_stats = {}
        for r in profitable:
            trail = int(r['params']['trailing_pct'] * 100)
            if trail not in trail_stats:
                trail_stats[trail] = []
            trail_stats[trail].append(r['results']['total_pnl_pct'])

        for trail in sorted(trail_stats.keys()):
            pnls = trail_stats[trail]
            avg_pnl = sum(pnls) / len(pnls)
            max_pnl = max(pnls)

            print(f"   {trail:>2}%: {len(pnls):>3} tests | "
                  f"Avg PnL: {avg_pnl:>+7.2f}% | "
                  f"Max PnL: {max_pnl:>+7.2f}%")

    else:
        print(f"\n⚠️  Aucune config profitable encore")
        print(f"   Le moteur continue à explorer...")

    print(f"\n{'='*80}")
    print("⏳ Rafraîchissement dans 5s... (Ctrl+C pour quitter)")
    print("="*80)

if __name__ == '__main__':
    print("\n🚀 Démarrage du monitoring...\n")

    try:
        while True:
            display_stats()
            time.sleep(5)
    except KeyboardInterrupt:
        clear_screen()
        print("\n👋 Monitoring arrêté.\n")

        # Afficher un dernier résumé
        results_file = Path('smart_optimizer_results.json')
        if results_file.exists():
            with open(results_file) as f:
                results = json.load(f)

            if results:
                profitable = [r for r in results if r['results']['total_pnl_pct'] > 0 and r['results']['profit_factor'] > 1.0]

                print("="*80)
                print("📊 RÉSUMÉ FINAL")
                print("="*80)
                print(f"Tests: {len(results)} | Profitables: {len(profitable)} ({len(profitable)/len(results)*100:.1f}%)")

                if profitable:
                    best = max(profitable, key=lambda x: x['results']['total_pnl_pct'])
                    print(f"\n🏆 Meilleur PnL: {best['results']['total_pnl_pct']:+.2f}% "
                          f"| PF: {best['results']['profit_factor']:.2f} "
                          f"| Trades: {best['results']['total_trades']}")

                print("="*80)
                print(f"\n💾 Résultats complets: smart_optimizer_results.json\n")
