#!/usr/bin/env python3
"""
Vérifie les approbations USDT et l'état du wallet
"""

from web3 import Web3
import json
import os

BSC_RPC_URL = "https://bsc-dataseed.binance.org/"
APOLLOX_V2_CONTRACT = "0x1b6F2d3844C6ae7D56ceb3C3643b9060ba28FEb0"
USDT_BSC = "0x55d398326f99059fF775485246999027B3197955"

# Charger la clé privée depuis l'env
from dotenv import load_dotenv
load_dotenv()

private_key = os.getenv('WALLET_PRIVATE_KEY')
if not private_key:
    print("❌ WALLET_PRIVATE_KEY non trouvée dans .env")
    exit(1)

w3 = Web3(Web3.HTTPProvider(BSC_RPC_URL))
account = w3.eth.account.from_key(private_key)

print("=" * 80)
print("🔍 DIAGNOSTIC WALLET & APPROBATIONS")
print("=" * 80)

print(f"\n👛 Wallet: {account.address}")

# Balance BNB
bnb_balance = w3.eth.get_balance(account.address)
print(f"   BNB: {w3.from_wei(bnb_balance, 'ether'):.6f} BNB")

# Balance USDT
erc20_abi = json.loads('[{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"type":"function"}]')

usdt_contract = w3.eth.contract(
    address=Web3.to_checksum_address(USDT_BSC),
    abi=erc20_abi
)

usdt_balance = usdt_contract.functions.balanceOf(account.address).call()
print(f"   USDT: {usdt_balance / 1e18:.2f} USDT")

# Vérifier l'approbation pour ApolloX
allowance = usdt_contract.functions.allowance(
    account.address,
    Web3.to_checksum_address(APOLLOX_V2_CONTRACT)
).call()

print(f"\n📝 Approbation USDT pour ApolloX:")
print(f"   Allowance actuelle: {allowance / 1e18:.2f} USDT")

if allowance == 0:
    print(f"   ❌ AUCUNE APPROBATION - C'EST LE PROBLÈME!")
    print(f"\n💡 Solution: Approuver le contrat ApolloX")
    print(f"   Voulez-vous approuver maintenant? (y/n)")

    response = input("   > ")
    if response.lower() == 'y':
        print(f"\n🔄 Approbation en cours...")

        # Approuver pour un montant infini (2^256 - 1)
        max_approval = 2**256 - 1

        tx = usdt_contract.functions.approve(
            Web3.to_checksum_address(APOLLOX_V2_CONTRACT),
            max_approval
        ).build_transaction({
            'from': account.address,
            'gas': 100000,
            'gasPrice': w3.eth.gas_price,
            'nonce': w3.eth.get_transaction_count(account.address),
            'chainId': 56
        })

        signed_tx = account.sign_transaction(tx)
        tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)

        print(f"   ✅ Transaction envoyée: {tx_hash.hex()}")
        print(f"   ⏳ Attente confirmation...")

        receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=120)

        if receipt['status'] == 1:
            print(f"   ✅ APPROUVÉ! Gas used: {receipt['gasUsed']}")
        else:
            print(f"   ❌ Échec approbation")
    else:
        print(f"   ⏭️  Approbation annulée")
elif allowance < usdt_balance:
    print(f"   ⚠️  Allowance insuffisante (besoin: {usdt_balance / 1e18:.2f} USDT)")
else:
    print(f"   ✅ Allowance suffisante")

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