"""
Backtest ULTRA RAPIDE - 100 meilleures configs seulement
"""
import pandas as pd
import numpy as np
from apollo_client import ApolloDegenClient

print('\n' + '='*80)
print('⚡ ULTRA FAST BACKTEST')
print('='*80)

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

print(f'✅ {len(df)} bougies')
print()

# MA
df['ma_20'] = df['close'].rolling(20).mean()

def backtest(df, ma_period, sl_pct, tp_ratio, leverage):
    """Backtest simple"""
    cap = 100
    trades = []
    pos = None

    for i in range(ma_period + 10, len(df), 2):  # Skip 1 bougie sur 2 pour vitesse
        close = df.iloc[i]['close']
        ma = df.iloc[i][f'ma_{ma_period}']

        if pd.isna(ma):
            continue

        # Position ouverte?
        if pos:
            # Check SL/TP
            hit_sl = (pos['side'] == 'LONG' and close <= pos['sl']) or \
                     (pos['side'] == 'SHORT' and close >= pos['sl'])
            hit_tp = (pos['side'] == 'LONG' and close >= pos['tp']) or \
                     (pos['side'] == 'SHORT' and close <= pos['tp'])

            if hit_sl or hit_tp:
                if pos['side'] == 'LONG':
                    pnl_pct = (close - pos['entry']) / pos['entry']
                else:
                    pnl_pct = (pos['entry'] - close) / pos['entry']

                pnl = pnl_pct * leverage * pos['margin']
                cap += pnl
                trades.append(pnl)
                pos = None

        # Nouveau signal
        if not pos and cap > 0:
            side = 'LONG' if close > ma else 'SHORT'

            if side == 'LONG':
                sl = close * (1 - sl_pct)
                tp = close * (1 + sl_pct * tp_ratio)
            else:
                sl = close * (1 + sl_pct)
                tp = close * (1 - sl_pct * tp_ratio)

            pos = {
                'side': side,
                'entry': close,
                'sl': sl,
                'tp': tp,
                'margin': cap * 0.05
            }

    # Close final
    if pos:
        close = df.iloc[-1]['close']
        if pos['side'] == 'LONG':
            pnl_pct = (close - pos['entry']) / pos['entry']
        else:
            pnl_pct = (pos['entry'] - close) / pos['entry']
        pnl = pnl_pct * leverage * pos['margin']
        cap += pnl
        trades.append(pnl)

    if not trades:
        return None

    ret = ((cap - 100) / 100) * 100
    wins = [t for t in trades if t > 0]
    wr = (len(wins) / len(trades)) * 100

    return {
        'return': round(ret, 2),
        'trades': len(trades),
        'win_rate': round(wr, 1),
        'capital': round(cap, 2)
    }

# Test configs prometteuses
results = []

print('🧪 Test de 100 configurations prometteuses...')
print()

