#!/usr/bin/env python3
"""
Debug V10 Range - Pourquoi aucun signal ?
"""
import pandas as pd
import requests
import sys
sys.path.insert(0, '/var/www/html/HyperOracle/crypto_trader/apollo_degen_bot')

from v10_range_strategy import V10RangeStrategy, V10RangeDetector

# Récupérer données réelles
resp = requests.get('https://api.binance.com/api/v3/klines', params={
    'symbol': 'BTCUSDT',
    'interval': '1m',
    'limit': 200
})

data = resp.json()
df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume',
                                  'close_time', 'quote_volume', 'trades', 'taker_buy_base',
                                  'taker_buy_quote', 'ignore'])

for col in ['open', 'high', 'low', 'close']:
    df[col] = df[col].astype(float)
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')

print("="*80)
print("DEBUG V10 RANGE STRATEGY - Pourquoi aucun signal ?")
print("="*80)
print(f"Prix actuel: ${df['close'].iloc[-1]:,.2f}")
print()

# Créer stratégie avec config actuelle
strategy = V10RangeStrategy(leverage=250)
strategy.params['rsi_oversold'] = 35
strategy.params['rsi_overbought'] = 78
strategy.params['range_atr_threshold'] = 0.32
strategy.params['min_confidence'] = 60
strategy.params['sl_atr_multiplier'] = 1.64

print("PARAMÈTRES STRATÉGIE:")
print(f"  RSI: {strategy.params['rsi_oversold']}/{strategy.params['rsi_overbought']}")
print(f"  ATR threshold: {strategy.params['range_atr_threshold']}")
print(f"  Min confidence: {strategy.params['min_confidence']}")
print()

# TEST 1: Est-ce détecté comme un marché en RANGE ?
print("="*80)
print("TEST 1: Marché en RANGE ?")
print("="*80)

lookback = strategy.params['lookback_range']
window = df.iloc[-lookback:]
closes = window['close'].values

# Calculer ATR
atr = V10RangeDetector.calculate_atr(
    window['high'], window['low'], window['close'], period=14
)
avg_atr = atr.iloc[-20:].mean()
price = closes[-1]
atr_pct = (avg_atr / price) * 100

print(f"ATR moyen (20 dernières): ${avg_atr:.2f}")
print(f"ATR %: {atr_pct:.3f}%")
print(f"Seuil: {strategy.params['range_atr_threshold']}%")

if atr_pct >= strategy.params['range_atr_threshold']:
    print(f"❌ ATR trop élevé ({atr_pct:.3f}% >= {strategy.params['range_atr_threshold']}%)")
    print("   → PAS en marché RANGE")
else:
    print(f"✅ ATR OK ({atr_pct:.3f}% < {strategy.params['range_atr_threshold']}%)")

# Support/Resistance touches
period_high = closes.max()
period_low = closes.min()
range_size = period_high - period_low

print(f"\nRange size: ${range_size:,.2f} ({range_size/price*100:.2f}%)")
print(f"High: ${period_high:,.2f}")
print(f"Low: ${period_low:,.2f}")

top_zone = period_high - range_size * 0.05
bottom_zone = period_low + range_size * 0.05

touches_top = sum(1 for c in closes[-50:] if c >= top_zone)
touches_bottom = sum(1 for c in closes[-50:] if c <= bottom_zone)

print(f"\nTouches resistance: {touches_top}")
print(f"Touches support: {touches_bottom}")

if touches_top >= 2 and touches_bottom >= 2:
    print(f"✅ Assez de touches S/R")
else:
    print(f"❌ Pas assez de touches (besoin 2+ de chaque)")

# TEST 2: RSI et Bollinger Bands
print("\n" + "="*80)
print("TEST 2: RSI et Bollinger Bands")
print("="*80)

closes_series = df['close']
rsi = strategy.calculate_rsi(closes_series, strategy.params['rsi_period'])
bb_upper, bb_middle, bb_lower = strategy.calculate_bollinger_bands(
    closes_series, strategy.params['bb_period'], strategy.params['bb_std']
)

current_price = closes_series.iloc[-1]
current_rsi = rsi.iloc[-1]
current_bb_upper = bb_upper.iloc[-1]
current_bb_lower = bb_lower.iloc[-1]

print(f"RSI actuel: {current_rsi:.1f}")
print(f"  Oversold: < {strategy.params['rsi_oversold']} → {'✅' if current_rsi <= strategy.params['rsi_oversold'] else '❌'}")
print(f"  Overbought: > {strategy.params['rsi_overbought']} → {'✅' if current_rsi >= strategy.params['rsi_overbought'] else '❌'}")

print(f"\nBollinger Bands:")
print(f"  Upper: ${current_bb_upper:,.2f}")
print(f"  Lower: ${current_bb_lower:,.2f}")
print(f"  Prix actuel: ${current_price:,.2f}")
print(f"  Touch BB lower: {'✅' if current_price <= current_bb_lower else '❌'}")
print(f"  Touch BB upper: {'✅' if current_price >= current_bb_upper else '❌'}")

# TEST 3: Support/Resistance zones
print("\n" + "="*80)
print("TEST 3: Zones Support/Resistance")
print("="*80)

resistance_zone = period_high - range_size * 0.05
support_zone = period_low + range_size * 0.05

print(f"Support zone: ${support_zone:,.2f}")
print(f"Resistance zone: ${resistance_zone:,.2f}")
print(f"Prix actuel: ${current_price:,.2f}")

if current_price <= support_zone:
    print(f"✅ Dans zone SUPPORT → Signal LONG possible")
elif current_price >= resistance_zone:
    print(f"✅ Dans zone RESISTANCE → Signal SHORT possible")
else:
    print(f"❌ Dans le milieu du range → Pas de signal")
    print(f"   (besoin <= ${support_zone:,.2f} pour LONG ou >= ${resistance_zone:,.2f} pour SHORT)")

# Lancer l'analyse complète
print("\n" + "="*80)
print("TEST 4: Analyse complète V10")
print("="*80)

signal = strategy.analyze('BTCUSDT', df)

if signal:
    print(f"✅ SIGNAL GÉNÉRÉ!")
    print(f"   Side: {signal['side']}")
    print(f"   Confidence: {signal['confidence']}%")
    print(f"   Confluences: {signal['confluences']}")
else:
    print(f"❌ Aucun signal")

print("="*80)
