import { fetchWithAuth } from "./client";

// ── 类型定义 ────────────────────────────────────────────────────────────────────

export interface Agent {
  id: string;
  name: string;
  type: string;
  status: "idle" | "running" | "error" | "disabled";
  description?: string;
  config?: Record<string, unknown>;
  created_at: string;
  updated_at: string;
}

export interface AgentRunLog {
  id: string;
  agent_id: string;
  status: "success" | "failed" | "running";
  started_at: string;
  finished_at?: string;
  message?: string;
}

// 执行记录相关类型
export interface AgentTask {
  id: string;
  agent_id: string;
  task_type: string;
  status: "pending" | "running" | "completed" | "failed" | "cancelled";
  priority: number;
  input_data: Record<string, unknown>;
  output_data?: Record<string, unknown>;
  error_message?: string;
  started_at?: string;
  completed_at?: string;
  created_at: string;
}

export interface TaskLog {
  id: string;
  task_id: string;
  agent_id: string;
  log_level: "DEBUG" | "INFO" | "WARNING" | "ERROR";
  message: string;
  metadata?: Record<string, unknown>;
  created_at: string;
}

export interface ExecutionStats {
  total: number;
  success_count: number;
  failed_count: number;
  running_count: number;
  success_rate: number;
  avg_duration_seconds: number;
}

// ── API ────────────────────────────────────────────────────────────────────────

export const agentsApi = {
  list: (token: string) =>
    fetchWithAuth("/api/v1/agents/", {}, token) as Promise<Agent[]>,
  get: (token: string, agentId: string) =>
    fetchWithAuth(`/api/v1/agents/${agentId}`, {}, token) as Promise<Agent>,
  updateConfig: (token: string, agentId: string, config: Record<string, unknown>) =>
    fetchWithAuth(
      `/api/v1/agents/${agentId}/config`,
      { method: "PUT", body: JSON.stringify(config) },
      token
    ) as Promise<Agent>,
  enable: (token: string, agentId: string) =>
    fetchWithAuth(
      `/api/v1/agents/${agentId}/enable`,
      { method: "POST" },
      token
    ) as Promise<Agent>,
  disable: (token: string, agentId: string) =>
    fetchWithAuth(
      `/api/v1/agents/${agentId}/disable`,
      { method: "POST" },
      token
    ) as Promise<Agent>,
  getLogs: (token: string, agentId: string) =>
    fetchWithAuth(
      `/api/v1/agents/${agentId}/logs`,
      {},
      token
    ) as Promise<AgentRunLog[]>,
  // 执行记录相关
  listTasks: (token: string, params?: {
    status?: string;
    task_type?: string;
    agent_name?: string;
    skip?: number;
    limit?: number;
  }) => {
    const searchParams = new URLSearchParams();
    if (params?.status) searchParams.set("status", params.status);
    if (params?.task_type) searchParams.set("task_type", params.task_type);
    if (params?.agent_name) searchParams.set("agent_name", params.agent_name);
    if (params?.skip !== undefined) searchParams.set("skip", String(params.skip));
    if (params?.limit !== undefined) searchParams.set("limit", String(params.limit));
    const query = searchParams.toString();
    return fetchWithAuth(
      `/api/v1/agents/tasks/${query ? `?${query}` : ""}`,
      {},
      token
    ) as Promise<{ items: AgentTask[]; total: number }>;
  },
  getTask: (token: string, taskId: string) =>
    fetchWithAuth(`/api/v1/agents/tasks/${taskId}`, {}, token) as Promise<AgentTask>,
  getTaskLogs: (token: string, taskId: string, params?: { skip?: number; limit?: number }) => {
    const searchParams = new URLSearchParams();
    if (params?.skip !== undefined) searchParams.set("skip", String(params.skip));
    if (params?.limit !== undefined) searchParams.set("limit", String(params.limit));
    const query = searchParams.toString();
    return fetchWithAuth(
      `/api/v1/agents/tasks/${taskId}/logs${query ? `?${query}` : ""}`,
      {},
      token
    ) as Promise<{ items: TaskLog[]; total: number }>;
  },
  cancelTask: (token: string, taskId: string) =>
    fetchWithAuth(
      `/api/v1/agents/tasks/${taskId}/cancel`,
      { method: "POST" },
      token
    ) as Promise<{ task_id: string; status: string; message: string }>,
};
