#!/usr/bin/env python3
"""
Débug transaction échouée ApolloX
"""

from web3 import Web3
import json

BSC_RPC_URL = "https://bsc-dataseed.binance.org/"
TX_HASH = "0x7de5cd5259ab87b27d8f3aee63aa4c525ffec722982d5a0479f29f69ba11ebb6"

w3 = Web3(Web3.HTTPProvider(BSC_RPC_URL))

print("=" * 80)
print("🔍 ANALYSE TRANSACTION ÉCHOUÉE")
print("=" * 80)

# Récupérer la transaction
tx = w3.eth.get_transaction(TX_HASH)
print(f"\n📝 Transaction Hash: {TX_HASH}")
print(f"   From: {tx['from']}")
print(f"   To: {tx['to']}")
print(f"   Value: {w3.from_wei(tx['value'], 'ether')} BNB")
print(f"   Gas: {tx['gas']}")
print(f"   Gas Price: {w3.from_wei(tx['gasPrice'], 'gwei')} gwei")

# Récupérer le receipt
receipt = w3.eth.get_transaction_receipt(TX_HASH)
print(f"\n📊 Receipt:")
print(f"   Status: {receipt['status']} ({'Success' if receipt['status'] == 1 else 'Failed'})")
print(f"   Gas Used: {receipt['gasUsed']}")
print(f"   Block: {receipt['blockNumber']}")

# Essayer de récupérer le revert reason
if receipt['status'] == 0:
    print(f"\n❌ TRANSACTION FAILED")
    print(f"\n🔍 Tentative de récupération du revert reason...")

    try:
        # Rejouer la transaction au même block pour obtenir le revert reason
        w3.eth.call(
            {
                'from': tx['from'],
                'to': tx['to'],
                'data': tx['input'],
                'value': tx['value'],
                'gas': tx['gas'],
                'gasPrice': tx['gasPrice']
            },
            block_identifier=receipt['blockNumber'] - 1
        )
        print("   ⚠️  Aucun revert detecté lors du replay")
    except Exception as e:
        error_msg = str(e)
        print(f"   💥 Revert Reason: {error_msg}")

        # Essayer de décoder le message d'erreur
        if "execution reverted" in error_msg.lower():
            # Extraire le message si possible
            if ":" in error_msg:
                parts = error_msg.split(":", 1)
                if len(parts) > 1:
                    print(f"   📝 Message décodé: {parts[1].strip()}")

# Analyser les logs
print(f"\n📋 Logs ({len(receipt['logs'])} events):")
for i, log in enumerate(receipt['logs']):
    print(f"   {i+1}. Address: {log['address']}")
    print(f"      Topics: {len(log['topics'])}")
    print(f"      Data length: {len(log['data'])} bytes")

# Vérifier l'input data
print(f"\n🔧 Input Data:")
input_data = tx['input']
print(f"   Length: {len(input_data)} bytes")
print(f"   Function selector: {input_data[:10]}")

# Décoder la fonction si possible
if input_data[:10] == '0x4ddf47d5':
    print(f"   ✅ Fonction: openMarketTrade()")

print("\n" + "=" * 80)
