#!/usr/bin/env python3
"""
Script pour forcer le mode isolated sur toutes les positions Hyperliquid
"""

import sys
import logging
from hyperliquid_client import HyperliquidClient

# Configuration du logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def fix_isolated_margin():
    """Force le mode isolated sur toutes les positions existantes"""

    print("=" * 60)
    print("FIX ISOLATED MARGIN - CORRECTION DES POSITIONS")
    print("=" * 60)

    try:
        # Initialiser le client
        logger.info("Initialisation du client Hyperliquid...")
        client = HyperliquidClient()

        if not client.exchange:
            logger.error("❌ Exchange API non disponible")
            return

        # Récupérer les positions actuelles
        logger.info("Récupération des positions actuelles...")
        account_state = client.get_account_state()

        if not account_state or 'assetPositions' not in account_state:
            logger.warning("Aucune position trouvée")
            return

        positions = account_state['assetPositions']
        logger.info(f"Trouvé {len(positions)} positions")

        # Afficher les positions actuelles
        print("\nPositions actuelles:")
        print("Symbol | Size | Leverage | Margin Mode")
        print("-" * 45)

        symbols_to_fix = []
        for pos in positions:
            symbol = pos['position']['coin']
            size = float(pos['position']['szi'])
            leverage = pos['position'].get('leverage', {}).get('value', 1)

            # Vérifier le mode margin (cross vs isolated)
            leverage_type = pos['position'].get('leverage', {}).get('type', 'unknown')
            is_cross = leverage_type == 'cross'
            margin_mode = "CROSS" if is_cross else "ISOLATED"

            print(f"{symbol:6} | {size:8.3f} | {leverage:8}x | {margin_mode}")

            # Si en mode cross, ajouter à la liste de correction
            if is_cross or leverage_type == 'unknown':
                symbols_to_fix.append({
                    'symbol': symbol,
                    'current_leverage': leverage
                })

        if not symbols_to_fix:
            logger.info("✅ Toutes les positions sont déjà en mode ISOLATED")
            return

        print(f"\n🔧 {len(symbols_to_fix)} positions à corriger vers ISOLATED:")

        # Corriger chaque position
        for pos_info in symbols_to_fix:
            symbol = pos_info['symbol']
            current_leverage = pos_info['current_leverage']

            try:
                logger.info(f"Correction {symbol} vers ISOLATED margin...")

                # Forcer le mode isolated en mettant à jour le leverage
                result = client.exchange.update_leverage(
                    leverage=int(current_leverage),
                    name=symbol,
                    is_cross=False  # Force isolated
                )

                if result and result.get('status') == 'ok':
                    logger.info(f"✅ {symbol} corrigé vers ISOLATED")
                else:
                    logger.warning(f"⚠️  {symbol} correction incertaine: {result}")

            except Exception as e:
                logger.error(f"❌ Erreur correction {symbol}: {e}")

        print("\n" + "=" * 60)
        print("CORRECTION TERMINÉE")
        print("=" * 60)
        print("Vérifiez les positions dans l'interface Hyperliquid")
        print("pour confirmer que toutes sont en mode ISOLATED")

    except Exception as e:
        logger.error(f"❌ Erreur générale: {e}", exc_info=True)

if __name__ == "__main__":
    fix_isolated_margin()