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 verifyBothTradeTypes() {
  // Create service container
  const container: IServiceContainer = {
    logger: {
      info: console.log,
      error: console.error,
      warn: console.warn,
      debug: console.log,
    } 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);

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

  // Initialize backtest mode
  await modeManager.initializeMode({
    mode: 'backtest',
    startDate: '2023-01-01T00:00:00Z',
    endDate: '2024-01-01T00:00:00Z',
    speed: 'max',
    symbols: ['AAPL'],
    initialCapital: 100000,
    dataFrequency: '1d',
    strategy: 'sma-crossover'
  });

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

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

  console.log('=== VERIFYING BOTH LONG AND SHORT TRADES ===\n');

  try {
    const result = await backtestEngine.runBacktest(config);
    
    console.log('=== BACKTEST COMPLETE ===');
    console.log(`Total Trades: ${result.metrics.totalTrades}`);
    console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
    console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
    
    // Analyze trades
    let longTrades = 0;
    let shortTrades = 0;
    let longPnL = 0;
    let shortPnL = 0;
    
    console.log('\n=== DETAILED TRADE ANALYSIS ===');
    result.trades.forEach((trade, i) => {
      const isLong = trade.side === 'buy';
      const tradeType = isLong ? 'LONG' : 'SHORT';
      
      if (isLong) {
        longTrades++;
        longPnL += trade.pnl;
      } else {
        shortTrades++;
        shortPnL += trade.pnl;
      }
      
      console.log(`\nTrade ${i + 1}:`);
      console.log(`  Type: ${tradeType} position`);
      console.log(`  Opening side: ${trade.side.toUpperCase()}`);
      console.log(`  Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
      console.log(`  Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
      console.log(`  P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
      
      // Explain the trade flow
      if (isLong) {
        console.log(`  Order flow: BUY ${trade.quantity} shares → SELL ${trade.quantity} shares`);
      } else {
        console.log(`  Order flow: SELL ${trade.quantity} shares → BUY ${trade.quantity} shares`);
      }
    });
    
    console.log('\n=== SUMMARY BY TRADE TYPE ===');
    console.log(`LONG trades: ${longTrades}`);
    console.log(`  - Total P&L from longs: $${longPnL.toFixed(2)}`);
    console.log(`  - Average P&L per long: $${longTrades > 0 ? (longPnL / longTrades).toFixed(2) : '0.00'}`);
    
    console.log(`\nSHORT trades: ${shortTrades}`);
    console.log(`  - Total P&L from shorts: $${shortPnL.toFixed(2)}`);
    console.log(`  - Average P&L per short: $${shortTrades > 0 ? (shortPnL / shortTrades).toFixed(2) : '0.00'}`);
    
    console.log(`\nTotal trades: ${result.metrics.totalTrades}`);
    
    if (longTrades === 0) {
      console.log('\n⚠️  WARNING: No long trades found!');
    }
    if (shortTrades === 0) {
      console.log('\n⚠️  WARNING: No short trades found!');
    }

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

// Run the verification
verifyBothTradeTypes().catch(console.error);