"""
Récupère l'historique complet de trading Hyperliquid
"""

import sys
sys.stdout.reconfigure(encoding='utf-8')

from hyperliquid_client import HyperliquidClient
from datetime import datetime, timedelta
import json

def get_complete_trading_history():
    """Récupère l'historique complet de trading"""

    print("=== RÉCUPÉRATION HISTORIQUE COMPLET HYPERLIQUID ===\n")

    try:
        client = HyperliquidClient()

        # Récupérer tous les fills
        all_fills = client.get_fill_info(limit=1000)

        if not all_fills:
            print("Aucun fill trouvé")
            return []

        print(f"Total fills récupérés: {len(all_fills)}")

        # Organiser par symbole et analyser
        trades_by_symbol = {}
        total_volume = 0
        total_fees = 0

        for fill in all_fills:
            try:
                symbol = fill.get('coin', '').upper()
                if not symbol:
                    continue

                if symbol not in trades_by_symbol:
                    trades_by_symbol[symbol] = {
                        'trades': [],
                        'volume': 0,
                        'fees': 0,
                        'pnl': 0,
                        'open_positions': {},
                        'closed_trades': []
                    }

                # Données du fill
                fill_time = datetime.fromtimestamp(int(fill.get('time', 0)) / 1000)
                direction = fill.get('dir', '')
                price = float(fill.get('px', 0))
                size = abs(float(fill.get('sz', 0)))
                fee = float(fill.get('fee', 0))
                side = fill.get('side', '')

                trade_info = {
                    'time': fill_time,
                    'direction': direction,
                    'price': price,
                    'size': size,
                    'fee': fee,
                    'side': side,
                    'value': price * size
                }

                trades_by_symbol[symbol]['trades'].append(trade_info)
                trades_by_symbol[symbol]['volume'] += price * size
                trades_by_symbol[symbol]['fees'] += fee
                total_volume += price * size
                total_fees += fee

            except Exception as e:
                print(f"Erreur traitement fill: {e}")
                continue

        # Trier les trades par date pour chaque symbole
        for symbol in trades_by_symbol:
            trades_by_symbol[symbol]['trades'].sort(key=lambda x: x['time'])

        # Afficher le résumé
        print("\n=== RÉSUMÉ PAR SYMBOLE ===")
        print("-" * 80)

        # Trier par volume
        sorted_symbols = sorted(trades_by_symbol.items(), key=lambda x: x[1]['volume'], reverse=True)

        for symbol, data in sorted_symbols:
            trades = data['trades']
            if not trades:
                continue

            first_trade = trades[0]['time']
            last_trade = trades[-1]['time']

            print(f"\n{symbol}:")
            print(f"  Nombre de trades: {len(trades)}")
            print(f"  Volume total: ${data['volume']:,.2f}")
            print(f"  Frais totaux: ${data['fees']:.2f}")
            print(f"  Première transaction: {first_trade.strftime('%Y-%m-%d %H:%M')}")
            print(f"  Dernière transaction: {last_trade.strftime('%Y-%m-%d %H:%M')}")

            # Calculer le PnL approximatif
            long_positions = []
            short_positions = []
            realized_pnl = 0

            for trade in trades:
                if 'Open Long' in trade['direction']:
                    long_positions.append(trade)
                elif 'Close Long' in trade['direction'] and long_positions:
                    # Matching FIFO
                    entry = long_positions.pop(0) if long_positions else None
                    if entry:
                        # Utiliser la méthode centralisée de calcul PnL
                        pnl_data = client.calculate_position_pnl(
                            entry_price=entry['price'],
                            current_price=trade['price'],
                            size=trade['size'],
                            side='LONG'
                        )
                        pnl = pnl_data['pnl_dollar']
                        # Déduire les frais d'ouverture ET de fermeture
                        total_fees = entry['fee'] + trade['fee']
                        pnl_net = pnl - total_fees
                        realized_pnl += pnl_net
                elif 'Open Short' in trade['direction']:
                    short_positions.append(trade)
                elif 'Close Short' in trade['direction'] and short_positions:
                    entry = short_positions.pop(0) if short_positions else None
                    if entry:
                        # Utiliser la méthode centralisée de calcul PnL
                        pnl_data = client.calculate_position_pnl(
                            entry_price=entry['price'],
                            current_price=trade['price'],
                            size=trade['size'],
                            side='SHORT'
                        )
                        pnl = pnl_data['pnl_dollar']
                        # Déduire les frais d'ouverture ET de fermeture
                        total_fees = entry['fee'] + trade['fee']
                        pnl_net = pnl - total_fees
                        realized_pnl += pnl_net

            print(f"  PnL réalisé estimé: ${realized_pnl:.2f}")

            # Positions encore ouvertes
            if long_positions:
                print(f"  Positions LONG ouvertes: {len(long_positions)}")
            if short_positions:
                print(f"  Positions SHORT ouvertes: {len(short_positions)}")

        print("\n" + "=" * 80)
        print("TOTAUX GLOBAUX:")
        print(f"  Volume total: ${total_volume:,.2f}")
        print(f"  Frais totaux: ${total_fees:.2f}")
        print(f"  Nombre de symboles tradés: {len(trades_by_symbol)}")

        # Sauvegarder dans un fichier JSON
        output_data = {
            'generated_at': datetime.now().isoformat(),
            'total_fills': len(all_fills),
            'total_volume': total_volume,
            'total_fees': total_fees,
            'symbols': {}
        }

        for symbol, data in trades_by_symbol.items():
            output_data['symbols'][symbol] = {
                'trades_count': len(data['trades']),
                'volume': data['volume'],
                'fees': data['fees'],
                'trades': [
                    {
                        'time': t['time'].isoformat(),
                        'direction': t['direction'],
                        'price': t['price'],
                        'size': t['size'],
                        'fee': t['fee'],
                        'value': t['value']
                    }
                    for t in data['trades']
                ]
            }

        with open('hyperliquid_trading_history.json', 'w') as f:
            json.dump(output_data, f, indent=2)

        print(f"\nHistorique sauvegardé: hyperliquid_trading_history.json")

        # Analyser les périodes d'activité
        print("\n=== PÉRIODES D'ACTIVITÉ ===")
        all_trades = []
        for symbol_data in trades_by_symbol.values():
            all_trades.extend(symbol_data['trades'])

        all_trades.sort(key=lambda x: x['time'])

        if all_trades:
            # Grouper par jour
            trades_by_day = {}
            for trade in all_trades:
                day = trade['time'].date()
                if day not in trades_by_day:
                    trades_by_day[day] = []
                trades_by_day[day].append(trade)

            print(f"\nActivité par jour (derniers 7 jours):")
            sorted_days = sorted(trades_by_day.keys(), reverse=True)[:7]

            for day in sorted_days:
                day_trades = trades_by_day[day]
                day_volume = sum(t['value'] for t in day_trades)
                print(f"  {day}: {len(day_trades)} trades, Volume: ${day_volume:,.2f}")

        return trades_by_symbol

    except Exception as e:
        print(f"Erreur: {e}")
        return {}

if __name__ == "__main__":
    history = get_complete_trading_history()

    # Analyser spécifiquement BNB si présent
    if 'BNB' in history:
        print("\n=== FOCUS SUR BNB ===")
        bnb_data = history['BNB']
        print(f"Trades BNB: {len(bnb_data['trades'])}")

        # Afficher les 10 derniers trades BNB
        print("\nDerniers trades BNB:")
        for trade in bnb_data['trades'][-10:]:
            print(f"  {trade['time'].strftime('%Y-%m-%d %H:%M')} | {trade['direction']:<15} | "
                  f"${trade['price']:.2f} x {trade['size']:.3f} | Fee: ${trade['fee']:.2f}")