#!/usr/bin/env python3
"""
FIX CLOSE POSITION - Avec le BON ABI
"""

from web3 import Web3
from dotenv import load_dotenv
import os
import json

load_dotenv()

# Config
BSC_RPC = "https://bsc-dataseed.binance.org/"
APOLLOX_CONTRACT = "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0"
USDT_BSC = "0x55d398326f99059fF775485246999027B3197955"

# ABI CORRIGÉ avec la VRAIE structure ITrading.OpenTrade (17 champs)
CORRECT_ABI = json.loads('''[
    {
        "inputs": [{"internalType": "bytes32", "name": "tradeHash", "type": "bytes32"}],
        "name": "closeTrade",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [{"internalType": "address", "name": "user", "type": "address"}],
        "name": "getPositionsV2",
        "outputs": [
            {
                "components": [
                    {"internalType": "address", "name": "user", "type": "address"},
                    {"internalType": "uint32", "name": "userOpenTradeIndex", "type": "uint32"},
                    {"internalType": "uint64", "name": "entryPrice", "type": "uint64"},
                    {"internalType": "address", "name": "pairBase", "type": "address"},
                    {"internalType": "address", "name": "tokenIn", "type": "address"},
                    {"internalType": "uint96", "name": "margin", "type": "uint96"},
                    {"internalType": "uint64", "name": "stopLoss", "type": "uint64"},
                    {"internalType": "uint64", "name": "takeProfit", "type": "uint64"},
                    {"internalType": "uint24", "name": "broker", "type": "uint24"},
                    {"internalType": "bool", "name": "isLong", "type": "bool"},
                    {"internalType": "uint96", "name": "openFee", "type": "uint96"},
                    {"internalType": "int256", "name": "longAccFundingFeePerShare", "type": "int256"},
                    {"internalType": "uint96", "name": "executionFee", "type": "uint96"},
                    {"internalType": "uint40", "name": "timestamp", "type": "uint40"},
                    {"internalType": "uint80", "name": "qty", "type": "uint80"},
                    {"internalType": "uint40", "name": "holdingFeeRate", "type": "uint40"},
                    {"internalType": "uint256", "name": "openBlock", "type": "uint256"}
                ],
                "internalType": "struct ITrading.OpenTrade[]",
                "name": "",
                "type": "tuple[]"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    }
]''')

# ERC20 ABI pour USDT
ERC20_ABI = json.loads('''[
    {
        "constant": true,
        "inputs": [{"name": "_owner", "type": "address"}],
        "name": "balanceOf",
        "outputs": [{"name": "balance", "type": "uint256"}],
        "type": "function"
    }
]''')


def main():
    print("=" * 80)
    print("🔧 FIX CLOSE POSITION - AVEC LE BON ABI")
    print("=" * 80)
    print()

    # Load wallet
    private_key = os.getenv('WALLET_PRIVATE_KEY')
    if not private_key:
        print("❌ WALLET_PRIVATE_KEY manquante")
        return

    # Init Web3
    w3 = Web3(Web3.HTTPProvider(BSC_RPC))
    account = w3.eth.account.from_key(private_key)
    wallet = account.address

    print(f"📍 Wallet: {wallet}")

    # Init contracts avec BON ABI
    contract = w3.eth.contract(address=APOLLOX_CONTRACT, abi=CORRECT_ABI)
    usdt = w3.eth.contract(address=USDT_BSC, abi=ERC20_ABI)

    # 1. Vérifier balance USDT
    usdt_balance = usdt.functions.balanceOf(wallet).call() / 1e18
    print(f"💵 USDT balance: {usdt_balance:.2f}")
    print()

    # 2. Récupérer TOUTES les positions actives
    print("═" * 80)
    print("📊 POSITIONS ACTIVES (getPositionsV2)")
    print("═" * 80)

    try:
        positions = contract.functions.getPositionsV2(wallet).call()

        print(f"Positions trouvées: {len(positions)}\n")

        if not positions:
            print("⚠️  Aucune position active")
            print("   Mais $10 USDT manquent → position existe mais non visible?")
            return

        # Afficher chaque position
        for i, pos in enumerate(positions, 1):
            print(f"Position #{i}:")
            print(f"  User: {pos[0]}")
            print(f"  Index: {pos[1]}")
            print(f"  Entry Price: {pos[2] / 1e10:.2f}")
            print(f"  Pair: {pos[3]}")
            print(f"  Margin: {pos[5] / 1e18:.4f} USDT")
            print(f"  Direction: {'LONG' if pos[9] else 'SHORT'}")
            print(f"  Qty: {pos[14]}")
            print(f"  Timestamp: {pos[13]}")
            print()

            # Tenter de fermer cette position
            print(f"🔓 Tentative de fermeture...")

            # Calculer trade hash
            # Note: On ne peut pas recalculer le hash ici car on ne l'a pas
            # Il faudrait l'extraire des événements lors de l'ouverture
            print(f"⚠️  Besoin du trade hash pour fermer")
            print(f"   Impossible de le recalculer à partir de la position")
            print()

    except Exception as e:
        print(f"❌ Erreur: {e}")
        import traceback
        traceback.print_exc()

    print("═" * 80)


if __name__ == '__main__':
    main()
