#!/usr/bin/env node

// Test Drift SDK on devnet to avoid RPC restrictions
import { DriftClient, initialize, Wallet } from '@drift-labs/sdk'
import { Connection, Keypair } from '@solana/web3.js'

async function testDriftDevnet() {
  try {
    console.log('🧪 Testing Drift SDK on devnet...')

    // Use devnet which is more permissive
    const connection = new Connection('https://api.devnet.solana.com', 'confirmed')
    
    // Create a random keypair for testing
    const keypair = Keypair.generate()
    const wallet = new Wallet(keypair)
    
    console.log('🔐 Test wallet:', keypair.publicKey.toString())

    // Initialize for devnet
    const env = 'devnet'
    const sdkConfig = initialize({ env })
    
    console.log('📋 Drift Program ID:', sdkConfig.DRIFT_PROGRAM_ID.toString())

    const driftClient = new DriftClient({
      connection,
      wallet,
      programID: sdkConfig.DRIFT_PROGRAM_ID,
      opts: {
        commitment: 'confirmed',
      },
    })

    console.log('✅ DriftClient created successfully')
    
    // Try to get program account info (read-only operation)
    const programInfo = await connection.getAccountInfo(sdkConfig.DRIFT_PROGRAM_ID)
    console.log('📊 Program account info:', programInfo ? 'Found' : 'Not found')

    // Try subscribing (this might fail without funds but should show what works)
    try {
      await driftClient.subscribe()
      console.log('✅ Subscribed to Drift client')
      
      // Try to get state
      const state = await driftClient.getStateAccount()
      console.log('📈 Drift state:', {
        admin: state.admin.toString(),
        numberOfAuthorities: state.numberOfAuthorities
      })
      
      await driftClient.unsubscribe()
      
    } catch (subscribeError) {
      console.log('ℹ️ Subscribe failed (expected for unfunded account):', subscribeError.message)
    }

    console.log('✅ Basic Drift SDK functionality working on devnet')
    
  } catch (error) {
    console.error('❌ Drift devnet test failed:', error)
  }
}

testDriftDevnet()
