#!/usr/bin/env python3
"""Diagnostic complet des positions - simule check_technical_exit"""
import json
import sys
import os
from datetime import datetime

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from config import TESTNET_MODE, BINANCE_API_KEY, BINANCE_API_SECRET
from binance.client import Client
import numpy as np

if TESTNET_MODE:
    client = Client(BINANCE_API_KEY, BINANCE_API_SECRET, testnet=True)
    client.API_URL = 'https://testnet.binancefuture.com'
else:
    client = Client(BINANCE_API_KEY, BINANCE_API_SECRET)

def get_price(symbol):
    try:
        ticker = client.futures_symbol_ticker(symbol=symbol)
        return float(ticker['price'])
    except:
        return None

def get_klines(symbol, limit=50):
    """Récupère les dernières bougies"""
    try:
        klines = client.futures_klines(symbol=symbol, interval='1m', limit=limit)
        return [float(k[4]) for k in klines]  # Close prices
    except:
        return []

def ema(prices, period):
    if len(prices) < period:
        return None
    multiplier = 2 / (period + 1)
    ema_value = sum(prices[:period]) / period
    for price in prices[period:]:
        ema_value = (price * multiplier) + (ema_value * (1 - multiplier))
    return ema_value

def rsi(prices, period=14):
    if len(prices) < period + 1:
        return None
    deltas = [prices[i] - prices[i-1] for i in range(1, len(prices))]
    gains = [d if d > 0 else 0 for d in deltas]
    losses = [-d if d < 0 else 0 for d in deltas]
    avg_gain = sum(gains[-period:]) / period
    avg_loss = sum(losses[-period:]) / period
    if avg_loss == 0:
        return 100
    rs = avg_gain / avg_loss
    return 100 - (100 / (1 + rs))

print("=" * 90)
print("DIAGNOSTIC COMPLET DES POSITIONS - SIMULATION check_technical_exit")
print(f"Mode: {'TESTNET' if TESTNET_MODE else 'PRODUCTION'}")
print(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 90)

positions = json.load(open('positions.json'))

