import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di';

async function debugPositionTracking() {
  // Create service container with detailed logging
  const container: IServiceContainer = {
    logger: {
      info: (msg: string, ...args: any[]) => console.log('[INFO]', msg, ...args),
      error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args),
      warn: (msg: string, ...args: any[]) => console.warn('[WARN]', msg, ...args),
      debug: (msg: string, ...args: any[]) => console.log('[DEBUG]', msg, ...args),
    } as any,
    custom: {}
  };

  // Initialize services
  const storageService = new StorageService();
  const marketDataService = new MarketDataService(container);
  const executionService = new ExecutionService(container);
  const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
  const strategyManager = new StrategyManager(container);

  // Set services in container
  container.custom = {
    MarketDataService: marketDataService,
    ExecutionService: executionService,
    ModeManager: modeManager,
    StorageService: storageService
  };

  // Initialize backtest mode with full config
  await modeManager.initializeMode({
    mode: 'backtest',
    startDate: '2023-06-01T00:00:00Z',
    endDate: '2023-09-01T00:00:00Z',  // Just 3 months for debugging
    speed: 'max',
    symbols: ['AAPL'],
    initialCapital: 100000,
    dataFrequency: '1d',
    strategy: 'sma-crossover'
  });

  // Create backtest engine
  const backtestEngine = new BacktestEngine(container, storageService, strategyManager);

  // Listen to strategy events for debugging
  strategyManager.on('order', (orderEvent: any) => {
    console.log('\n📊 STRATEGY ORDER EVENT:', orderEvent);
  });

  // Configure backtest
  const config = {
    mode: 'backtest' as const,
    name: 'Position Tracking Debug',
    strategy: 'sma-crossover',
    symbols: ['AAPL'],
    startDate: '2023-06-01T00:00:00Z',
    endDate: '2023-09-01T00:00:00Z',
    initialCapital: 100000,
    commission: 0.001,
    slippage: 0.0001,
    dataFrequency: '1d' as const,
    speed: 'max' as const
  };

  console.log('Starting position tracking debug...\n');

  try {
    const result = await backtestEngine.runBacktest(config);
    
    console.log('\n=== FINAL RESULTS ===');
    console.log(`Total Trades: ${result.metrics.totalTrades}`);
    console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
    
    console.log('\n=== TRADE DETAILS ===');
    let buyCount = 0;
    let sellCount = 0;
    
    result.trades.forEach((trade, i) => {
      console.log(`\nTrade ${i + 1}:`);
      console.log(`  Symbol: ${trade.symbol}`);
      console.log(`  Side: ${trade.side}`);
      console.log(`  Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
      console.log(`  Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
      console.log(`  Quantity: ${trade.quantity}`);
      console.log(`  P&L: $${trade.pnl.toFixed(2)}`);
      
      if (trade.side === 'buy') buyCount++;
      else if (trade.side === 'sell') sellCount++;
    });
    
    console.log(`\n=== TRADE SIDE SUMMARY ===`);
    console.log(`Buy trades: ${buyCount}`);
    console.log(`Sell trades: ${sellCount}`);
    
    // Check final positions
    console.log('\n=== FINAL POSITIONS ===');
    result.positions.forEach(pos => {
      console.log(`${pos.symbol}: ${pos.quantity} shares @ avg $${pos.averagePrice.toFixed(2)}`);
    });

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

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