"""
Monitoring Dashboard pour Live Trading V10
Affiche l'état du trading en temps réel
"""

import json
import time
import os
from pathlib import Path
from datetime import datetime
from typing import Dict, List

def clear_screen():
    """Efface l'écran"""
    os.system('clear' if os.name != 'nt' else 'cls')

def load_state() -> Dict:
    """Charge l'état actuel du trading"""
    state_file = Path('live_trading_data/current_state.json')

    if not state_file.exists():
        return None

    try:
        with open(state_file, 'r') as f:
            return json.load(f)
    except Exception as e:
        print(f"Erreur chargement état: {e}")
        return None

def format_time_ago(timestamp_str: str) -> str:
    """Formate le temps écoulé"""
    try:
        dt = datetime.fromisoformat(timestamp_str)
        elapsed = datetime.now() - dt
        seconds = int(elapsed.total_seconds())

        if seconds < 60:
            return f"{seconds}s ago"
        elif seconds < 3600:
            return f"{seconds // 60}m ago"
        else:
            return f"{seconds // 3600}h ago"
    except:
        return "unknown"

def print_dashboard(state: Dict):
    """Affiche le dashboard"""
    clear_screen()

    print("=" * 100)
    print("🤖 APOLLO DEGEN BOT V10 - LIVE TRADING DASHBOARD")
    print("=" * 100)

    if not state:
        print("\n❌ Aucun état de trading trouvé")
        print("   Le bot n'a pas encore été démarré ou le fichier d'état est manquant")
        return

    # Header
    mode = state.get('mode', 'UNKNOWN')
    timestamp = state.get('timestamp', '')
    last_update = format_time_ago(timestamp)

    mode_emoji = "📝" if mode == 'PAPER' else "💰"
    print(f"\n{mode_emoji} Mode: {mode} | Dernière mise à jour: {last_update}")

    # Stats
    stats = state.get('stats', {})
    print(f"\n{'='*100}")
    print("📊 STATISTIQUES GLOBALES")
    print(f"{'='*100}")

    total_trades = stats.get('total_trades', 0)
    wins = stats.get('wins', 0)
    losses = stats.get('losses', 0)
    win_rate = stats.get('win_rate', 0) * 100
    total_pnl = stats.get('total_pnl', 0)

    pnl_color = "🟢" if total_pnl > 0 else "🔴" if total_pnl < 0 else "⚪"

    print(f"Total trades:  {total_trades}")
    print(f"Wins:          {wins}")
    print(f"Losses:        {losses}")
    print(f"Win rate:      {win_rate:.1f}%")
    print(f"Total PnL:     {pnl_color} ${total_pnl:+.2f}")

    # Positions actives
    positions = state.get('positions', {})

    if positions:
        print(f"\n{'='*100}")
        print(f"💼 POSITIONS ACTIVES ({len(positions)})")
        print(f"{'='*100}")

        # Header
        print(f"{'Symbol':<12} {'Side':<6} {'Lev':<5} {'Entry':<10} {'Quantity':<10} "
              f"{'PnL %':<10} {'PnL $':<12} {'SL':<10} {'TP':<10} {'Opened':<15}")
        print("-" * 100)

        for symbol, pos in positions.items():
            side = pos['side']
            leverage = pos['leverage']
            entry = pos['entry_price']
            quantity = pos['quantity']
            pnl_pct = pos['pnl_pct'] * 100
            pnl = pos['pnl']
            sl = pos.get('stop_loss', 0)
            tp = pos.get('take_profit', 0)
            opened_at = format_time_ago(pos['opened_at'])

            pnl_emoji = "🟢" if pnl_pct > 0 else "🔴" if pnl_pct < 0 else "⚪"
            side_emoji = "📈" if side == "LONG" else "📉"

            print(f"{symbol:<12} {side_emoji}{side:<4} {leverage:<5}x "
                  f"${entry:<9.2f} {quantity:<10.4f} "
                  f"{pnl_emoji}{pnl_pct:+7.2f}% ${pnl:+10.2f} "
                  f"${sl:<9.2f} ${tp:<9.2f} {opened_at:<15}")

        # Calculer PnL total positions actives
        total_active_pnl = sum(pos['pnl'] for pos in positions.values())
        total_active_pnl_pct = sum(pos['pnl_pct'] for pos in positions.values()) * 100 / len(positions)

        print("-" * 100)
        print(f"{'TOTAL ACTIF':<50} {total_active_pnl_pct:+.2f}% avg | ${total_active_pnl:+.2f} total")

    else:
        print(f"\n{'='*100}")
        print("💼 POSITIONS ACTIVES")
        print(f"{'='*100}")
        print("Aucune position active")

    # Historique récent
    history = state.get('history', [])
    if history:
        print(f"\n{'='*100}")
        print(f"📜 HISTORIQUE RÉCENT ({len(history)} derniers trades)")
        print(f"{'='*100}")

        # Header
        print(f"{'Symbol':<12} {'Side':<6} {'Lev':<5} {'Entry':<10} {'PnL %':<10} "
              f"{'PnL $':<12} {'Reason':<15} {'Closed':<15}")
        print("-" * 100)

        for trade in history[-10:]:  # Afficher 10 derniers
            symbol = trade['symbol']
            side = trade['side']
            leverage = trade['leverage']
            entry = trade['entry_price']
            pnl_pct = trade['pnl_pct'] * 100
            pnl = trade['pnl']
            reason = trade.get('close_reason', 'UNKNOWN')
            closed_at = format_time_ago(trade.get('closed_at', ''))

            pnl_emoji = "🟢" if pnl_pct > 0 else "🔴"
            side_emoji = "📈" if side == "LONG" else "📉"

            print(f"{symbol:<12} {side_emoji}{side:<4} {leverage:<5}x "
                  f"${entry:<9.2f} {pnl_emoji}{pnl_pct:+7.2f}% ${pnl:+10.2f} "
                  f"{reason:<15} {closed_at:<15}")

    print(f"\n{'='*100}")
    print(f"Rafraîchissement automatique... (Ctrl+C pour quitter)")
    print(f"{'='*100}\n")

def main():
    """Boucle principale de monitoring"""
    print("🚀 Démarrage monitoring...")
    print("   Dashboard se rafraîchit toutes les 5 secondes")
    print()

    try:
        while True:
            state = load_state()
            print_dashboard(state)
            time.sleep(5)

    except KeyboardInterrupt:
        print("\n\n✅ Monitoring arrêté")

if __name__ == '__main__':
    main()
