#!/usr/bin/env bun

import { BacktestEngine } from './apps/stock/core/index.js';

// Create a simple test configuration
const config = {
  name: 'TypeScript Strategy Test',
  symbols: ['AA', 'AAS'],
  startDate: '2024-01-01T00:00:00Z',
  endDate: '2024-01-15T00:00:00Z',
  initialCapital: 100000,
  commission: 0.001,
  slippage: 0.0001,
  dataFrequency: '1d',
};

// Create the Rust engine
const engine = new BacktestEngine(config);

// Add TypeScript strategy with callback
console.log('Adding TypeScript strategy with callback...');
engine.addTypescriptStrategy(
  'SMA Crossover',
  'strategy-test-1',
  { fastPeriod: 5, slowPeriod: 15 },
  (callJson) => {
    const call = JSON.parse(callJson);
    console.log('TypeScript callback called:', call.method);
    
    if (call.method === 'on_market_data') {
      const data = call.data;
      console.log(`Market data for ${data.symbol}: close=${data.data?.close}`);
      return JSON.stringify({ signals: [] });
    } else if (call.method === 'on_fill') {
      console.log('Fill received:', call.data);
      return JSON.stringify({ signals: [] });
    }
    
    return JSON.stringify({ signals: [] });
  }
);

// Load some test market data
const testData = [];
const startDate = new Date('2024-01-01');
for (let i = 0; i < 20; i++) {
  const date = new Date(startDate);
  date.setDate(date.getDate() + i);
  
  // Add data for both symbols
  for (const symbol of ['AA', 'AAS']) {
    const basePrice = symbol === 'AA' ? 100 : 50;
    const price = basePrice + Math.sin(i / 3) * 5 + Math.random() * 2;
    
    testData.push({
      symbol,
      timestamp: date.getTime(),
      type: 'bar',
      open: price - 0.5,
      high: price + 0.5,
      low: price - 1,
      close: price,
      volume: 1000000,
      vwap: price,
    });
  }
}

console.log(`Loading ${testData.length} market data points...`);
engine.loadMarketData(testData);

// Run the backtest
console.log('Running backtest...');
try {
  const resultJson = engine.run();
  const result = JSON.parse(resultJson);
  
  console.log('\nBacktest Results:');
  console.log('Total trades:', result.trades?.length || 0);
  console.log('Final equity:', result.equity_curve[result.equity_curve.length - 1]?.[1]);
  console.log('Metrics:', result.metrics);
  
} catch (error) {
  console.error('Backtest failed:', error);
}