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

export interface Backtest {
  id: string;
  name: string;
  strategy: string;
  symbols: string[];
  startDate: string;
  endDate: string;
  initialCapital: number;
  config: Record<string, any>;
  createdAt: string;
  updatedAt: string;
}

export interface Run {
  id: string;
  backtestId: string;
  runNumber: number;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
  speedMultiplier: number;
  error?: string;
  startedAt?: string;
  completedAt?: string;
  pausedAt?: string;
  progress: number;
  currentSimulationDate?: string;
  createdAt: string;
  updatedAt: string;
}

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

export interface CreateRunRequest {
  speedMultiplier?: number | null;
}

export interface RunResult {
  runId: string;
  backtestId: string;
  status: 'completed';
  completedAt: string;
  config: {
    name: string;
    strategy: string;
    symbols: string[];
    startDate: string;
    endDate: string;
    initialCapital: number;
    commission: number;
    slippage: number;
    dataFrequency: string;
  };
  metrics: any;
  equity: any[];
  ohlcData: Record<string, any[]>;
  trades: any[];
  positions: any;
  analytics: any;
  executionTime: number;
}

export const backtestApiV2 = {
  // Backtest operations
  async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
    const response = await fetch(`${API_BASE_URL}/api/v2/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();
  },

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

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

    return response.json();
  },

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

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

    return response.json();
  },

  async updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
    const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(updates),
    });

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

    return response.json();
  },

  async deleteBacktest(id: string): Promise<void> {
    const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
      method: 'DELETE',
    });

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

  // Run operations
  async createRun(backtestId: string, request?: CreateRunRequest): Promise<Run> {
    const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request || {}),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`Failed to create run:`, response.status, errorText);
      throw new Error(`Failed to create run: ${response.statusText}`);
    }

    return response.json();
  },

  async listRuns(backtestId: string): Promise<Run[]> {
    const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`);

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

    return response.json();
  },

  async getRun(id: string): Promise<Run> {
    const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`);

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

    return response.json();
  },

  async getRunResults(runId: string): Promise<RunResult> {
    const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`);

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

    return response.json();
  },

  async pauseRun(id: string): Promise<void> {
    const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/pause`, {
      method: 'POST',
    });

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

  async resumeRun(id: string): Promise<void> {
    const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/resume`, {
      method: 'POST',
    });

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

  async cancelRun(id: string): Promise<void> {
    const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, {
      method: 'POST',
    });

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

  async updateRunSpeed(id: string, speedMultiplier: number): Promise<void> {
    const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/speed`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ speedMultiplier }),
    });

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

  // Note: WebSocket connections are handled by the useWebSocket hook
  // which connects to ws://localhost:2003/ws?runId={runId}
};