"""
Script d'Urgence - Ferme Toutes les Positions
À utiliser en cas de problème critique
"""

import logging
from apollo_client import ApolloDegenClient

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def emergency_close_all():
    """Ferme toutes les positions ouvertes immédiatement"""

    logger.info("=" * 80)
    logger.info("⚠️  SCRIPT D'URGENCE - FERMETURE DE TOUTES LES POSITIONS")
    logger.info("=" * 80)
    logger.info("")

    # Confirmer
    print("⚠️  ATTENTION: Ce script va fermer TOUTES les positions ouvertes sur ApolloX")
    print("   Cela inclut:")
    print("   - Fermeture immédiate au prix du marché")
    print("   - Annulation de tous les ordres pendants")
    print("   - Perte/Gain réalisé selon prix actuel")
    print("")

    confirm = input("Êtes-vous SÛR de vouloir continuer? (tapez 'CLOSE ALL'): ").strip()

    if confirm != 'CLOSE ALL':
        logger.info("❌ Annulé")
        return

    try:
        # Créer client
        client = ApolloDegenClient()

        # Récupérer positions
        logger.info("\n🔍 Récupération des positions ouvertes...")
        positions = client.get_positions()

        if not positions:
            logger.info("✅ Aucune position ouverte - rien à faire")
            return

        logger.info(f"   Trouvé {len(positions)} position(s) ouverte(s)\n")

        # Afficher positions
        for pos in positions:
            symbol = pos['symbol']
            amount = float(pos['positionAmt'])
            entry = float(pos['entryPrice'])
            unreal_pnl = float(pos['unrealizedProfit'])

            side = 'LONG' if amount > 0 else 'SHORT'
            pnl_emoji = "🟢" if unreal_pnl > 0 else "🔴"

            logger.info(
                f"   {symbol}: {side} {abs(amount)} @ ${entry:.2f} | "
                f"PnL: {pnl_emoji}${unreal_pnl:+.2f}"
            )

        print("\n")
        confirm2 = input("Confirmer la fermeture de CES positions? (yes/no): ").strip().lower()

        if confirm2 != 'yes':
            logger.info("❌ Annulé")
            return

        # Fermer chaque position
        logger.info("\n🔻 Fermeture des positions...\n")

        closed_count = 0
        errors = []

        for pos in positions:
            symbol = pos['symbol']
            amount = float(pos['positionAmt'])

            if amount == 0:
                continue

            try:
                # Annuler ordres pendants
                logger.info(f"   Annulation ordres {symbol}...")
                client.cancel_all_orders(symbol)

                # Fermer position
                side = 'LONG' if amount > 0 else 'SHORT'
                logger.info(f"   Fermeture {side} {symbol}...")

                result = client.close_position(symbol, side, abs(amount))

                if result:
                    logger.info(f"   ✅ {symbol} fermé")
                    closed_count += 1
                else:
                    logger.error(f"   ❌ Échec fermeture {symbol}")
                    errors.append(symbol)

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

        # Résumé
        logger.info("\n" + "=" * 80)
        logger.info("📊 RÉSUMÉ")
        logger.info("=" * 80)
        logger.info(f"Positions fermées: {closed_count}/{len(positions)}")

        if errors:
            logger.warning(f"Erreurs sur: {', '.join(errors)}")
            logger.warning("⚠️  Vérifiez ces positions manuellement sur ApolloX")
        else:
            logger.info("✅ Toutes les positions fermées avec succès")

    except Exception as e:
        logger.error(f"❌ ERREUR CRITIQUE: {e}")
        logger.error("⚠️  Allez sur https://www.apollox.finance et fermez manuellement")


if __name__ == '__main__':
    emergency_close_all()

    logger.info("\n✅ Script terminé")
