import { NextResponse } from 'next/server'

export async function GET() {
  try {
    console.log('🧪 Testing Drift imports...')

    // Test import step by step
    console.log('Step 1: Importing Solana...')
    const { Connection, Keypair } = await import('@solana/web3.js')
    
    console.log('Step 2: Importing Anchor...')
    const anchor = await import('@coral-xyz/anchor')
    console.log('Anchor exports:', Object.keys(anchor))
    
    console.log('Step 3: Testing Wallet...')
    const { Wallet } = await import('@coral-xyz/anchor')
    console.log('Wallet type:', typeof Wallet)
    
    if (!process.env.SOLANA_PRIVATE_KEY) {
      return NextResponse.json({
        success: false,
        error: 'No SOLANA_PRIVATE_KEY found',
        anchorExports: Object.keys(anchor),
        walletType: typeof anchor.Wallet,
        defaultWallet: typeof anchor.default?.Wallet
      })
    }
    
    console.log('Step 4: Creating keypair...')
    const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY)
    const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray))
    
    console.log('Step 5: Creating wallet - trying different approaches...')
    let wallet
    
    // Try direct import instead
    try {
      const { Wallet: DirectWallet } = await import('@coral-xyz/anchor')
      wallet = new DirectWallet(keypair)
      console.log('✅ Wallet created via direct import')
    } catch (e1) {
      console.log('Direct import failed:', e1.message)
      
      // Try another approach - NodeWallet
      try {
        const { NodeWallet } = await import('@coral-xyz/anchor')
        wallet = new NodeWallet(keypair)
        console.log('✅ Wallet created via NodeWallet')
      } catch (e2) {
        console.log('NodeWallet failed:', e2.message)
        
        // Last resort - create simple wallet interface
        wallet = {
          publicKey: keypair.publicKey,
          signTransaction: async (tx) => {
            tx.partialSign(keypair)
            return tx
          },
          signAllTransactions: async (txs) => {
            return txs.map(tx => {
              tx.partialSign(keypair)
              return tx
            })
          }
        }
        console.log('✅ Wallet created with manual interface')
      }
    }
    
    console.log('✅ All steps successful')
    
    return NextResponse.json({
      success: true,
      message: 'Drift imports working',
      walletCreated: true,
      publicKey: keypair.publicKey.toString(),
      anchorExports: Object.keys(anchor)
    })

  } catch (error) {
    console.error('❌ Import test error:', error)
    
    return NextResponse.json({
      success: false,
      error: error.message,
      stack: error.stack
    })
  }
}

export async function POST() {
  return NextResponse.json({
    message: 'Use GET method to test Drift imports'
  }, { status: 405 })
}