configs = [
    # MA20 - configs autour de la baseline
    (20, 0.00025, 6, 250),  # Baseline
    (20, 0.0001, 8, 250),   # SL plus serré, TP plus large
    (20, 0.0002, 10, 200),
    (20, 0.0003, 8, 200),
    (20, 0.0005, 6, 150),
    (20, 0.0001, 10, 250),
    (20, 0.00015, 8, 250),
    (20, 0.0002, 6, 250),
    (20, 0.00025, 8, 250),
    (20, 0.0003, 6, 200),

    # MA10 - fast trend
    (10, 0.0001, 10, 250),
    (10, 0.00025, 8, 250),
    (10, 0.0002, 10, 200),
    (10, 0.0001, 8, 250),
    (10, 0.00015, 10, 250),
    (10, 0.0003, 6, 200),
    (10, 0.0002, 8, 250),
    (10, 0.00025, 10, 200),
    (10, 0.0001, 6, 250),
    (10, 0.0005, 5, 150),

    # MA30 - slower trend
    (30, 0.0001, 10, 250),
    (30, 0.00025, 8, 250),
    (30, 0.0002, 8, 200),
    (30, 0.0003, 6, 200),
    (30, 0.0001, 8, 250),
    (30, 0.00015, 10, 250),
    (30, 0.0002, 10, 250),
    (30, 0.00025, 6, 250),
    (30, 0.0005, 5, 150),
    (30, 0.0001, 12, 250),

    # MA50 - long trend
    (50, 0.0001, 10, 250),
    (50, 0.0002, 8, 200),
    (50, 0.00025, 6, 200),
    (50, 0.0003, 8, 200),
    (50, 0.0001, 12, 250),
    (50, 0.00015, 10, 250),
    (50, 0.0002, 10, 200),
    (50, 0.00025, 8, 250),
    (50, 0.0005, 5, 150),
    (50, 0.0001, 8, 250),

    # Aggressive SL configs
    (20, 0.00005, 15, 250),
    (20, 0.00008, 12, 250),
    (10, 0.00005, 15, 250),
    (10, 0.00008, 12, 250),
    (30, 0.00005, 15, 250),

    # High TP ratio configs
    (20, 0.0001, 15, 250),
    (20, 0.0001, 20, 250),
    (10, 0.0001, 15, 250),
    (10, 0.0001, 20, 250),
    (30, 0.0001, 15, 250),

    # Medium leverage configs
    (20, 0.0002, 8, 150),
    (20, 0.0003, 6, 150),
    (10, 0.0002, 10, 150),
    (30, 0.0002, 8, 150),
    (50, 0.0002, 8, 150),

    # Lower leverage high SL
    (20, 0.001, 5, 100),
    (20, 0.002, 4, 100),
    (10, 0.001, 6, 100),
    (30, 0.001, 5, 100),
    (50, 0.001, 5, 100),

    # Mixed configs
    (15, 0.0001, 10, 250),
    (15, 0.00025, 8, 250),
    (15, 0.0002, 8, 200),
    (25, 0.0001, 10, 250),
    (25, 0.00025, 8, 250),
    (25, 0.0002, 8, 200),
    (40, 0.0001, 10, 250),
    (40, 0.00025, 8, 250),
    (40, 0.0002, 8, 200),

    # Ultra tight SL
    (20, 0.00003, 20, 250),
    (20, 0.00004, 15, 250),
    (10, 0.00003, 20, 250),
    (30, 0.00003, 20, 250),

    # Balanced configs
    (20, 0.0004, 6, 200),
    (20, 0.0006, 5, 200),
    (10, 0.0004, 8, 200),
    (30, 0.0004, 6, 200),
    (50, 0.0004, 6, 200),

    # High leverage low SL
    (20, 0.0001, 6, 250),
    (20, 0.00015, 6, 250),
    (10, 0.0001, 8, 250),
    (30, 0.0001, 6, 250),
    (50, 0.0001, 6, 250),

    # Additional promising
    (12, 0.0001, 10, 250),
    (12, 0.00025, 8, 250),
    (35, 0.0001, 10, 250),
    (35, 0.00025, 8, 250),
    (45, 0.0001, 10, 250),
    (45, 0.00025, 8, 250),
]

print(f'Testing {len(configs)} configurations...\n')

# Calculer toutes les MA nécessaires
for ma in set([c[0] for c in configs]):
    df[f'ma_{ma}'] = df['close'].rolling(ma).mean()

for i, (ma, sl, tp, lev) in enumerate(configs, 1):
    if i % 20 == 0:
        print(f'⏳ {i}/{len(configs)}...')

    result = backtest(df, ma, sl, tp, lev)
    if result:
        results.append({
            'ma': ma,
            'sl': sl,
            'tp': tp,
            'lev': lev,
            **result
        })

print(f'\n✅ {len(results)} résultats')
print()

# Sort
results.sort(key=lambda x: x['return'], reverse=True)

# TOP 20
print('='*80)
print('🏆 TOP 20 CONFIGURATIONS')
print('='*80)
print()

for i, r in enumerate(results[:20], 1):
    print(f"{i}. MA{r['ma']} | SL {r['sl']*100:.3f}% | TP {r['tp']}:1 | Lev {r['lev']}x")
    print(f"   💵 Return: {r['return']:+.2f}% (${r['capital']:.2f})")
    print(f"   ✅ WR: {r['win_rate']:.1f}% | Trades: {r['trades']}")
    print()

# Champion
if results:
    c = results[0]
    print('='*80)
    print('👑 CHAMPION')
    print('='*80)
    print(f"MA{c['ma']} Cross Strategy")
    print(f"Stop-Loss: {c['sl']*100:.4f}%")
    print(f"Take-Profit: {c['tp']}:1 ratio")
    print(f"Leverage: {c['lev']}x")
    print(f"Return: {c['return']:+.2f}%")
    print(f"Win Rate: {c['win_rate']:.1f}%")
    print(f"Trades: {c['trades']}")
    print(f"Capital final: ${c['capital']:.2f}")
    print('='*80)
