// REAL Drift Protocol Limit Order Test - Orders will be visible in Drift UI
// This test places limit orders that will appear in the Orders tab

const { DriftClient, initialize, OrderType, PositionDirection } = require('@drift-labs/sdk');
const { Connection, Keypair } = require('@solana/web3.js');
const { Wallet } = require('@coral-xyz/anchor');

const TEST_SYMBOL = 'SOL-PERP';
const MARKET_INDEX = 0; // SOL-PERP
const POSITION_SIZE_USD = 1.0; // $1 for testing

async function placeRealLimitOrders() {
  console.log('🚀 REAL DRIFT PROTOCOL LIMIT ORDER TEST');
  console.log('============================================================');
  console.log('⚠️  This test places REAL LIMIT ORDERS that will be visible in Drift UI');
  console.log(`💰 Position size: $${POSITION_SIZE_USD} each`);
  console.log('📋 Orders will appear in the "Orders" tab until filled or cancelled');
  console.log('============================================================\n');

  try {
    // 1. Setup Drift client
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=5e236449-f936-4af7-ae38-f15e2f1a3757');
    const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY);
    const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray));
    const wallet = new Wallet(keypair);
    
    const sdkConfig = initialize({ env: 'mainnet-beta' });
    const driftClient = new DriftClient({
      connection,
      wallet,
      programID: sdkConfig.DRIFT_PROGRAM_ID,
      opts: { 
        commitment: 'confirmed',
        skipPreflight: false,
        preflightCommitment: 'confirmed'
      }
    });

    await driftClient.subscribe();
    console.log('✅ Connected to Drift Protocol');

    // 2. Get current market price
    const perpMarketAccount = driftClient.getPerpMarketAccount(MARKET_INDEX);
    const currentPrice = Number(perpMarketAccount.amm.lastMarkPriceTwap) / 1e6;
    console.log(`📊 Current SOL price: $${currentPrice.toFixed(2)}\n`);

    // 3. Calculate position size
    const positionSizeSOL = POSITION_SIZE_USD / currentPrice;
    const baseAssetAmount = Math.floor(positionSizeSOL * 1e9); // Convert to base units

    console.log(`📋 Position calculation:`);
    console.log(`   USD Amount: $${POSITION_SIZE_USD}`);
    console.log(`   SOL Amount: ${positionSizeSOL.toFixed(6)} SOL`);
    console.log(`   Base Asset Amount: ${baseAssetAmount}\n`);

    // 4. Test different percentage levels with LIMIT orders
    const testCases = [
      { 
        name: 'Conservative Scalping (1.5% above market)', 
        priceOffset: 0.015,
        description: 'Buy limit 1.5% above current price'
      },
      { 
        name: 'Moderate Scalping (1.0% above market)', 
        priceOffset: 0.01,
        description: 'Buy limit 1.0% above current price'
      },
      { 
        name: 'Tight Scalping (0.5% above market)', 
        priceOffset: 0.005,
        description: 'Buy limit 0.5% above current price'
      },
      { 
        name: 'Ultra-tight Scalping (0.25% above market)', 
        priceOffset: 0.0025,
        description: 'Buy limit 0.25% above current price'
      }
    ];

    const placedOrders = [];

    for (const testCase of testCases) {
      console.log(`🔬 Testing: ${testCase.name}`);
      console.log(`   ${testCase.description}`);
      
      // Calculate limit price (above current market price so it won't execute immediately)
      const limitPrice = currentPrice * (1 + testCase.priceOffset);
      const limitPriceBN = Math.floor(limitPrice * 1e6);
      
      console.log(`   Current Price: $${currentPrice.toFixed(4)}`);
      console.log(`   Limit Price: $${limitPrice.toFixed(4)} (+${(testCase.priceOffset * 100).toFixed(2)}%)`);
      console.log(`   Price Difference: $${(limitPrice - currentPrice).toFixed(4)}`);

      try {
        // Place limit order (will appear in Orders tab)
        const orderParams = {
          orderType: OrderType.LIMIT,
          marketIndex: MARKET_INDEX,
          direction: PositionDirection.LONG,
          baseAssetAmount,
          price: limitPriceBN,
          reduceOnly: false,
        };

        console.log(`   📤 Placing limit order...`);
        
        const orderTx = await driftClient.placePerpOrder(orderParams);
        
        console.log(`   ✅ SUCCESS: Limit order placed!`);
        console.log(`   📋 Transaction: ${orderTx}`);
        console.log(`   🎯 Order will be visible in Drift "Orders" tab`);
        
        placedOrders.push({
          testCase: testCase.name,
          limitPrice: limitPrice.toFixed(4),
          priceOffset: testCase.priceOffset,
          tx: orderTx
        });

        // Wait between orders to avoid rate limiting
        await new Promise(resolve => setTimeout(resolve, 2000));

      } catch (error) {
        console.log(`   ❌ FAILED: ${error.message}`);
        
        // Analyze failure reason
        if (error.message.includes('price')) {
          console.log(`   📊 Price Analysis:`);
          console.log(`      Price difference: ${(limitPrice - currentPrice).toFixed(4)} USD`);
          console.log(`      Percentage difference: ${(testCase.priceOffset * 100).toFixed(2)}%`);
          console.log(`      Minimum tick size issue: ${limitPrice - currentPrice < 0.01 ? 'LIKELY' : 'UNLIKELY'}`);
        }
      }
      
      console.log(''); // Empty line for readability
    }

    // 5. Summary of placed orders
    console.log('🎯 SUMMARY OF PLACED ORDERS:');
    console.log('============================================================');
    
    if (placedOrders.length > 0) {
      console.log(`✅ Successfully placed ${placedOrders.length} limit orders:`);
      placedOrders.forEach((order, index) => {
        console.log(`   ${index + 1}. ${order.testCase}`);
        console.log(`      Limit Price: $${order.limitPrice}`);
        console.log(`      Transaction: ${order.tx}`);
      });
      
      console.log('\n🔍 CHECK DRIFT PROTOCOL UI:');
      console.log('   Navigate to: Positions → Orders tab');
      console.log('   You should see the limit orders listed');
      console.log('   Orders will remain until market price reaches limit price or you cancel them');
      
      console.log('\n🧹 TO CANCEL ORDERS:');
      console.log('   Option 1: Use Drift UI (recommended for safety)');
      console.log('   Option 2: Run cancel script (we can create this)');

      // Get the smallest successful percentage
      const smallestOffset = Math.min(...placedOrders.map(o => o.priceOffset));
      console.log(`\n🏆 SMALLEST SUCCESSFUL PERCENTAGE: ${(smallestOffset * 100).toFixed(2)}%`);
      console.log('   This proves the minimum percentage can be set to this level');

    } else {
      console.log('❌ No orders were successfully placed');
      console.log('   All test cases failed - current minimums may be necessary');
    }

    console.log('\n💡 RECOMMENDED MINIMUM PERCENTAGES:');
    if (placedOrders.length > 0) {
      const smallestOffset = Math.min(...placedOrders.map(o => o.priceOffset));
      console.log(`   stopLossPercentCalc = Math.max(stopLossPercent / 100, ${smallestOffset.toFixed(4)}) // ${(smallestOffset * 100).toFixed(2)}%`);
      console.log(`   takeProfitPercentCalc = Math.max(takeProfitPercent / 100, ${(smallestOffset / 2).toFixed(4)}) // ${((smallestOffset / 2) * 100).toFixed(2)}%`);
    } else {
      console.log('   Keep current minimums - all tests failed');
    }

    await driftClient.unsubscribe();

  } catch (error) {
    console.error('❌ Test failed:', error);
  }
}

// Safety check
if (process.argv.includes('--confirm')) {
  placeRealLimitOrders();
} else {
  console.log('⚠️  SAFETY CONFIRMATION REQUIRED ⚠️');
  console.log('This test will place REAL limit orders on Drift Protocol');
  console.log('Orders will be visible in the Drift UI until cancelled');
  console.log('');
  console.log('To proceed, run: node test-drift-real-limit-orders.js --confirm');
}
