#!/usr/bin/env python3
"""
Script de monitoring des signaux de trading en temps réel
"""

import time
import json
import requests
import logging
from datetime import datetime
from typing import Dict, List
import os
import subprocess

# Configuration
API_BASE_URL = "http://localhost:8888"
AUTH = ("admin", "trading2024")
REFRESH_INTERVAL = 10  # secondes

# Configuration du logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def clear_screen():
    """Nettoie l'écran"""
    os.system('clear' if os.name == 'posix' else 'cls')

def get_active_signals() -> Dict:
    """Récupère les signaux actifs via l'API"""
    try:
        response = requests.get(
            f"{API_BASE_URL}/api/trading/active-signals",
            auth=AUTH,
            timeout=10
        )
        response.raise_for_status()
        return response.json()
    except Exception as e:
        logger.error(f"Erreur récupération signaux actifs: {e}")
        return {}

def get_recent_logs(lines: int = 20) -> List[str]:
    """Récupère les logs récents du service"""
    try:
        result = subprocess.run([
            'journalctl', '-u', 'crypto-trader.service',
            '--no-pager', '-n', str(lines)
        ], capture_output=True, text=True, timeout=10)

        if result.returncode == 0:
            return result.stdout.strip().split('\n')
        return []
    except Exception as e:
        logger.error(f"Erreur récupération logs: {e}")
        return []

def get_service_status() -> Dict:
    """Récupère le statut du service"""
    try:
        result = subprocess.run([
            'systemctl', 'status', 'crypto-trader.service', '--no-pager'
        ], capture_output=True, text=True, timeout=5)

        if "Active: active (running)" in result.stdout:
            return {"status": "running", "details": "Service actif"}
        elif "Active: failed" in result.stdout:
            return {"status": "failed", "details": "Service en erreur"}
        else:
            return {"status": "unknown", "details": "Statut inconnu"}
    except Exception as e:
        return {"status": "error", "details": f"Erreur: {e}"}

def format_signal(signal: Dict) -> str:
    """Formate un signal pour affichage"""
    symbol = signal.get('symbol', 'N/A')
    side = signal.get('side', 'N/A')
    score = signal.get('score', 0)
    leverage = signal.get('leverage', 0)
    pnl = signal.get('pnl_percent', 0)
    timestamp = signal.get('timestamp', '')

    # Formatage de l'heure (conversion Paris)
    try:
        from zoneinfo import ZoneInfo
        dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
        dt_paris = dt.astimezone(ZoneInfo('Europe/Paris'))
        time_str = dt_paris.strftime('%H:%M:%S')
    except:
        try:
            # Fallback sans zoneinfo
            dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
            time_str = dt.strftime('%H:%M:%S')
        except:
            time_str = timestamp[:8] if len(timestamp) > 8 else timestamp

    # Couleur pour PnL
    pnl_color = "🟢" if pnl >= 0 else "🔴"

    return f"{symbol:6} | {side:5} | {score:4.2f} | {leverage:2}x | {pnl_color} {pnl:+6.2f}% | {time_str}"

def display_dashboard():
    """Affiche le dashboard de monitoring"""
    clear_screen()

    print("=" * 80)
    print("🚀 CRYPTO TRADER - MONITORING DES SIGNAUX")
    print("=" * 80)
    print(f"⏰ Dernière mise à jour: {datetime.now().strftime('%d/%m/%Y %H:%M:%S')} (Paris)")
    print()

    # Statut du service
    service_status = get_service_status()
    status_icon = "🟢" if service_status["status"] == "running" else "🔴"
    print(f"📊 Statut du service: {status_icon} {service_status['details']}")
    print()

    # Signaux actifs
    active_signals_data = get_active_signals()

    if active_signals_data and active_signals_data.get('status') == 'success':
        signals = active_signals_data.get('signals', [])
        count = len(signals)

        print(f"📈 SIGNAUX ACTIFS ({count} signaux)")
        print("-" * 60)

        if signals:
            print("Symbol | Side  | Score | Lev | PnL      | Heure")
            print("-" * 60)

            for signal in signals[:15]:  # Limiter à 15 signaux
                print(format_signal(signal))
        else:
            print("🔍 Aucun signal actif trouvé")
    else:
        print("❌ Impossible de récupérer les signaux actifs")

    print()

    # Logs récents
    print("📝 LOGS RÉCENTS (10 dernières lignes)")
    print("-" * 60)

    logs = get_recent_logs(10)
    signal_logs = []

    for log in logs:
        if any(keyword in log.lower() for keyword in ['signal', 'pragmatique', 'leverage', 'corrélation']):
            # Extraire la partie importante du log
            if 'python3[' in log:
                log_content = log.split('python3[')[1].split(']:')[1].strip() if ']:' in log else log
                signal_logs.append(log_content[:75] + ('...' if len(log_content) > 75 else ''))

    if signal_logs:
        for log in signal_logs[-5:]:  # 5 derniers logs de signaux
            print(f"  {log}")
    else:
        print("  🔍 Aucun log de signal récent")

    print()
    print("=" * 80)
    print(f"⏱️  Rafraîchissement automatique toutes les {REFRESH_INTERVAL}s | Ctrl+C pour quitter")
    print("=" * 80)

def monitor_signals():
    """Boucle principale de monitoring"""
    logger.info("Démarrage du monitoring des signaux...")

    try:
        while True:
            display_dashboard()
            time.sleep(REFRESH_INTERVAL)

    except KeyboardInterrupt:
        print("\n\n👋 Arrêt du monitoring...")
        logger.info("Monitoring arrêté par l'utilisateur")
    except Exception as e:
        logger.error(f"Erreur dans la boucle de monitoring: {e}")

def show_help():
    """Affiche l'aide"""
    print("""
🚀 CRYPTO TRADER - MONITORING DES SIGNAUX

UTILISATION:
  python3 monitor_signals.py           - Monitoring en temps réel
  python3 monitor_signals.py --once   - Affichage unique
  python3 monitor_signals.py --help   - Cette aide

FONCTIONNALITÉS:
  ✅ Statut du service en temps réel
  ✅ Liste des signaux actifs avec PnL
  ✅ Logs récents filtrés sur les signaux
  ✅ Rafraîchissement automatique toutes les 10s

RACCOURCIS:
  Ctrl+C - Quitter le monitoring

API ENDPOINTS DISPONIBLES:
  GET /api/trading/active-signals    - Signaux actifs
  GET /api/trading/signals          - Nouveaux signaux (en réparation)

AUTHENTIFICATION:
  Username: admin
  Password: trading2024
""")

if __name__ == "__main__":
    import sys

    if len(sys.argv) > 1:
        if sys.argv[1] == "--help":
            show_help()
            exit(0)
        elif sys.argv[1] == "--once":
            display_dashboard()
            exit(0)

    monitor_signals()