#!/usr/bin/env python3
"""
Approve USDC spending for the Turbo contract.
Run once per wallet.

Usage:
  python3 mm/approve_usdc.py --key 0xYOUR_PRIVATE_KEY
"""

import argparse
import json
import sys

sys.path.insert(0, "backend")
from config import TURBO_CONTRACT_ADDRESS, USDC_ADDRESS, MONAD_RPC_URL, MONAD_CHAIN_ID

# Monad USDC doesn't accept max uint256, use 1 billion USDC instead
APPROVE_AMOUNT = 1_000_000_000 * 10**6

USDC_ABI = json.loads("""[
  {
    "inputs": [
      {"name": "spender", "type": "address"},
      {"name": "amount", "type": "uint256"}
    ],
    "name": "approve",
    "outputs": [{"name": "", "type": "bool"}],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {"name": "owner", "type": "address"},
      {"name": "spender", "type": "address"}
    ],
    "name": "allowance",
    "outputs": [{"name": "", "type": "uint256"}],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [{"name": "account", "type": "address"}],
    "name": "balanceOf",
    "outputs": [{"name": "", "type": "uint256"}],
    "stateMutability": "view",
    "type": "function"
  }
]""")


def main():
    parser = argparse.ArgumentParser(description="Approve USDC for Turbo contract")
    parser.add_argument("--key", required=True, help="Private key of wallet to approve")
    args = parser.parse_args()

    from web3 import Web3

    w3 = Web3(Web3.HTTPProvider(MONAD_RPC_URL))
    account = w3.eth.account.from_key(args.key)
    address = account.address

    usdc = w3.eth.contract(
        address=Web3.to_checksum_address(USDC_ADDRESS),
        abi=USDC_ABI,
    )
    turbo = Web3.to_checksum_address(TURBO_CONTRACT_ADDRESS)

    # Check balance
    balance = usdc.functions.balanceOf(address).call()
    print(f"Wallet:    {address}")
    print(f"USDC bal:  {balance / 1e6:.2f} USDC")

    # Check current allowance
    allowance = usdc.functions.allowance(address, turbo).call()
    print(f"Allowance: {allowance / 1e6:.2f} USDC")

    if allowance >= balance and allowance > 0:
        print("Already approved!")
        return

    # Approve max
    print(f"Approving max USDC for Turbo contract {turbo}...")
    tx = usdc.functions.approve(turbo, APPROVE_AMOUNT).build_transaction({
        "from": address,
        "nonce": w3.eth.get_transaction_count(address),
        "gas": 100_000,
        "gasPrice": w3.eth.gas_price,
        "chainId": MONAD_CHAIN_ID,
    })
    signed = account.sign_transaction(tx)
    tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
    receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=30)

    if receipt.status == 1:
        print(f"Approved! TX: {tx_hash.hex()}")
    else:
        print(f"FAILED! TX: {tx_hash.hex()}")


if __name__ == "__main__":
    main()
