import axios from 'axios'

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

// Project APIs
export const projectApi = {
  list: (params?: { topology?: string; skip?: number; limit?: number }) =>
    api.get('/projects', { params }),
  get: (id: number) => api.get(`/projects/${id}`),
  create: (data: any) => api.post('/projects', data),
  update: (id: number, data: any) => api.put(`/projects/${id}`, data),
  delete: (id: number) => api.delete(`/projects/${id}`)
}

// Plan APIs
export const planApi = {
  list: (params?: { project_id?: number; skip?: number; limit?: number }) =>
    api.get('/plans', { params }),
  get: (id: number) => api.get(`/plans/${id}`),
  create: (data: any) => api.post('/plans', data),
  update: (id: number, data: any) => api.put(`/plans/${id}`, data),
  delete: (id: number) => api.delete(`/plans/${id}`),
  download: (id: number) => api.get(`/plans/${id}/download`),
  downloadByUuid: (uuid: string) => api.get(`/plans/by-plan-id/${uuid}/download`),
  uploadResults: (id: number, file: File) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post(`/plans/${id}/upload-results`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  getResults: (id: number) => api.get(`/plans/${id}/results`)
}

// Experience APIs
export const experienceApi = {
  list: (params?: { topology?: string; tag?: string; skip?: number; limit?: number }) =>
    api.get('/experience', { params }),
  get: (id: number) => api.get(`/experience/${id}`),
  create: (data: any) => api.post('/experience', data),
  update: (id: number, data: any) => api.put(`/experience/${id}`, data),
  delete: (id: number) => api.delete(`/experience/${id}`),
  importFromPlan: (planId: number, data?: { tags?: string[]; rating?: number; auto_conclusion?: boolean }) =>
    api.post(`/experience/from-plan/${planId}`, data || {}),
  importFromResult: (resultId: number, data?: { conclusion?: string; tags?: string[]; rating?: number }) =>
    api.post(`/experience/from-result/${resultId}`, data || {})
}

// Generation / Rule Engine APIs
export const generationApi = {
  listScanParameters: (category?: string) =>
    api.get('/scan-parameters', { params: category ? { category } : {} }),
  recommendRange: (parameterName: string, boundaryConditions: Record<string, any>) =>
    api.post('/recommend-range', { parameter_name: parameterName, boundary_conditions: boundaryConditions }),
  generatePlan: (data: { boundary_conditions: Record<string, any>; parameter_names?: string[]; model_path?: string }) =>
    api.post('/generate-plan', data),
  generatePlanForProject: (projectId: number, data: { boundary_conditions?: Record<string, any>; parameter_names?: string[]; model_path?: string }) =>
    api.post(`/projects/${projectId}/generate-plan`, data)
}

// Analytics APIs
export const analyticsApi = {
  listMetrics: () => api.get('/analytics/metrics'),
  experienceStats: (topology?: string) =>
    api.get('/analytics/experience/stats', { params: topology ? { topology } : {} }),
  experienceSimilar: (params: Record<string, number>, topology?: string, topK = 5, tolerance = 0.3) =>
    api.post('/analytics/experience/similar', { params }, { params: { topology, top_k: topK, tolerance } }),
  planTrend: (planId: number, paramKey: string, metricKey: string) =>
    api.get(`/analytics/plans/${planId}/trend`, { params: { param_key: paramKey, metric_key: metricKey } }),
  planPareto: (planId: number, xMetric = 'total_losses_w', yMetric = 'efficiency_pct') =>
    api.get(`/analytics/plans/${planId}/pareto`, { params: { x_metric: xMetric, y_metric: yMetric } }),
  planSensitivity: (planId: number, metricKey: string) =>
    api.get(`/analytics/plans/${planId}/sensitivity`, { params: { metric_key: metricKey } }),
  projectOverview: (projectId: number) =>
    api.get(`/analytics/projects/${projectId}/overview`)
}

export default api
