// 基础API请求函数
const apiRequest = async (endpoint, options = {}) => {
  const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
  const url = `${baseURL}${endpoint}`;
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
    },
    ...options,
  };

  // 添加认证token
  const token = localStorage.getItem('authToken');
  if (token) {
    defaultOptions.headers.Authorization = `Bearer ${token}`;
  }

  try {
    const response = await fetch(url, defaultOptions);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('API request failed:', error);
    throw error;
  }
};

// 文件上传功能
export const UploadFile = async ({ file, type = 'material' }) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('type', type);
  
  const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
  const url = `${baseURL}/api/upload`;
  
  const token = localStorage.getItem('authToken');
  const headers = {};
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const response = await fetch(url, {
    method: 'POST',
    headers,
    body: formData,
  });

  if (!response.ok) {
    throw new Error(`Upload failed: ${response.status}`);
  }

  return await response.json();
};

// LLM调用功能
export const InvokeLLM = async ({ prompt, model = 'gpt-3.5-turbo', temperature = 0.7 }) => {
  return await apiRequest('/api/llm/invoke', {
    method: 'POST',
    body: JSON.stringify({
      prompt,
      model,
      temperature,
    }),
  });
};

// AI换脸功能
export const AISwap = async ({ sourceImage, targetImage, options = {} }) => {
  const formData = new FormData();
  formData.append('source_image', sourceImage);
  formData.append('target_image', targetImage);
  
  // 添加选项参数
  Object.keys(options).forEach(key => {
    formData.append(key, options[key]);
  });
  
  const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
  const url = `${baseURL}/api/ai-swap`;
  
  const token = localStorage.getItem('authToken');
  const headers = {};
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const response = await fetch(url, {
    method: 'POST',
    headers,
    body: formData,
  });

  if (!response.ok) {
    throw new Error(`AI Swap failed: ${response.status}`);
  }

  return await response.json();
};

// 获取AI换脸任务状态
export const GetAISwapStatus = async (taskId) => {
  return await apiRequest(`/api/ai-swap/status/${taskId}`);
};

// 获取AI换脸结果
export const GetAISwapResult = async (taskId) => {
  return await apiRequest(`/api/ai-swap/result/${taskId}`);
};

// 文本生成功能
export const GenerateText = async ({ template, params = {} }) => {
  return await apiRequest('/api/text/generate', {
    method: 'POST',
    body: JSON.stringify({
      template,
      params,
    }),
  });
};

// 图像生成功能
export const GenerateImage = async ({ prompt, style = 'fashion', size = '1024x1024' }) => {
  return await apiRequest('/api/image/generate', {
    method: 'POST',
    body: JSON.stringify({
      prompt,
      style,
      size,
    }),
  });
};

// 获取生成任务状态
export const GetGenerationStatus = async (taskId) => {
  return await apiRequest(`/api/generation/status/${taskId}`);
};

// 获取生成结果
export const GetGenerationResult = async (taskId) => {
  return await apiRequest(`/api/generation/result/${taskId}`);
}; 