require('dotenv').config()
const { Connection, PublicKey, Keypair } = require('@solana/web3.js')

async function checkWalletBalance() {
  try {
    console.log('🔍 Checking Solana wallet balance...\n')
    
    // Initialize connection
    const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'
    const connection = new Connection(rpcUrl, 'confirmed')
    console.log(`📡 Connected to: ${rpcUrl}`)
    
    // Get wallet from private key
    if (!process.env.SOLANA_PRIVATE_KEY) {
      console.error('❌ SOLANA_PRIVATE_KEY environment variable not set!')
      console.log('💡 You need to set your Solana wallet private key to trade live.')
      return
    }
    
    const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY)
    const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray))
    const publicKey = keypair.publicKey
    
    console.log(`🔑 Wallet Address: ${publicKey.toBase58()}\n`)
    
    // Check SOL balance
    const solBalance = await connection.getBalance(publicKey)
    const solBalanceFormatted = (solBalance / 1e9).toFixed(4)
    console.log(`💰 SOL Balance: ${solBalanceFormatted} SOL`)
    
    // Check USDC balance
    const usdcMint = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v')
    
    try {
      const tokenAccounts = await connection.getTokenAccountsByOwner(publicKey, {
        mint: usdcMint
      })
      
      if (tokenAccounts.value.length > 0) {
        const usdcAccount = tokenAccounts.value[0]
        const accountInfo = await connection.getTokenAccountBalance(usdcAccount.pubkey)
        const usdcBalance = parseFloat(accountInfo.value.amount) / Math.pow(10, accountInfo.value.decimals)
        console.log(`💵 USDC Balance: ${usdcBalance.toFixed(2)} USDC`)
        
        // Trading readiness check
        console.log('\n📊 TRADING READINESS CHECK:')
        console.log('=' .repeat(40))
        
        const tradingAmount = 100 // Current config
        const estimatedFees = 5 // Estimate for Jupiter swap fees
        const recommendedMinimum = tradingAmount + estimatedFees
        
        console.log(`💰 Current USDC: $${usdcBalance.toFixed(2)}`)
        console.log(`🎯 Trading Amount: $${tradingAmount}`)
        console.log(`💸 Estimated Fees: ~$${estimatedFees}`)
        console.log(`⚡ Recommended Min: $${recommendedMinimum}`)
        
        if (usdcBalance >= recommendedMinimum) {
          console.log('✅ READY FOR LIVE TRADING!')
          console.log(`   You have sufficient USDC for ${Math.floor(usdcBalance / recommendedMinimum)} trades`)
        } else {
          console.log('⚠️  INSUFFICIENT USDC FOR LIVE TRADING')
          console.log(`   You need at least $${(recommendedMinimum - usdcBalance).toFixed(2)} more USDC`)
        }
        
        // SOL for fees check
        if (solBalance < 0.01 * 1e9) { // Less than 0.01 SOL
          console.log('⚠️  LOW SOL BALANCE - You need SOL for transaction fees')
          console.log('   Recommended: At least 0.01 SOL for fees')
        } else {
          console.log('✅ Sufficient SOL for transaction fees')
        }
        
      } else {
        console.log('❌ No USDC token account found')
        console.log('💡 You need to have USDC in your wallet to trade SOL/USD')
      }
    } catch (error) {
      console.error('Error checking USDC balance:', error.message)
    }
    
    console.log('\n🔧 CURRENT TRADING CONFIG:')
    console.log('=' .repeat(30))
    console.log('Trading Amount: $100')
    console.log('Max Leverage: 3x')
    console.log('Stop Loss: 2%') 
    console.log('Take Profit: 6%')
    console.log('Max Daily Trades: 5')
    
    console.log('\n💡 RECOMMENDATIONS:')
    console.log('- Start with smaller amounts for first live trades ($10-20)')
    console.log('- Keep at least 0.01 SOL for transaction fees')
    console.log('- Monitor your first few trades closely')
    console.log('- You can always switch back to SIMULATION mode')
    
  } catch (error) {
    console.error('❌ Error checking wallet:', error)
  }
}

// Run the check
checkWalletBalance()
