#!/usr/bin/env python3
"""
Script pour fermer AUTOMATIQUEMENT toutes les positions - MODE FORCE
"""

import sys
import logging
import time
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 force_close_all_positions():
    """Ferme automatiquement toutes les positions sans confirmation"""

    print("=" * 60)
    print("🧹 NETTOYAGE FORCÉ - FERMETURE AUTOMATIQUE")
    print("=" * 60)

    try:
        client = HyperliquidClient()

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

        # Récupérer les positions
        account_state = client.get_account_state()
        if not account_state or 'assetPositions' not in account_state:
            logger.info("✅ Aucune position à fermer")
            return True

        positions = account_state['assetPositions']
        logger.info(f"FERMETURE FORCÉE de {len(positions)} positions")

        if len(positions) == 0:
            logger.info("✅ Aucune position à fermer")
            return True

        # Fermer immédiatement
        closed_count = 0
        total_pnl = 0

        for pos in positions:
            symbol = pos['position']['coin']
            size = float(pos['position']['szi'])
            unrealized_pnl = float(pos['position']['unrealizedPnl'])
            total_pnl += unrealized_pnl

            side = "LONG" if size > 0 else "SHORT"
            abs_size = abs(size)

            try:
                logger.info(f"🔥 FERMETURE FORCÉE {symbol} {side} size={abs_size:.3f} PnL=${unrealized_pnl:+.2f}")

                result = client.place_market_order(
                    symbol=symbol,
                    is_buy=(size < 0),  # BUY pour fermer SHORT, SELL pour fermer LONG
                    size=abs_size,
                    reduce_only=True,
                    order_tag=f"FORCE_CLOSE_{symbol}"
                )

                if result and result.get('success'):
                    logger.info(f"✅ {symbol} fermé")
                    closed_count += 1
                else:
                    logger.error(f"❌ Échec {symbol}: {result.get('error', 'Erreur')}")

                time.sleep(0.5)  # Délai court entre ordres

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

        print(f"\n🎯 RÉSULTAT FINAL:")
        print(f"   Positions fermées: {closed_count}/{len(positions)}")
        print(f"   PnL total réalisé: ${total_pnl:+.2f}")

        return closed_count == len(positions)

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

if __name__ == "__main__":
    print("🚀 FERMETURE FORCÉE - RESTART STRATÉGIE QUALITÉ")

    success = force_close_all_positions()

    if success:
        print("\n" + "✅" * 20)
        print("🎯 TOUTES LES POSITIONS FERMÉES")
        print("📈 PRÊT POUR STRATÉGIE HAUTE QUALITÉ")
        print("✅" * 20)
    else:
        print("\n❌ Échec partiel - Vérifiez manuellement")