#!/usr/bin/env python3
"""
Test d'ouverture et fermeture de position ApolloX V2
"""

import os
import time
import requests
from dotenv import load_dotenv
from apollox_v2_client import ApolloXV2Client

load_dotenv()

def get_btc_price():
    """Récupère le prix BTC actuel depuis Binance"""
    try:
        url = "https://api.binance.com/api/v3/ticker/price"
        response = requests.get(url, params={'symbol': 'BTCUSDT'}, timeout=5)
        response.raise_for_status()
        data = response.json()
        return float(data['price'])
    except Exception as e:
        print(f"Erreur récupération prix: {e}")
        return None

print("=" * 80)
print("🧪 TEST TRADE APOLLOX V2")
print("=" * 80)

# Configuration test - DEGEN MODE
TEST_MARGIN = 25.0  # $25 USDT
TEST_LEVERAGE = 200  # 200x leverage (DEGEN MODE!)
SYMBOL = 'BTCUSD_DEGEN'  # Utiliser paire Degen pour leverage > 50x

# Note: Degen Mode supporte jusqu'à 1001x leverage!

print(f"\n📝 Configuration test:")
print(f"   Symbole: {SYMBOL}")
print(f"   Margin: ${TEST_MARGIN}")
print(f"   Leverage: {TEST_LEVERAGE}x")
print(f"   Exposition: ${TEST_MARGIN * TEST_LEVERAGE}")

# Initialisation
private_key = os.getenv('WALLET_PRIVATE_KEY')
if not private_key:
    print("❌ WALLET_PRIVATE_KEY non trouvée")
    exit(1)

client = ApolloXV2Client(private_key=private_key)

# Vérifier balances initiales
print(f"\n💰 Balances AVANT:")
bnb_before = client.get_balance()
usdt_before = client.get_usdt_balance()
print(f"   BNB: {bnb_before:.6f}")
print(f"   USDT: ${usdt_before:.2f}")

if usdt_before < TEST_MARGIN:
    print(f"❌ Balance insuffisante pour test (besoin ${TEST_MARGIN})")
    exit(1)

# Récupérer prix actuel BTC
print(f"\n📊 Récupération prix {SYMBOL}...")
current_price = get_btc_price()
if not current_price:
    print(f"❌ Impossible de récupérer le prix")
    exit(1)
print(f"   Prix BTC: ${current_price:,.2f}")

# ÉTAPE 1: Ouvrir position LONG
print(f"\n" + "=" * 80)
print(f"🟢 ÉTAPE 1: OUVERTURE POSITION LONG")
print(f"=" * 80)

trade_hash = client.open_position(
    pair=SYMBOL,
    is_long=True,  # LONG pour test
    margin_usd=TEST_MARGIN,
    leverage=TEST_LEVERAGE,
    price=current_price,
    stop_loss=0,  # Pas de SL pour ce test rapide
    take_profit=0  # Pas de TP pour ce test rapide
)

if not trade_hash:
    print(f"❌ ÉCHEC ouverture position!")
    print(f"\n💡 Vérifier les logs pour plus de détails")
    exit(1)

print(f"✅ Position ouverte!")
print(f"   TX Hash: {trade_hash}")

# Attendre quelques secondes
print(f"\n⏳ Attente 10 secondes avant fermeture...")
time.sleep(10)

# Vérifier positions ouvertes
print(f"\n📊 Vérification positions...")
positions = client.get_positions()
print(f"   Positions actives: {len(positions)}")

if len(positions) == 0:
    print(f"⚠️  Aucune position trouvée (peut-être déjà liquidée ou fermée?)")
    print(f"   Note: Position très petite pourrait avoir été fermée automatiquement")
else:
    for i, pos in enumerate(positions):
        print(f"\n   Position #{i+1}:")
        print(f"      Trade Hash: {pos['tradeHash']}")
        print(f"      Pair: {pos['pairBase']}")
        print(f"      Direction: {'LONG' if pos['isLong'] else 'SHORT'}")
        print(f"      Margin: ${pos['margin']:.2f}")
        print(f"      Qty: {pos['qty']:.6f}")
        print(f"      Entry Price: ${pos['entryPrice']:.2f}")

# ÉTAPE 2: Fermer position
if len(positions) > 0:
    print(f"\n" + "=" * 80)
    print(f"🔴 ÉTAPE 2: FERMETURE POSITION")
    print(f"=" * 80)

    # Fermer la première position trouvée
    trade_hash_to_close = positions[0]['tradeHash']
    print(f"   Fermeture de: {trade_hash_to_close}")

    success = client.close_position(trade_hash_to_close)

    if success:
        print(f"✅ Position fermée avec succès!")
    else:
        print(f"❌ Échec fermeture position")
else:
    print(f"\n⏭️  Pas de position à fermer")

# Vérifier balances finales
print(f"\n" + "=" * 80)
print(f"💰 Balances APRÈS:")
bnb_after = client.get_balance()
usdt_after = client.get_usdt_balance()
print(f"   BNB: {bnb_after:.6f} (Δ {bnb_after - bnb_before:+.6f})")
print(f"   USDT: ${usdt_after:.2f} (Δ ${usdt_after - usdt_before:+.2f})")

print(f"\n📊 RÉSUMÉ:")
print(f"   BNB utilisé (gas): {bnb_before - bnb_after:.6f} BNB")
print(f"   PnL USDT: ${usdt_after - usdt_before:+.2f}")

if trade_hash and len(positions) > 0:
    print(f"\n✅ TEST RÉUSSI!")
    print(f"   • Position ouverte: ✅")
    print(f"   • Position détectée: ✅")
    print(f"   • Position fermée: ✅")
else:
    print(f"\n⚠️  TEST PARTIEL")
    print(f"   Vérifier manuellement l'état sur BSCScan")

print("=" * 80)
