"""
Test de paramètres EXTRÊMES pour trouver ce qui fonctionne
"""

import logging
import numpy as np
from apollo_client import ApolloDegenClient
from signals.short_term_signals import ShortTermSignalGenerator

logging.basicConfig(level=logging.WARNING)

print("\n" + "="*100)
print("🚀 TEST DE PARAMÈTRES EXTRÊMES")
print("="*100)

client = ApolloDegenClient()
df = client.get_klines('BTCUSDT', '1m', limit=1500)

signal_gen = ShortTermSignalGenerator()

# Paramètres EXTRÊMES à tester
extreme_configs = [
    # SL TRÈS TIGHT + TP TRÈS LARGE (scalping agressif)
    {'name': 'Ultra Scalp 1', 'sl': 0.0005, 'tp_ratio': 10, 'lev': 250},  # SL 0.05%, TP 0.5%
    {'name': 'Ultra Scalp 2', 'sl': 0.001, 'tp_ratio': 8, 'lev': 250},   # SL 0.1%, TP 0.8%
    {'name': 'Ultra Scalp 3', 'sl': 0.0015, 'tp_ratio': 6, 'lev': 250},  # SL 0.15%, TP 0.9%

    # SL LARGE + TP TRÈS LARGE (swing)
    {'name': 'Swing 1', 'sl': 0.01, 'tp_ratio': 3, 'lev': 100},   # SL 1%, TP 3%
    {'name': 'Swing 2', 'sl': 0.015, 'tp_ratio': 2, 'lev': 100},  # SL 1.5%, TP 3%
    {'name': 'Swing 3', 'sl': 0.02, 'tp_ratio': 2, 'lev': 50},    # SL 2%, TP 4%

    # TP/SL ÉGAUX (ratio 1:1)
    {'name': 'Equal 1:1 tight', 'sl': 0.002, 'tp_ratio': 1, 'lev': 250},
    {'name': 'Equal 1:1 wide', 'sl': 0.005, 'tp_ratio': 1, 'lev': 200},

    # TP ÉNORME (ratio 20:1)
    {'name': 'Mega TP 1', 'sl': 0.001, 'tp_ratio': 20, 'lev': 250},  # SL 0.1%, TP 2%
    {'name': 'Mega TP 2', 'sl': 0.002, 'tp_ratio': 15, 'lev': 200},  # SL 0.2%, TP 3%

    # Leverage FAIBLE (moins de risque)
    {'name': 'Low Lev 1', 'sl': 0.005, 'tp_ratio': 3, 'lev': 25},
    {'name': 'Low Lev 2', 'sl': 0.01, 'tp_ratio': 2, 'lev': 10},
]

print(f"\n🔬 Test de {len(extreme_configs)} configurations extrêmes...")
print(f"{'Name':<20} | {'SL%':<8} | {'TP%':<8} | {'Lev':<6} | {'Return%':<10} | {'WR%':<7} | {'Trades':<8}")
print("-"*100)

results = []

for cfg in extreme_configs:
    capital = 1000
    trades = []

    # Test SANS inversion (signaux directs)
    for i in range(100, len(df) - 100, 10):  # Check every 10 candles
        if len([t for t in trades if 'exit' not in t]) >= 2:  # Max 2 positions
            continue

        window_df = df.iloc[:i]
        signals = signal_gen.generate_signals(window_df, 'BTCUSDT')

        if not signals:
            continue

        signal = max(signals, key=lambda x: x.score)
        entry_price = df.iloc[i]['close']

        # SL/TP
        if signal.side == 'LONG':
            sl = entry_price * (1 - cfg['sl'])
            tp = entry_price * (1 + cfg['sl'] * cfg['tp_ratio'])
        else:
            sl = entry_price * (1 + cfg['sl'])
            tp = entry_price * (1 - cfg['sl'] * cfg['tp_ratio'])

        trade = {
            'entry_idx': i,
            'entry_price': entry_price,
            'side': signal.side,
            'sl': sl,
            'tp': tp
        }
        trades.append(trade)

    # Process all exits
    for trade in trades:
        if 'exit' in trade:
            continue

        for j in range(trade['entry_idx'] + 1, min(trade['entry_idx'] + 200, len(df))):
            candle = df.iloc[j]
            exit_price = None

            if trade['side'] == 'LONG':
                if candle['low'] <= trade['sl']:
                    exit_price = trade['sl']
                elif candle['high'] >= trade['tp']:
                    exit_price = trade['tp']
            else:
                if candle['high'] >= trade['sl']:
                    exit_price = trade['sl']
                elif candle['low'] <= trade['tp']:
                    exit_price = trade['tp']

            if exit_price:
                pnl_pct = ((exit_price - trade['entry_price']) / trade['entry_price']) if trade['side'] == 'LONG' else ((trade['entry_price'] - exit_price) / trade['entry_price'])
                pnl_usd = capital * 0.1 * cfg['lev'] * pnl_pct
                capital += pnl_usd

                trade['exit'] = exit_price
                trade['pnl'] = pnl_usd
                break

    completed = [t for t in trades if 'exit' in t]

    if len(completed) >= 3:
        total_return = ((capital - 1000) / 1000) * 100
        wins = len([t for t in completed if t['pnl'] > 0])
        wr = wins / len(completed) * 100

        print(f"{cfg['name']:<20} | {cfg['sl']*100:<8.2f} | {cfg['sl']*100*cfg['tp_ratio']:<8.2f} | {cfg['lev']:<6} | {total_return:<10.2f} | {wr:<7.1f} | {len(completed):<8}")

        results.append({
            'config': cfg,
            'return': total_return,
            'wr': wr,
            'trades': len(completed),
            'capital': capital
        })

# Best result
if results:
    best = max(results, key=lambda x: x['return'])

    print("\n" + "="*100)
    print("🥇 MEILLEURE CONFIG TROUVÉE")
    print("="*100)
    print(f"Name:       {best['config']['name']}")
    print(f"SL:         {best['config']['sl']*100:.3f}%")
    print(f"TP:         {best['config']['sl']*100*best['config']['tp_ratio']:.3f}% (ratio {best['config']['tp_ratio']}:1)")
    print(f"Leverage:   {best['config']['lev']}x")
    print(f"")
    print(f"Return:     {best['return']:+.2f}%")
    print(f"Win Rate:   {best['wr']:.1f}%")
    print(f"Trades:     {best['trades']}")
    print(f"Capital:    ${best['capital']:.2f}")

    if best['return'] > 5:
        print(f"\n✅ CONFIGURATION PROFITABLE TROUVÉE !")
    elif best['return'] > 0:
        print(f"\n⚠️  Légèrement profitable, peut être optimisé")
    else:
        print(f"\n❌ Toutes les configs sont perdantes sur cette période")

    print("="*100)
