import { TradingEngine } from '@stock-bot/engine';

async function debugRustShortTrades() {
  // Create engine config for backtest mode
  const engineConfig = {
    startTime: new Date('2023-01-01').getTime(),
    endTime: new Date('2023-02-01').getTime(),
    speedMultiplier: 0
  };
  
  console.log('=== RUST CORE SHORT TRADE DEBUG ===\n');
  
  console.log('1. Creating TradingEngine in backtest mode...');
  const engine = new TradingEngine('backtest', engineConfig);
  
  // Simulate opening a short position
  console.log('\n2. Submitting SELL order to open short position...');
  const sellOrder = {
    id: 'sell-order-001',
    symbol: 'TEST',
    side: 'sell',
    quantity: 100,
    orderType: 'market',
    timeInForce: 'DAY'
  };
  const sellOrderId = engine.submitOrder(sellOrder);
  console.log(`   Sell order ID: ${sellOrderId}`);
  
  // Process the sell fill
  console.log('\n3. Processing SELL fill...');
  const sellFillResult = engine.processFillWithMetadata(
    'TEST',      // symbol
    50.0,        // price
    100,         // quantity
    'sell',      // side
    0.1,         // commission
    sellOrderId, // orderId
    'debug-strategy' // strategyId
  );
  console.log(`   Fill result: ${sellFillResult}`);
  
  // Check positions
  console.log('\n4. Checking positions after SELL...');
  const positionsAfterSell = engine.getPosition('TEST');
  console.log('   Position:', positionsAfterSell);
  
  // Check open trades
  const openTradesAfterSell = JSON.parse(engine.getOpenTrades());
  console.log('   Open trades:', openTradesAfterSell.length);
  if (openTradesAfterSell.length > 0) {
    console.log('   First open trade:', openTradesAfterSell[0]);
  }
  
  // Check closed trades
  const closedTradesAfterSell = JSON.parse(engine.getClosedTrades());
  console.log('   Closed trades:', closedTradesAfterSell.length);
  
  // Now close the short with a buy order
  console.log('\n5. Submitting BUY order to close short position...');
  const buyOrder = {
    id: 'buy-order-001',
    symbol: 'TEST',
    side: 'buy',
    quantity: 100,
    orderType: 'market',
    timeInForce: 'DAY'
  };
  const buyOrderId = engine.submitOrder(buyOrder);
  console.log(`   Buy order ID: ${buyOrderId}`);
  
  // Process the buy fill
  console.log('\n6. Processing BUY fill...');
  const buyFillResult = engine.processFillWithMetadata(
    'TEST',      // symbol
    48.0,        // price (profit on short)
    100,         // quantity
    'buy',       // side
    0.1,         // commission
    buyOrderId,  // orderId
    'debug-strategy' // strategyId
  );
  console.log(`   Fill result: ${buyFillResult}`);
  
  // Check positions after closing
  console.log('\n7. Checking positions after BUY...');
  const positionsAfterBuy = engine.getPosition('TEST');
  console.log('   Position:', positionsAfterBuy);
  
  // Check open trades after closing
  const openTradesAfterBuy = JSON.parse(engine.getOpenTrades());
  console.log('   Open trades:', openTradesAfterBuy.length);
  
  // Check closed trades after closing - THIS IS WHERE WE SHOULD SEE THE SHORT TRADE
  const closedTradesAfterBuy = JSON.parse(engine.getClosedTrades());
  console.log('   Closed trades:', closedTradesAfterBuy.length);
  
  if (closedTradesAfterBuy.length > 0) {
    console.log('\n8. Closed trade details:');
    closedTradesAfterBuy.forEach((trade: any, i: number) => {
      console.log(`   Trade ${i + 1}:`);
      console.log(`     ID: ${trade.id}`);
      console.log(`     Side: ${trade.side}`);
      console.log(`     Entry: ${trade.entry_price} @ ${trade.entry_time}`);
      console.log(`     Exit: ${trade.exit_price} @ ${trade.exit_time}`);
      console.log(`     P&L: ${trade.pnl} (${trade.pnl_percent}%)`);
      console.log(`     Quantity: ${trade.quantity}`);
    });
  } else {
    console.log('\n❌ ERROR: No closed trades found! Short trade was not recorded.');
  }
  
  // Also check trade history
  console.log('\n9. Trade history:');
  const tradeHistory = JSON.parse(engine.getTradeHistory());
  tradeHistory.forEach((trade: any, i: number) => {
    console.log(`   Trade ${i + 1}: ${trade.side} ${trade.quantity} @ ${trade.price}`);
  });
  
  // Check totals
  console.log('\n10. Summary:');
  console.log(`   Total trades: ${engine.getTradeCount()}`);
  console.log(`   Closed trades: ${engine.getClosedTradeCount()}`);
  const [realizedPnl, unrealizedPnl] = engine.getTotalPnl();
  console.log(`   Realized P&L: ${realizedPnl}`);
  console.log(`   Unrealized P&L: ${unrealizedPnl}`);
}

// Run the debug
debugRustShortTrades().catch(console.error);