#!/usr/bin/env python3
"""
Recalcule correctement les PnL en analysant les VRAIS transferts USDT
"""

import requests
import json
from datetime import datetime
from dotenv import load_dotenv
import os

load_dotenv()

WALLET_ADDRESS = '0x7476737C49d55bea691e54c2c96fD39a6bAf3049'
APOLLOX_CONTRACT = '0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0'
USDT_CONTRACT = '0x55d398326f99059fF775485246999027B3197955'
API_KEY = os.getenv('BSCSCAN_API_KEY', 'VRB4NXXEGV5FIIDDCRXQG8AN6PIVQ4ZQYJ')


def get_all_usdt_transfers():
    """Récupère TOUS les transferts USDT (in et out)"""
    url = "https://api.etherscan.io/v2/api"
    params = {
        'chainid': '56',
        'module': 'account',
        'action': 'tokentx',
        'contractaddress': USDT_CONTRACT,
        'address': WALLET_ADDRESS,
        'startblock': 65508000,
        'endblock': 99999999,
        'sort': 'asc',
        'apikey': API_KEY
    }

    response = requests.get(url, params=params, timeout=30)
    data = response.json()

    if data['status'] != '1':
        print(f"❌ Erreur API: {data.get('message', 'Unknown error')}")
        return []

    return data['result']


def analyze_transfers():
    """Analyse tous les transferts pour calculer les vrais PnL"""
    print("🔍 Récupération de tous les transferts USDT...")
    transfers = get_all_usdt_transfers()

    # Séparer les envois (wallet -> ApolloX) et réceptions (ApolloX -> wallet)
    sends = []  # Argent envoyé pour ouvrir positions
    receives = []  # Argent reçu en fermant positions

    for tx in transfers:
        from_addr = tx['from'].lower()
        to_addr = tx['to'].lower()
        wallet = WALLET_ADDRESS.lower()
        apollox = APOLLOX_CONTRACT.lower()

        value_wei = int(tx['value'])
        value_usdt = value_wei / 10**18
        timestamp = datetime.fromtimestamp(int(tx['timeStamp']))

        if from_addr == wallet and to_addr == apollox:
            # Envoi vers ApolloX (ouverture position)
            sends.append({
                'timestamp': timestamp,
                'amount': value_usdt,
                'tx_hash': tx['hash'],
                'block': int(tx['blockNumber'])
            })
        elif from_addr == apollox and to_addr == wallet:
            # Réception depuis ApolloX (fermeture position)
            receives.append({
                'timestamp': timestamp,
                'amount': value_usdt,
                'tx_hash': tx['hash'],
                'block': int(tx['blockNumber'])
            })

    print(f"✅ {len(sends)} envois (ouvertures)")
    print(f"✅ {len(receives)} réceptions (fermetures)")

    # Calculer PnL global
    total_sent = sum(s['amount'] for s in sends)
    total_received = sum(r['amount'] for r in receives)
    total_pnl = total_received - total_sent

    print(f"\n{'='*80}")
    print(f"📊 BILAN RÉEL")
    print(f"{'='*80}")
    print(f"💸 Total envoyé (margins): ${total_sent:.2f}")
    print(f"💰 Total reçu (retours):   ${total_received:.2f}")
    print(f"{'='*80}")
    print(f"📈 PnL RÉEL: ${total_pnl:+.2f}")
    print(f"{'='*80}")

    return {
        'sends': sends,
        'receives': receives,
        'total_sent': total_sent,
        'total_received': total_received,
        'total_pnl': total_pnl
    }


def update_positions_with_real_pnl():
    """Met à jour positions.json avec les vrais PnL"""

    # Analyser les transferts
    analysis = analyze_transfers()

    # Charger positions actuelles
    with open('positions.json', 'r') as f:
        data = json.load(f)

    positions = data['positions']

    # Pour chaque position, essayer de matcher avec les transferts
    print(f"\n🔧 Mise à jour des positions...")

    sends = analysis['sends']
    receives = analysis['receives']

    # Trier positions par date d'ouverture
    pos_list = [(hash, pos) for hash, pos in positions.items()]
    pos_list.sort(key=lambda x: x[1].get('opened_at', ''))

    # Assigner les sends/receives dans l'ordre
    for i, (trade_hash, pos) in enumerate(pos_list):
        if pos.get('status') != 'CLOSED':
            continue

        # Le send correspondant (dans l'ordre)
        if i < len(sends):
            sent = sends[i]
            pos['margin'] = sent['amount']

        # Le receive correspondant (dans l'ordre)
        if i < len(receives):
            received = receives[i]
            pnl = received['amount'] - pos.get('margin', 0)
            pos['pnl'] = round(pnl, 2)
            pos['pnl_pct'] = round((pnl / pos.get('margin', 1)) * 100, 2)
        else:
            # Pas de receive = perte totale
            pos['pnl'] = -pos.get('margin', 0)
            pos['pnl_pct'] = -100.0

        print(f"  ✓ {pos['symbol']} ({pos['opened_at'][:16]}): Margin ${pos['margin']:.2f}, PnL ${pos['pnl']:+.2f}")

    # Sauvegarder
    with open('positions.json', 'w') as f:
        json.dump(data, f, indent=2)

    print(f"\n✅ positions.json mis à jour avec les vrais PnL")

    return analysis


if __name__ == '__main__':
    print("="*80)
    print("🔄 RECALCUL DES PNL RÉELS")
    print("="*80)
    print()

    analysis = update_positions_with_real_pnl()

    print(f"\n{'='*80}")
    print(f"✅ TERMINÉ")
    print(f"{'='*80}")
    print(f"\nBalance actuelle: ~$49 USDT")
    print(f"PnL réel total: ${analysis['total_pnl']:+.2f}")
    print()
