#!/usr/bin/env python3
"""
Get position by trade hash
"""
import os
from dotenv import load_dotenv
from apollox_v2_client import ApolloXV2Client

load_dotenv()

private_key = os.getenv('WALLET_PRIVATE_KEY')
client = ApolloXV2Client(private_key=private_key)

# Trade hash from the last transaction
trade_hash = "0x658eb89d282942230efff0909815190586ccc3686d2ea550f1f25c110dd8fbd8"

print("\n" + "="*80)
print("🔍 RÉCUPÉRATION POSITION PAR TRADE HASH")
print("="*80)
print(f"Trade Hash: {trade_hash}")
print()

try:
    # Convertir en bytes32
    trade_hash_bytes = bytes.fromhex(trade_hash.replace('0x', ''))

    # Appeler getPositionByHashV2
    position = client.contract.functions.getPositionByHashV2(trade_hash_bytes).call()

    print("✅ Position trouvée!")
    print()
    print(f"   Trade Hash: {position[0].hex()}")
    print(f"   User: {position[1]}")
    print(f"   Pair Base: {position[2]}")
    print(f"   Side: {'LONG' if position[3] else 'SHORT'}")
    print(f"   Margin: ${position[4] / 1e18:.2f}")
    print(f"   Qty: {position[5] / 1e10:.4f}")
    print(f"   Entry Price: ${position[6] / 1e8:.2f}")
    print(f"   Stop Loss: ${position[7] / 1e8:.2f}")
    print(f"   Take Profit: ${position[8] / 1e8:.2f}")
    print()

    # Vérifier si la position est encore active
    if position[4] > 0:  # margin > 0
        print("🟢 Position ACTIVE")
    else:
        print("🔴 Position FERMÉE")

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

print("="*80)
