const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';

export interface BacktestRequest {
  strategy: string;
  symbols: string[];
  startDate: string;
  endDate: string;
  initialCapital: number;
  config?: Record<string, any>;
}

export interface BacktestJob {
  id: string;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
  strategy: string;
  symbols: string[];
  startDate: string;
  endDate: string;
  initialCapital: number;
  config: Record<string, any>;
  createdAt: string;
  updatedAt: string;
  error?: string;
}

export interface BacktestResult {
  // Identification
  backtestId: string;
  status: 'completed' | 'failed' | 'cancelled';
  completedAt: string;
  
  // Configuration
  config: {
    name: string;
    strategy: string;
    symbols: string[];
    startDate: string;
    endDate: string;
    initialCapital: number;
    commission: number;
    slippage: number;
    dataFrequency: string;
  };
  
  // Performance metrics
  metrics: {
    totalReturn: number;
    sharpeRatio: number;
    maxDrawdown: number;
    winRate: number;
    totalTrades: number;
    profitFactor: number;
    profitableTrades: number;
    avgWin: number;
    avgLoss: number;
    expectancy: number;
    calmarRatio: number;
    sortinoRatio: number;
  };
  
  // Chart data
  equity: Array<{ date: string; value: number }>;
  ohlcData: Record<string, Array<{
    time: number;
    open: number;
    high: number;
    low: number;
    close: number;
    volume?: number;
  }>>;
  
  // Trade history
  trades: Array<{
    id: string;
    symbol: string;
    entryDate: string;
    exitDate: string | null;
    entryPrice: number;
    exitPrice: number;
    quantity: number;
    side: string;
    pnl: number;
    pnlPercent: number;
    commission: number;
    duration: number;
  }>;
  
  // Positions
  positions: Array<{
    symbol: string;
    quantity: number;
    averagePrice: number;
    currentPrice: number;
    unrealizedPnl: number;
    realizedPnl: number;
  }>;
  
  // Analytics
  analytics: {
    drawdownSeries: Array<{ timestamp: number; value: number }>;
    dailyReturns: number[];
    monthlyReturns: Record<string, number>;
    exposureTime: number;
    riskMetrics: Record<string, number>;
  };
}

export const backtestApi = {
  // Create a new backtest
  async createBacktest(request: BacktestRequest): Promise<BacktestJob> {
    const response = await fetch(`${API_BASE_URL}/api/backtests`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
    });

    if (!response.ok) {
      throw new Error(`Failed to create backtest: ${response.statusText}`);
    }

    return response.json();
  },

  // Get backtest status
  async getBacktest(id: string): Promise<BacktestJob> {
    const response = await fetch(`${API_BASE_URL}/api/backtests/${id}`);

    if (!response.ok) {
      throw new Error(`Failed to get backtest: ${response.statusText}`);
    }

    return response.json();
  },

  // Get backtest results
  async getBacktestResults(id: string): Promise<BacktestResult> {
    const response = await fetch(`${API_BASE_URL}/api/backtests/${id}/results`);

    if (!response.ok) {
      throw new Error(`Failed to get results: ${response.statusText}`);
    }

    return response.json();
  },

  // List all backtests
  async listBacktests(limit = 50, offset = 0): Promise<BacktestJob[]> {
    const response = await fetch(
      `${API_BASE_URL}/api/backtests?limit=${limit}&offset=${offset}`
    );

    if (!response.ok) {
      throw new Error(`Failed to list backtests: ${response.statusText}`);
    }

    return response.json();
  },

  // Cancel a running backtest
  async cancelBacktest(id: string): Promise<void> {
    const response = await fetch(`${API_BASE_URL}/api/backtests/${id}/cancel`, {
      method: 'POST',
    });

    if (!response.ok) {
      throw new Error(`Failed to cancel backtest: ${response.statusText}`);
    }
  },
};