"""
Diagnostic du régime de marché
Affiche toutes les informations utiles pour déboguer les blocages
"""

from market_regime import MarketRegimeDetector
import json
from datetime import datetime

def format_time(seconds):
    """Formate les secondes en format lisible"""
    if seconds < 60:
        return f"{seconds:.0f}s"
    elif seconds < 3600:
        return f"{seconds/60:.1f}min"
    else:
        return f"{seconds/3600:.1f}h"

def main():
    print("\n" + "="*70)
    print("  DIAGNOSTIC RÉGIME DE MARCHÉ")
    print("="*70)
    
    detector = MarketRegimeDetector()
    
    # Afficher la configuration actuelle
    print(f"\n⚙️  CONFIGURATION:")
    print(f"   Update interval: {detector.update_interval}s ({format_time(detector.update_interval)})")
    print(f"   Max cache time: {detector.max_cache_time}s ({format_time(detector.max_cache_time)})")
    
    # Afficher l'état du cache
    if detector.last_update:
        now = datetime.now()
        elapsed = (now - detector.last_update).total_seconds()
        print(f"   Dernière update: {detector.last_update.strftime('%H:%M:%S')}")
        print(f"   Âge du cache: {format_time(elapsed)}")
        if elapsed > detector.max_cache_time:
            print(f"   ⚠️  Cache EXPIRÉ (> {format_time(detector.max_cache_time)})")
        elif elapsed < detector.update_interval:
            print(f"   ✅ Cache VALIDE")
        else:
            print(f"   🔄 Cache ACTUALISABLE")
    else:
        print("   Aucune update précédente")
    
    print(f"\n🔄 DÉTECTION EN COURS...")
    regime, config = detector.detect_regime(force_update=True)
    
    # Afficher le résultat
    print(f"\n{'='*70}")
    print(f"📊 RÉGIME DÉTECTÉ: {regime}")
    print(f"{'='*70}")
    print(f"   Description: {config['description']}")
    print(f"   Max positions: {config['max_positions']}")
    print(f"   Score IA minimum: {config['min_score']}")
    print(f"   Taille position: {config['position_size_pct']}%")
    print(f"   TP multiplier: {config['take_profit_multiplier']}")
    
    # Détails du marché
    market_data = detector.market_data
    print(f"\n💰 BITCOIN (score={market_data['btc']['sentiment_score']}):")
    btc = market_data['btc']
    print(f"   Prix: {btc['price']:.2f} USDT")
    print(f"   EMA9: {btc['ema9']:.2f}  |  EMA21: {btc['ema21']:.2f}  |  Tendance: {btc['ema_trend']}")
    print(f"   RSI: {btc['rsi']:.1f}")
    print(f"   Momentum 3h:  {btc['momentum_3h']:+.2f}%  {'🟢' if btc['momentum_3h'] > 0 else '🔴'}")
    print(f"   Momentum 5h:  {btc['momentum_5h']:+.2f}%  {'🟢' if btc['momentum_5h'] > 0 else '🔴'}")
    print(f"   Momentum 24h: {btc['momentum_24h']:+.2f}%  {'🟢' if btc['momentum_24h'] > 0 else '🔴'}")
    
    # Calcul momentum pondéré BTC
    btc_weighted = (btc['momentum_3h'] * 0.5) + (btc['momentum_5h'] * 0.35) + (btc['momentum_24h'] * 0.15)
    print(f"   Momentum pondéré: {btc_weighted:+.2f}%  {'🟢' if btc_weighted > 0 else '🔴'}")
    
    print(f"\n🪙  ALTCOINS (score={market_data['altcoins']['altcoin_score']}):")
    alt = market_data['altcoins']
    print(f"   Analysés: {alt['analyzed']}")
    print(f"   Bullish: {alt['bullish_count']} ({alt['bullish_pct']:.1f}%)  {'🟢' if alt['bullish_pct'] >= 40 else '🔴'}")
    print(f"   Bearish: {alt['bearish_count']}")
    print(f"   Neutral: {alt['neutral_count']}")
    print(f"   Momentum 3h:  {alt['avg_momentum_3h']:+.2f}%  {'🟢' if alt['avg_momentum_3h'] > 0 else '🔴'}")
    print(f"   Momentum 5h:  {alt['avg_momentum_5h']:+.2f}%  {'🟢' if alt['avg_momentum_5h'] > 0 else '🔴'}")
    print(f"   Momentum 24h: {alt['avg_momentum']:+.2f}%  {'🟢' if alt['avg_momentum'] > 0 else '🔴'}")
    print(f"   Momentum pondéré: {alt['weighted_momentum']:+.2f}%  {'🟢' if alt['weighted_momentum'] > 0 else '🔴'}")
    
    print(f"\n🎯 SCORE GLOBAL: {market_data['global_score']:.1f}/100")
    
    # Historique des changements
    if detector.regime_history:
        print(f"\n📜 HISTORIQUE (5 derniers changements):")
        for change in detector.regime_history[-5:]:
            timestamp = datetime.fromisoformat(change['timestamp']).strftime('%H:%M:%S')
            print(f"   {timestamp}: {change['from']:12} → {change['to']:12}  (score={change['score']:.1f})")
    
    # Conditions pour BULL
    print(f"\n✅ CONDITIONS POUR BULL:")
    btc_allows = btc_weighted >= 0
    alt_allows = alt['bullish_pct'] >= 40 and alt['weighted_momentum'] >= -1.0
    btc_status = "✅" if btc_allows else f"❌ (actuel: {btc_weighted:.2f}%)"
    alt_status = "✅" if alt_allows else f"❌ (actuel: {alt['bullish_pct']:.1f}%, momentum: {alt['weighted_momentum']:.2f}%)"
    print(f"   BTC momentum pondéré ≥ 0%: {btc_allows}  {btc_status}")
    print(f"   Altcoins ≥ 40% bullish:    {alt_allows}  {alt_status}")
    
    # Seuils de régime
    print(f"\n📏 SEUILS DE RÉGIME:")
    print(f"   BULL_STRONG:  score ≥ 75  ET conditions BULL  {'✅' if market_data['global_score'] >= 75 and btc_allows and alt_allows else '❌'}")
    print(f"   BULL_WEAK:    score ≥ 60  ET conditions BULL  {'✅' if market_data['global_score'] >= 60 and btc_allows and alt_allows else '❌'}")
    print(f"   NEUTRAL:      score ≥ 45                      {'✅' if market_data['global_score'] >= 45 else '❌'}")
    print(f"   CORRECTION:   score ≥ 30                      {'✅' if market_data['global_score'] >= 30 else '❌'}")
    print(f"   BEAR:         score < 30                      {'✅' if market_data['global_score'] < 30 else '❌'}")
    
    print(f"\n{'='*70}\n")

if __name__ == "__main__":
    main()
