import axios from 'axios';

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000/api';

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

export const marketDataApi = {
getGoldPrice: async (): Promise<any> => {
    const response = await api.get('/market/gold/current');
    return response.data;
  },

  getHistoricalData: async (
    interval: string = 'daily',
    outputSize: string = 'compact'
  ): Promise<any[]> => {
    const response = await api.get('/market/gold/history', {
      params: { interval, outputSize },
    });
    return response.data;
  },

  getLivePrice: async (interval: string = '1min'): Promise<any> => {
    const response = await api.get('/market/gold/live', {
      params: { interval },
    });
    return response.data;
  },

  // New: Generic OHLCV history for Live charts (BTC/ETH via Binance, XAU via AlphaVantage)
  getOHLCV: async (
    symbol: string,
    timeframe: string = '1m',
    limit: number = 500
  ): Promise<any[]> => {
    const response = await api.get('/ohlcv', { params: { symbol, timeframe, limit } });
    // Normalize to PriceData
    const rows = response.data as { time: number; open: number; high: number; low: number; close: number }[];
    return rows.map((r) => ({ time: r.time, open: r.open, high: r.high, low: r.low, close: r.close }));
  },

  getIndicatorData: async (
    indicator: string,
    params: Record<string, any>
  ): Promise<any[]> => {
    const response = await api.get(`/indicators/${indicator}`, {
      params,
    });
    return response.data;
  },
};

export const tradingApi = {
executeTrade: async (trade: any): Promise<any> => {
    const response = await api.post('/trading/execute', trade);
    return response.data;
  },

  getTradeHistory: async (): Promise<any[]> => {
    const response = await api.get('/trading/history');
    return response.data;
  },

  getPortfolio: async (): Promise<any> => {
    const response = await api.get('/trading/portfolio');
    return response.data;
  },

  resetSimulation: async (): Promise<void> => {
    await api.post('/trading/reset');
  },
};

export const aiApi = {
  analyzeScenario: async (data: {
    priceData: any[];
    indicators: any[];
    currentPrice: number;
  }): Promise<any> => {
    const response = await api.post('/ai/analyze', data);
    return response.data;
  },

  getTradeRecommendation: async (
    priceData: any[],
    position: any
  ): Promise<any> => {
    const response = await api.post('/ai/recommend', {
      priceData,
      position,
    });
    return response.data;
  },

  generateTradingPlan: async (data: {
    current_price: number;
    user_capital?: number;
    risk_tolerance?: string;
    use_indicator_preferences?: boolean;
    price_data?: any[];
    indicators_data?: any;
  }): Promise<any> => {
    const response = await api.post('/ai/generate-plan', data);
    return response.data;
  },

  getPlanHistory: async (userId?: string, limit: number = 10): Promise<any[]> => {
    const response = await api.get('/ai/plans/history', {
      params: { user_id: userId, limit },
    });
    return response.data;
  },

  submitPlanFeedback: async (data: {
    plan_id: number;
    accepted: boolean;
    modified?: boolean;
    feedback?: string;
  }): Promise<any> => {
    const response = await api.post('/ai/plans/feedback', data);
    return response.data;
  },
};

export const newsApi = {
  getNewsFeed: async (limit: number = 50): Promise<any> => {
    const response = await api.get('/news/feed', {
      params: { limit },
    });
    return response.data;
  },

  getAlerts: async (limit: number = 50): Promise<any> => {
    const response = await api.get('/news/alerts', {
      params: { limit },
    });
    return response.data;
  },

  getEconomicCalendar: async (): Promise<any> => {
    const response = await api.get('/news/economic-calendar');
    return response.data;
  },

  clearOldAlerts: async (): Promise<void> => {
    await api.post('/news/alerts/clear');
  },
};

// New endpoints
export const accountApi = {
  getAccount: async (): Promise<any> => (await api.get('/account')).data,
  getPositions: async (): Promise<any[]> => (await api.get('/positions')).data,
}

export const performanceApi = {
  getEquityHistory: async (symbol = 'XAU/USD', timeframe = '1m', limit = 300): Promise<{ time: number; equity: number }[]> => (
    await api.get('/equity-history', { params: { symbol, timeframe, limit } })
  ).data,
  getPerformance: async (symbol = 'XAU/USD', timeframe = '1m', limit = 300): Promise<any> => (
    await api.get('/performance', { params: { symbol, timeframe, limit } })
  ).data,
}

export const statusApi = {
  getStatus: async (): Promise<any> => (await api.get('/status')).data,
}

export const settingsApi = {
  getModels: async (): Promise<any> => (await api.get('/settings/models')).data,
  putModels: async (patch: any): Promise<any> => (await api.put('/settings/models', patch)).data,
  getExchanges: async (): Promise<any> => (await api.get('/settings/exchanges')).data,
  putExchanges: async (patch: any): Promise<any> => (await api.put('/settings/exchanges', patch)).data,

  // Indicator Preferences
  getIndicatorPreferences: async (userId?: string, enabledOnly: boolean = false): Promise<any> => {
    const response = await api.get('/settings/indicators/preferences', {
      params: { user_id: userId, enabled_only: enabledOnly },
    });
    return response.data;
  },

  createIndicatorPreference: async (data: {
    indicator_name: string;
    enabled?: boolean;
    parameters?: any;
    priority?: number;
    notes?: string;
  }, userId?: string): Promise<any> => {
    const response = await api.post('/settings/indicators/preferences', data, {
      params: { user_id: userId },
    });
    return response.data;
  },

  updateIndicatorPreference: async (preferenceId: number, data: {
    enabled?: boolean;
    parameters?: any;
    priority?: number;
    notes?: string;
  }): Promise<any> => {
    const response = await api.put(`/settings/indicators/preferences/${preferenceId}`, data);
    return response.data;
  },

  deleteIndicatorPreference: async (preferenceId: number): Promise<void> => {
    await api.delete(`/settings/indicators/preferences/${preferenceId}`);
  },

  createBulkIndicatorPreferences: async (preferences: any[], userId?: string): Promise<any> => {
    const response = await api.post('/settings/indicators/preferences/bulk', preferences, {
      params: { user_id: userId },
    });
    return response.data;
  },
}

export const promptsApi = {
  list: async (): Promise<any[]> => (await api.get('/prompt-templates')).data,
  get: async (name: string): Promise<any> => (await api.get(`/prompt-templates/${encodeURIComponent(name)}`)).data,
}

export const decisionsApi = {
  getLatest: async (limit = 20): Promise<any[]> => (await api.get('/decisions/latest', { params: { limit } })).data,
}

export default api;