for sym, pos in positions.items():
    print(f"\n{'='*90}")
    print(f"📊 {sym}")
    print("="*90)
    
    try:
        price = get_price(sym)
        if price is None:
            print("   ❌ Prix non disponible")
            continue
        
        prices_list = get_klines(sym)
        if len(prices_list) < 21:
            print(f"   ❌ Pas assez de données ({len(prices_list)} bougies)")
            continue
        
        entry = pos['entry_price']
        pnl = ((price/entry)-1)*100
        max_pnl = pos.get('max_pnl', 0)
        max_price = pos.get('max_price', entry)
        timestamp = pos.get('timestamp', 'N/A')
        
        # Calculer l'âge de la position
        try:
            ts = datetime.fromisoformat(timestamp)
            age_minutes = (datetime.now() - ts).total_seconds() / 60
        except:
            age_minutes = 0
        
        print(f"\n   📍 POSITION:")
        print(f"      Entry: {entry:.6f} | Current: {price:.6f} | PnL: {pnl:+.2f}%")
        print(f"      Max Price: {max_price:.6f} | Max PnL: {max_pnl:.2f}%")
        print(f"      Âge: {age_minutes:.0f} minutes ({timestamp})")
        
        # Calculer indicateurs
        ema9 = ema(prices_list, 9)
        ema21 = ema(prices_list, 21)
        rsi_val = rsi(prices_list)
        
        if not ema9 or not ema21:
            print("   ❌ EMA non calculable")
            continue
        
        ema_gap_pct = ((ema9 - ema21) / ema21) * 100
        
        momentum_3 = ((price - prices_list[-3]) / prices_list[-3]) * 100
        momentum_5 = ((price - prices_list[-5]) / prices_list[-5]) * 100
        
        print(f"\n   📈 INDICATEURS:")
        print(f"      EMA9: {ema9:.6f} | EMA21: {ema21:.6f} | Gap: {ema_gap_pct:+.2f}%")
        print(f"      RSI: {rsi_val:.1f}")
        print(f"      Mom3: {momentum_3:+.2f}% | Mom5: {momentum_5:+.2f}%")
        print(f"      Prix vs EMA9: {'AU-DESSUS' if price > ema9 else 'EN-DESSOUS'}")
        
        # Simuler les détections
        exit_score = 0
        exit_reasons = []
        urgent_exit = False
        
        # DÉTECTION #2: CRASH SOUDAIN
        if momentum_3 < -1.0:
            urgent_exit = True
            exit_score += 8
            exit_reasons.append(f"CRASH SOUDAIN: {momentum_3:.2f}%")
        elif momentum_3 < -0.5 and momentum_5 < -0.8:
            exit_score += 5
            exit_reasons.append(f"Chute rapide: Mom3={momentum_3:.2f}%")
        
        # DÉTECTION #3: Death Cross
        if ema_gap_pct < -0.15 and momentum_3 < 0 and momentum_5 < 0:
            exit_score += 6
            exit_reasons.append(f"Death Cross: EMA gap={ema_gap_pct:.2f}%")
            if rsi_val and rsi_val < 40:
                urgent_exit = True
                exit_score += 4
                exit_reasons.append(f"+ RSI faible ({rsi_val:.0f})")
        
        # DÉTECTION #5: Chute depuis le max
        drop_from_max = ((price - max_price) / max_price) * 100
        if drop_from_max < -2.0:
            exit_score += 4
            exit_reasons.append(f"Chute {drop_from_max:.1f}% depuis max")
        if drop_from_max < -3.5:
            exit_score += 3
            urgent_exit = True
            exit_reasons.append(f"Chute sévère {drop_from_max:.1f}%")
        
        # DÉTECTION #5b: Retournement
        if max_pnl > 0.5 and pnl < max_pnl * 0.3:
            if ema_gap_pct < 0:
                exit_score += 6
                exit_reasons.append(f"Retournement: max +{max_pnl:.1f}% → {pnl:+.1f}%")
                if pnl < 0:
                    urgent_exit = True
                    exit_score += 4
        
        # DÉTECTION #6: EMA baissière
        if ema_gap_pct < -0.3:
            exit_score += 3
            exit_reasons.append(f"EMA baissière ({ema_gap_pct:.2f}%)")
        
        # DÉTECTION #7: Prix sous les deux EMA
        if price < ema9 and price < ema21:
            exit_score += 2
            exit_reasons.append("Prix sous EMA9 et EMA21")
        
        print(f"\n   🎯 ANALYSE SORTIE:")
        print(f"      Exit Score: {exit_score}")
        print(f"      Urgent Exit: {urgent_exit}")
        if exit_reasons:
            print(f"      Raisons: {', '.join(exit_reasons)}")
        
        # Vérifier les PROTECTIONS
        strong_uptrend = (ema_gap_pct > 0.2 and momentum_3 > 0.3 and momentum_5 > 0.5)
        ema_bullish_with_healthy_rsi = (ema_gap_pct > 0.1 and rsi_val and 45 < rsi_val < 75 and price > ema9)
        
        print(f"\n   🛡️ PROTECTIONS:")
        print(f"      Strong Uptrend: {strong_uptrend}")
        print(f"      EMA Bullish + RSI Sain: {ema_bullish_with_healthy_rsi}")
        
        # Décision finale
        if strong_uptrend and not urgent_exit:
            decision = "🛡️ PROTÉGÉ (Strong Uptrend)"
        elif ema_bullish_with_healthy_rsi and not urgent_exit and exit_score < 10:
            decision = "🛡️ PROTÉGÉ (EMA Bullish + RSI)"
        elif urgent_exit and exit_score >= 8:
            decision = "🚨 VENDRE URGENT"
        elif exit_score >= 10:
            decision = "⚡ VENDRE (score>=10)"
        elif exit_score >= 7 and pnl < -0.5:
            decision = "⚡ VENDRE (score>=7 + perte)"
        elif exit_score >= 5 and pnl < -1.5:
            decision = "⚡ VENDRE (perte importante)"
        elif pnl > -0.5 and exit_score < 8:
            decision = "⏳ GARDER (micro-perte + score<8)"
        else:
            decision = "⏳ GARDER (aucun critère de vente atteint)"
        
        print(f"\n   📌 DÉCISION: {decision}")
        
        # DIAGNOSTIC SUPPLÉMENTAIRE
        if "PROTÉGÉ" in decision and pnl < 0:
            print(f"\n   ⚠️ PROBLÈME: En perte {pnl:.2f}% mais protégé!")
            print(f"      → La protection bloque la vente alors qu'on perd de l'argent")
            
    except Exception as e:
        print(f"   ❌ ERREUR: {e}")

print("\n" + "=" * 90)
print("🔧 RECOMMANDATIONS:")
print("   - Si positions en perte protégées → ajuster les protections")
print("   - Si max_pnl=0 → le max_price n'a jamais été mis à jour (jamais eu de profit)")
print("=" * 90)
