#!/usr/bin/env python3
"""
Optimisation RAPIDE - HIGH LEVERAGE (100-225x) avec 20% position size
"""

import pandas as pd
import numpy as np
import random
import json
from datetime import datetime
from adaptive_strategy import AdaptiveStrategy
from backtest_adaptive import AdaptiveBacktest
import logging

logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)

# Fichiers de sauvegarde
RESULTS_FILE = 'optimization_results_high_lev.json'
SUMMARY_FILE = 'optimization_summary_high_lev.txt'

# Charger données réduites
df = pd.read_csv('historical_data/BTCUSDT_5m_2000candles.csv')
df['timestamp'] = pd.to_datetime(df['timestamp'])

print(f"\n⚡ OPTIMISATION HIGH LEVERAGE - 2000 bougies")
print(f"📊 Période: {df['timestamp'].iloc[0]} → {df['timestamp'].iloc[-1]}")
print(f"🔬 Tests: 30 configurations | Leverage: 100-225x | Position: 20%\n")
print(f"💾 Sauvegarde: {RESULTS_FILE}\n")

results = []

for i in range(1, 31):
    # Params aléatoires
    params = {
        'sl_atr_mult': random.uniform(0.8, 2.0),
        'tp_atr_mult': random.uniform(2.0, 5.0),
        'min_confidence': random.randint(70, 85),
        'leverage': random.choice([100, 125, 150, 175, 200, 225]),  # HIGH LEVERAGE!
    }

    # S'assurer TP > SL * 1.5
    if params['tp_atr_mult'] < params['sl_atr_mult'] * 1.5:
        params['tp_atr_mult'] = params['sl_atr_mult'] * random.uniform(2.5, 4.0)

    # Stratégie
    strategy = AdaptiveStrategy(leverage=params['leverage'])
    strategy.params['ranging']['sl_atr_multiplier'] = params['sl_atr_mult']
    strategy.params['ranging']['tp_atr_multiplier'] = params['tp_atr_mult']
    strategy.params['ranging']['min_confidence'] = params['min_confidence']

    # Backtest
    backtest = AdaptiveBacktest(strategy, initial_capital=100.0)
    res = backtest.run(df, "BTCUSD_DEGEN")

    if not res or res['total_trades'] == 0:
        continue

    # Enregistrer
    result = {
        'iteration': i,
        'params': params,
        'trades': res['total_trades'],
        'wr': res['win_rate'],
        'pnl': res['total_pnl_pct'],
        'pf': res['profit_factor'],
        'final': res['final_capital'],
    }
    results.append(result)

    # 💾 SAUVEGARDER IMMÉDIATEMENT
    with open(RESULTS_FILE, 'w') as f:
        json.dump(results, f, indent=2)

    # Afficher si profitable
    if result['pnl'] > 0 and result['pf'] > 1.0:
        print(f"✅ #{i} | PnL: {result['pnl']:+.1f}% | PF: {result['pf']:.2f} | Lev: {params['leverage']}x | Trades: {result['trades']}")

# Trier et afficher TOP 10
profitable = [r for r in results if r['pnl'] > 0 and r['pf'] > 1.0]

print(f"\n{'='*80}")
print(f"🏆 TOP 10 CONFIGURATIONS (HIGH LEVERAGE)")
print(f"{'='*80}")

if not profitable:
    print("\n❌ Aucune config profitable! Voici les meilleures:")
    best = sorted(results, key=lambda x: x['pnl'], reverse=True)[:10]
else:
    best = sorted(profitable, key=lambda x: x['pnl'], reverse=True)[:10]

for idx, r in enumerate(best, 1):
    p = r['params']
    print(f"\n#{idx}. PnL: {r['pnl']:+.1f}% | PF: {r['pf']:.2f} | WR: {r['wr']:.1f}% | Trades: {r['trades']}")
    print(f"   Leverage: {p['leverage']}x")
    print(f"   SL: {p['sl_atr_mult']:.2f}x ATR | TP: {p['tp_atr_mult']:.2f}x ATR | Ratio: {p['tp_atr_mult']/p['sl_atr_mult']:.1f}:1")
    print(f"   Min Confidence: {p['min_confidence']}%")
    print(f"   Capital final: ${r['final']:.2f}")

print(f"\n{'='*80}\n")

# 💾 SAUVEGARDER SUMMARY
with open(SUMMARY_FILE, 'w') as f:
    f.write(f"OPTIMISATION RANGING STRATEGY - HIGH LEVERAGE - {datetime.now()}\n")
    f.write("="*80 + "\n\n")
    f.write(f"Tests: 30 configurations\n")
    f.write(f"Leverage range: 100-225x\n")
    f.write(f"Position size: 20% (ISOLATED)\n")
    f.write(f"Période: {df['timestamp'].iloc[0]} → {df['timestamp'].iloc[-1]}\n")
    f.write(f"Configs profitables: {len(profitable)}/{len(results)}\n\n")
    f.write("="*80 + "\n")
    f.write("TOP 10 CONFIGURATIONS\n")
    f.write("="*80 + "\n\n")

    for idx, r in enumerate(best, 1):
        p = r['params']
        f.write(f"#{idx}. PnL: {r['pnl']:+.1f}% | PF: {r['pf']:.2f} | WR: {r['wr']:.1f}% | Trades: {r['trades']}\n")
        f.write(f"   Leverage: {p['leverage']}x\n")
        f.write(f"   SL: {p['sl_atr_mult']:.2f}x ATR | TP: {p['tp_atr_mult']:.2f}x ATR | Ratio: {p['tp_atr_mult']/p['sl_atr_mult']:.1f}:1\n")
        f.write(f"   Min Confidence: {p['min_confidence']}%\n")
        f.write(f"   Capital final: ${r['final']:.2f}\n\n")

print(f"💾 Résultats sauvegardés:")
print(f"   - {RESULTS_FILE} (JSON complet)")
print(f"   - {SUMMARY_FILE} (Résumé TOP 10)\n")
