"""
Stratégie SIMPLE: Trend Following basique
Si prix > MA → LONG
Si prix < MA → SHORT
"""

import logging
import numpy as np
import pandas as pd
from apollo_client import ApolloDegenClient

logging.basicConfig(level=logging.WARNING)

print("\n" + "="*100)
print("📈 STRATÉGIE SIMPLE: TREND FOLLOWING")
print("="*100)

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

# Add moving averages
df['ma_20'] = df['close'].rolling(20).mean()
df['ma_50'] = df['close'].rolling(50).mean()
df['ma_100'] = df['close'].rolling(100).mean()

# Test plusieurs configs simples
configs = [
    {'name': 'MA20 Tight', 'ma_period': 20, 'sl': 0.003, 'tp_ratio': 3, 'lev': 250},
    {'name': 'MA20 Wide', 'ma_period': 20, 'sl': 0.005, 'tp_ratio': 2, 'lev': 200},
    {'name': 'MA50 Tight', 'ma_period': 50, 'sl': 0.003, 'tp_ratio': 3, 'lev': 250},
    {'name': 'MA50 Wide', 'ma_period': 50, 'sl': 0.005, 'tp_ratio': 2, 'lev': 200},
    {'name': 'MA100 Tight', 'ma_period': 100, 'sl': 0.003, 'tp_ratio': 3, 'lev': 250},
    {'name': 'MA100 Wide', 'ma_period': 100, 'sl': 0.005, 'tp_ratio': 2, 'lev': 200},
]

print(f"\n{'Strategy':<20} | {'MA':<6} | {'SL%':<7} | {'TP:SL':<7} | {'Lev':<6} | {'Return%':<10} | {'WR%':<7} | {'Trades':<8}")
print("-"*100)

results = []

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

    ma_col = f"ma_{cfg['ma_period']}"

    for i in range(cfg['ma_period'] + 10, len(df) - 50, 20):  # Every 20 candles
        if pd.isna(df.iloc[i][ma_col]):
            continue

        if len([t for t in trades if 'exit' not in t]) >= 2:  # Max 2 positions
            continue

        close = df.iloc[i]['close']
        ma = df.iloc[i][ma_col]

        # Simple trend logic
        if close > ma:
            side = 'LONG'
        elif close < ma:
            side = 'SHORT'
        else:
            continue

        # Entry
        entry_price = close

        # SL/TP
        if 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': side,
            'sl': sl,
            'tp': tp
        }
        trades.append(trade)

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

        for j in range(trade['entry_idx'] + 1, 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['ma_period']:<6} | {cfg['sl']*100:<7.2f} | {cfg['tp_ratio']:<7} | {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
        })

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

    print("\n" + "="*100)
    print("🥇 MEILLEURE STRATÉGIE TREND FOLLOWING")
    print("="*100)
    print(f"Strategy:   {best['config']['name']}")
    print(f"MA Period:  {best['config']['ma_period']}")
    print(f"SL:         {best['config']['sl']*100:.2f}%")
    print(f"TP:         {best['config']['sl']*100*best['config']['tp_ratio']:.2f}% (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✅ STRATÉGIE PROFITABLE !")
        print(f"\n📝 Cette stratégie simple bat les stratégies complexes !")
        print(f"   → Remplacer ShortTermSignalGenerator par simple MA cross")
    elif best['return'] > 0:
        print(f"\n⚠️  Légèrement profitable")
    else:
        print(f"\n❌ Même le trend following perd sur cette période")
        print(f"   → Le marché était probablement en range choppy")

    print("="*100)
else:
    print("\n❌ Aucune stratégie n'a généré assez de trades")
