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';

// Modify the data generation to ensure we get both golden and death crosses
function generateMockDataWithBothCrosses() {
  const data = [];
  const startDate = new Date('2023-01-01');
  let price = 150;
  
  // Create 365 days of data with clear trends
  for (let i = 0; i < 365; i++) {
    const date = new Date(startDate);
    date.setDate(date.getDate() + i);
    
    // Create alternating trends every ~30 days
    const cycleDay = i % 60;
    if (cycleDay < 30) {
      // Uptrend - will create golden crosses
      price += Math.random() * 2 - 0.5; // Bias upward
    } else {
      // Downtrend - will create death crosses
      price -= Math.random() * 2 - 0.5; // Bias downward
    }
    
    // Add some volatility
    const dayChange = (Math.random() - 0.5) * 4;
    price = Math.max(100, Math.min(200, price + dayChange));
    
    data.push({
      timestamp: date.toISOString(),
      open: price - Math.random() * 2,
      high: price + Math.random() * 2,
      low: price - Math.random() * 2,
      close: price,
      volume: Math.floor(Math.random() * 10000000) + 5000000
    });
  }
  
  return data;
}

async function forceBothTradeTypes() {
  // Create service container with minimal logging
  const container: IServiceContainer = {
    logger: {
      info: (msg: string, ...args: any[]) => {
        if (msg.includes('cross detected') || msg.includes('Generated') || msg.includes('Position update')) {
          console.log('[INFO]', msg, ...args);
        }
      },
      error: console.error,
      warn: () => {},
      debug: () => {},
    } 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
  };

  // Override the mock data generation
  const originalGenerateMockData = marketDataService.generateMockData;
  marketDataService.generateMockData = function(symbol: string, startDate: string, endDate: string) {
    console.log('Generating mock data with forced crossovers...');
    return generateMockDataWithBothCrosses();
  };

  // 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: 'Force Both Trade Types',
    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('=== TESTING WITH FORCED CROSSOVERS ===\n');

  try {
    const result = await backtestEngine.runBacktest(config);
    
    console.log('\n=== BACKTEST COMPLETE ===');
    console.log(`Total Trades: ${result.metrics.totalTrades}`);
    
    // Analyze trades
    let longTrades = 0;
    let shortTrades = 0;
    
    result.trades.forEach((trade) => {
      if (trade.side === 'buy') {
        longTrades++;
        console.log(`\nLONG trade found:`);
        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)}`);
      } else {
        shortTrades++;
        console.log(`\nSHORT trade found:`);
        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)}`);
      }
    });
    
    console.log('\n=== FINAL SUMMARY ===');
    console.log(`LONG trades: ${longTrades}`);
    console.log(`SHORT trades: ${shortTrades}`);
    console.log(`Total trades: ${result.metrics.totalTrades}`);
    
    if (longTrades > 0 && shortTrades > 0) {
      console.log('\n✅ SUCCESS: Both long and short trades are working!');
    } else {
      console.log('\n❌ ISSUE: Missing trade types');
      if (longTrades === 0) console.log('  - No long trades found');
      if (shortTrades === 0) console.log('  - No short trades found');
    }

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

// Run the test
forceBothTradeTypes().catch(console.error);