# -*- coding: utf-8 -*-
"""
Module utilitaire pour la récupération centralisée des positions
Factorisation pour éviter les incohérences entre SimpleTradingEngine et le serveur
"""

import logging
from typing import List, Dict, Optional, Tuple

logger = logging.getLogger(__name__)

class PositionRetriever:
    """Classe centralisée pour récupérer les positions de manière cohérente"""

    @staticmethod
    def get_hyperliquid_positions(hyperliquid_client, min_size: float = 0.000001) -> List[Dict]:
        """
        Récupère les positions Hyperliquid avec filtrage standardisé

        Args:
            hyperliquid_client: Client Hyperliquid
            min_size: Taille minimale pour considérer une position active

        Returns:
            Liste des positions filtrées
        """
        try:
            if not hyperliquid_client:
                logger.warning("Aucun client Hyperliquid disponible")
                return []

            raw_positions = hyperliquid_client.get_positions()
            if not raw_positions:
                logger.debug("Aucune position retournée par Hyperliquid")
                return []

            # Filtrage standardisé
            filtered_positions = []
            for pos in raw_positions:
                size = abs(float(pos.get('size', 0)))
                if size > min_size:
                    filtered_positions.append(pos)
                else:
                    symbol = pos.get('symbol', 'UNKNOWN').replace('-PERP', '')
                    logger.debug(f"Position {symbol} filtrée (taille {size} < {min_size})")

            logger.debug(f"Positions filtrées: {len(filtered_positions)}/{len(raw_positions)}")
            return filtered_positions

        except Exception as e:
            logger.error(f"Erreur récupération positions Hyperliquid: {e}")
            return []

    @staticmethod
    def get_positions_count(hyperliquid_client) -> int:
        """Compte le nombre de positions actives"""
        positions = PositionRetriever.get_hyperliquid_positions(hyperliquid_client)
        return len(positions)

    @staticmethod
    def get_positions_summary(hyperliquid_client) -> List[Tuple[str, str, float]]:
        """
        Retourne un résumé des positions (symbol, side, size)

        Returns:
            Liste de tuples (symbol, side, size)
        """
        positions = PositionRetriever.get_hyperliquid_positions(hyperliquid_client)
        summary = []

        for pos in positions:
            symbol = pos.get('symbol', 'UNKNOWN').replace('-PERP', '')
            side = pos.get('side', 'UNKNOWN').upper()
            size = abs(float(pos.get('size', 0)))
            summary.append((symbol, side, size))

        return summary

    @staticmethod
    def get_positions_with_pnl(hyperliquid_client) -> Dict[str, Dict]:
        """
        Récupère les positions avec calcul PnL pour le serveur principal

        Returns:
            Dict {symbol: {side, pnl_percent, pnl, entry_price, current_price}}
        """
        positions = PositionRetriever.get_hyperliquid_positions(hyperliquid_client)
        result = {}

        for pos in positions:
            try:
                symbol = pos.get('symbol', 'UNKNOWN').replace('-PERP', '')
                side = pos.get('side', 'UNKNOWN').upper()
                size = abs(float(pos.get('size', 0)))
                entry_price = float(pos.get('entry_price', 1))
                pnl_usd = float(pos.get('unrealized_pnl', 0))

                # Calcul PnL%
                margin_used = abs(size * entry_price)
                pnl_percent = (pnl_usd / margin_used * 100) if margin_used > 0 else 0

                result[symbol] = {
                    'side': side,
                    'pnl_percent': pnl_percent,
                    'pnl': pnl_usd,
                    'entry_price': entry_price,
                    'current_price': float(pos.get('mark_price', entry_price)),
                    'size': size
                }

            except Exception as e:
                logger.error(f"Erreur traitement position {pos}: {e}")
                continue

        return result