#!/usr/bin/env python3
"""
Script d'urgence pour fermer les positions en perte excessive
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from hyperliquid_client import HyperliquidClient
import time

def close_losing_positions(max_loss_threshold=-5.0):
    """Ferme toutes les positions dépassant le seuil de perte"""

    client = HyperliquidClient()

    print("=" * 60)
    print("🚨 FERMETURE D'URGENCE DES POSITIONS EN PERTE")
    print("=" * 60)
    print(f"Seuil de fermeture: {max_loss_threshold}%\n")

    # Initialiser l'exchange pour pouvoir passer des ordres
    if not client.exchange:
        try:
            from hyperliquid.exchange import Exchange
            from hyperliquid.utils import constants

            # Charger la clé privée
            key_file = "hyperliquid_key.txt"
            if os.path.exists(key_file):
                with open(key_file, 'r') as f:
                    private_key = f.read().strip()

                client.exchange = Exchange(
                    private_key,
                    constants.MAINNET_API_URL
                )
                print("✅ Exchange initialisé\n")
            else:
                print("❌ Fichier de clé privée non trouvé!")
                return
        except Exception as e:
            print(f"❌ Erreur initialisation exchange: {e}")
            return

    # Récupérer toutes les positions
    positions = client.get_positions()

    if not positions:
        print("Aucune position ouverte")
        return

    positions_to_close = []

    print("POSITIONS ACTUELLES:")
    print("-" * 60)

    for pos in positions:
        coin = pos.get('raw_position_data', {}).get('coin', '')
        data = pos.get('raw_position_data', {})
        size = float(data.get('szi', 0))
        entry_px = float(data.get('entryPx', 0))
        roe = float(data.get('returnOnEquity', 0)) * 100
        leverage = data.get('leverage', {}).get('value', 1)

        # Skip les positions vides
        if abs(size) < 0.0001:
            continue

        side = "LONG" if size > 0 else "SHORT"
        status = "🔴 À FERMER" if roe <= max_loss_threshold else "✅ OK"

        print(f"{coin:8} {side:5} | Size: {abs(size):10.4f} | Leverage: {leverage:2}x | PnL: {roe:+7.2f}% | {status}")

        # Ajouter à la liste de fermeture si nécessaire
        if roe <= max_loss_threshold:
            positions_to_close.append({
                'coin': coin,
                'side': side,
                'size': size,
                'roe': roe
            })

    print("-" * 60)

    if not positions_to_close:
        print("\n✅ Aucune position à fermer (toutes au-dessus du seuil)")
        return

    print(f"\n⚠️ {len(positions_to_close)} position(s) à fermer d'urgence:\n")

    for pos in positions_to_close:
        coin = pos['coin']
        size = pos['size']
        roe = pos['roe']
        side = pos['side']

        print(f"🔴 Fermeture {coin} {side} (PnL: {roe:.2f}%)...")

        try:
            # Fermer la position
            is_buy = size < 0  # Si SHORT (size négatif), on achète pour fermer

            result = client.exchange.market_close(
                coin=coin,
                sz=str(abs(size))
            )

            if result and result.get('status') == 'ok':
                print(f"✅ {coin} fermée avec succès!")
            else:
                print(f"⚠️ Réponse pour {coin}: {result}")

            # Attendre entre les fermetures
            time.sleep(0.5)

        except Exception as e:
            print(f"❌ Erreur fermeture {coin}: {e}")

    # Vérification finale après 3 secondes
    print("\nVérification après 3 secondes...")
    time.sleep(3)

    new_positions = client.get_positions()
    still_in_loss = []

    for pos in new_positions:
        coin = pos.get('raw_position_data', {}).get('coin', '')
        roe = float(pos.get('raw_position_data', {}).get('returnOnEquity', 0)) * 100
        size = float(pos.get('raw_position_data', {}).get('szi', 0))

        if abs(size) > 0.0001 and roe <= max_loss_threshold:
            still_in_loss.append(f"{coin} ({roe:.2f}%)")

    if still_in_loss:
        print(f"\n⚠️ Positions encore en perte: {', '.join(still_in_loss)}")
    else:
        print("\n✅ Toutes les positions en perte ont été fermées!")

    print("\n" + "=" * 60)

if __name__ == "__main__":
    # Fermer toutes les positions avec plus de 5% de perte
    close_losing_positions(max_loss_threshold=-5.0)