import { getSettings, getConfig } from './configService';
import { RunTaskRequest, RunTaskApiResponse, Task } from '../types/task';

// 获取任务列表
export const getTasks = async (): Promise<Task[]> => {
  try {
    const config = await getConfig();
    const endpoint = config?.apiEndpoints?.getTasks;

    if (!endpoint) {
      throw new Error('获取任务列表的API端点未配置');
    }

    const settings = await getSettings();
    const serverUrl = settings.serverUrl || config?.serverUrl;

    if (!serverUrl) {
      throw new Error('服务器地址未配置');
    }

    const url = `${serverUrl.replace(/\/$/, '')}${endpoint}`;
    console.log('获取任务列表:', url);

    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const result = await response.json();
    if (result.code !== 200) {
      throw new Error(`API 错误: ${result.message}`);
    }

    return result.data;
  } catch (error) {
    console.error('获取任务列表失败:', error);
    throw error;
  }
};

// 获取任务详情
export const getTaskDetail = async (taskId: string): Promise<Task> => {
  try {
    const config = await getConfig();
    let endpoint = config?.apiEndpoints?.getTaskDetail;

    if (!endpoint) {
      throw new Error('获取任务详情的API端点未配置');
    }
    endpoint = endpoint.replace('{taskId}', taskId);

    const settings = await getSettings();
    const serverUrl = settings.serverUrl || config?.serverUrl;

    if (!serverUrl) {
      throw new Error('服务器地址未配置');
    }

    const url = `${serverUrl.replace(/\/$/, '')}${endpoint}`;
    console.log('获取任务详情:', url);

    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const result = await response.json();
    if (result.code !== 200) {
      throw new Error(`API 错误: ${result.message}`);
    }

    return result.data;
  } catch (error) {
    console.error(`获取任务详情失败 (ID: ${taskId}):`, error);
    throw error;
  }
};

// 运行任务
export const runTask = async (
  taskData: RunTaskRequest,
): Promise<RunTaskApiResponse> => {
  try {
    const config = await getConfig();
    const endpoint = config?.apiEndpoints?.runTask;

    if (!endpoint) {
      throw new Error('运行任务的API端点未配置');
    }

    const settings = await getSettings();
    const serverUrl = settings.serverUrl || config?.serverUrl;

    if (!serverUrl) {
      throw new Error('服务器地址未配置');
    }

    const url = `${serverUrl.replace(/\/$/, '')}${endpoint}`;
    console.log('运行任务请求:', url, JSON.stringify(taskData, null, 2));

    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(taskData),
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`HTTP ${response.status}: ${errorText}`);
    }

    const result: RunTaskApiResponse = await response.json();
    console.log('运行任务响应:', result);

    if (result.code !== 200) {
      throw new Error(`API 错误: ${result.message}`);
    }

    return result;
  } catch (error) {
    console.error('运行任务失败:', error);
    throw error;
  }
};
