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

async function checkDriftAccount() {
  console.log('🔍 Checking Drift account without subscription...');
  
  try {
    // Setup wallet (same as our service)
    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('🔑 Wallet public key:', keypair.publicKey.toString());
    
    // Check SOL balance
    const balance = await connection.getBalance(keypair.publicKey);
    console.log('💰 SOL balance:', (balance / 1e9).toFixed(6), 'SOL');
    
    // Check if Drift user account exists (without SDK)
    const DRIFT_PROGRAM_ID = 'dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH';
    
    // Calculate user account PDA manually
    const [userAccountPDA] = await PublicKey.findProgramAddress(
      [
        Buffer.from('user'),
        keypair.publicKey.toBuffer(),
        Buffer.from([0]) // subAccountId = 0
      ],
      new PublicKey(DRIFT_PROGRAM_ID)
    );
    
    console.log('🏦 Drift user account PDA:', userAccountPDA.toString());
    
    // Check if account exists
    const accountInfo = await connection.getAccountInfo(userAccountPDA);
    
    if (accountInfo) {
      console.log('✅ Drift user account EXISTS!');
      console.log('📊 Account data length:', accountInfo.data.length);
      console.log('👤 Account owner:', accountInfo.owner.toString());
      console.log('\n🎉 Your Drift account is properly initialized!');
      console.log('🔧 The issue is likely with the Drift SDK subscription/connection.');
    } else {
      console.log('❌ Drift user account does NOT exist.');
      console.log('📝 You need to initialize your account first.');
      console.log('🌐 Visit https://app.drift.trade and deposit some USDC to initialize your account.');
    }
    
  } catch (error) {
    console.error('❌ Check failed:', error.message);
  }
}

checkDriftAccount().catch(console.error);
