#!/usr/bin/env node

/**
 * Direct Drift SDK test
 */

require('dotenv').config();

async function testDrift() {
  console.log('🌊 Testing Drift SDK directly...');
  
  try {
    const { Connection, Keypair, PublicKey } = require('@solana/web3.js');
    const { 
      DriftClient, 
      Wallet,
      getUserAccountPublicKey,
      DRIFT_PROGRAM_ID
    } = require('@drift-labs/sdk');
    
    // Setup connection and wallet
    const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
    const privateKey = JSON.parse(process.env.SOLANA_PRIVATE_KEY);
    const keypair = Keypair.fromSecretKey(Buffer.from(privateKey));
    const connection = new Connection(rpcUrl, 'confirmed');
    const wallet = new Wallet(keypair);
    
    console.log(`🏠 Public Key: ${keypair.publicKey.toString()}`);
    console.log(`📡 RPC: ${rpcUrl}`);
    
    // Create Drift client
    console.log('🔧 Creating Drift client...');
    const driftClient = new DriftClient({
      connection,
      wallet,
      env: 'mainnet-beta',
      opts: { commitment: 'confirmed' }
    });
    
    console.log('📡 Subscribing to Drift client...');
    await driftClient.subscribe();
    
    console.log('🔍 Checking user account...');
    const userAccountPublicKey = await getUserAccountPublicKey(
      new PublicKey(DRIFT_PROGRAM_ID),
      keypair.publicKey,
      0
    );
    
    console.log(`👤 User account PK: ${userAccountPublicKey.toString()}`);
    
    const userAccountInfo = await connection.getAccountInfo(userAccountPublicKey);
    console.log(`👤 User account exists: ${!!userAccountInfo}`);
    
    if (userAccountInfo) {
      console.log('✅ User account found! Getting user data...');
      const user = driftClient.getUser();
      console.log('👤 User object created successfully');
      
      // Try to get some basic data
      try {
        const totalCollateral = user.getTotalCollateral();
        console.log(`💰 Total collateral (raw): ${totalCollateral.toString()}`);
      } catch (e) {
        console.log(`⚠️ Could not get collateral: ${e.message}`);
      }
    } else {
      console.log('❌ User account not found - user needs to initialize account at app.drift.trade');
    }
    
    console.log('🔌 Unsubscribing...');
    await driftClient.unsubscribe();
    
    console.log('✅ Drift test completed successfully!');
    
  } catch (error) {
    console.error('❌ Drift test failed:', error.message);
    console.error('Stack:', error.stack);
  }
}

testDrift().catch(console.error);
