#!/usr/bin/env node
require('dotenv').config();
const { Connection, Keypair, PublicKey } = require('@solana/web3.js');

async function analyzeWalletAndProviideNextSteps() {
  console.log('🔍 DRIFT ACCOUNT ANALYSIS & SOLUTION\n');
  
  try {
    const secret = process.env.SOLANA_PRIVATE_KEY;
    const keypair = Keypair.fromSecretKey(Buffer.from(JSON.parse(secret)));
    const connection = new Connection(process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com', 'confirmed');
    
    console.log('📋 CURRENT STATUS:');
    console.log('==================');
    console.log('🔑 Wallet Address:', keypair.publicKey.toString());
    
    const balance = await connection.getBalance(keypair.publicKey);
    console.log('💰 SOL Balance:', (balance / 1e9).toFixed(6), 'SOL');
    console.log('🌐 Network: mainnet-beta');
    console.log('🎯 RPC Endpoint:', process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com');
    
    // Check if Drift account exists
    const DRIFT_PROGRAM_ID = 'dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH';
    const [userAccountPDA] = await PublicKey.findProgramAddress(
      [
        Buffer.from('user'),
        keypair.publicKey.toBuffer(),
        Buffer.from([0])
      ],
      new PublicKey(DRIFT_PROGRAM_ID)
    );
    
    const accountInfo = await connection.getAccountInfo(userAccountPDA);
    console.log('🏦 Drift Account PDA:', userAccountPDA.toString());
    console.log('✅ Drift Account Exists:', !!accountInfo);
    
    if (!accountInfo) {
      console.log('\n❌ PROBLEM IDENTIFIED:');
      console.log('======================');
      console.log('Your Drift account has NOT been initialized on the blockchain.');
      console.log('This means you have never deposited funds or created a Drift account.');
      console.log('');
      console.log('🔧 SOLUTION - Follow these steps:');
      console.log('==================================');
      console.log('1. 📱 Visit https://app.drift.trade in your browser');
      console.log('2. 🔗 Connect your wallet using this address:');
      console.log('   ', keypair.publicKey.toString());
      console.log('3. 💵 Deposit some USDC (minimum ~$10) to initialize your account');
      console.log('4. ✅ Your account will be created automatically upon first deposit');
      console.log('5. 🔄 Come back and test your dashboard again');
      console.log('');
      console.log('📝 IMPORTANT NOTES:');
      console.log('===================');
      console.log('• Make sure you\'re on MAINNET (not devnet/testnet)');
      console.log('• The wallet address above must match exactly');
      console.log('• You need some SOL for transaction fees (~0.01 SOL)');
      console.log('• Initialization costs ~0.035 SOL in rent (refundable)');
      console.log('');
      console.log('🔍 After initialization, run this test again to verify.');
    } else {
      console.log('\n✅ SUCCESS:');
      console.log('============');
      console.log('Your Drift account exists! The dashboard should work now.');
      console.log('If you\'re still seeing zero balance, there might be RPC issues.');
    }
    
  } catch (error) {
    console.error('❌ Analysis failed:', error.message);
  }
}

analyzeWalletAndProviideNextSteps().catch(console.error);
