/**
 * Agent API client
 * Handles agent-related API interactions
 */

import { apiGet, apiPost, apiPatch, apiDelete } from "./client";

export interface AgentStatus {
  id: string;
  name: string;
  displayName: string;
  role: string;
  isActive: boolean;
  containerStatus?: "running" | "stopped" | "unknown";
}

export interface UserAgent {
  id: string;
  userId: string;
  templateId: string | null;
  name: string;
  displayName: string;
  role: string;
  personality: string;
  primaryModel: string | null;
  fallbackModels: string[];
  toolPermissions: string[];
  discordChannel: string | null;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface CreateUserAgentRequest {
  templateId?: string;
  name: string;
  displayName: string;
  role: string;
  personality: string;
  primaryModel?: string;
  fallbackModels?: string[];
  toolPermissions?: string[];
  discordChannel?: string;
  isActive?: boolean;
}

export interface UpdateUserAgentRequest {
  name?: string;
  displayName?: string;
  role?: string;
  personality?: string;
  primaryModel?: string;
  fallbackModels?: string[];
  toolPermissions?: string[];
  discordChannel?: string;
  isActive?: boolean;
}

export interface UpdateUserAgentRequest {
  name?: string;
  displayName?: string;
  role?: string;
  personality?: string;
  primaryModel?: string;
  fallbackModels?: string[];
  toolPermissions?: string[];
  discordChannel?: string;
  isActive?: boolean;
}

/**
 * Get all user's agents
 */
export async function getAgents(): Promise<UserAgent[]> {
  return apiGet<UserAgent[]>("/api/agents");
}

/**
 * Get all agent statuses
 */
export async function getAgentStatuses(): Promise<AgentStatus[]> {
  return apiGet<AgentStatus[]>("/api/agents/status");
}

/**
 * Get a single agent by ID
 */
export async function getAgent(id: string): Promise<UserAgent> {
  return apiGet<UserAgent>(`/api/agents/${id}`);
}

/**
 * Get a single agent's status
 */
export async function getAgentStatus(id: string): Promise<AgentStatus> {
  return apiGet<AgentStatus>(`/api/agents/${id}/status`);
}

/**
 * Create a new custom agent
 */
export async function createAgent(data: CreateUserAgentRequest): Promise<UserAgent> {
  return apiPost<UserAgent>("/api/agents", data);
}

/**
 * Create an agent from a template
 */
export async function createAgentFromTemplate(templateId: string): Promise<UserAgent> {
  return apiPost<UserAgent>(`/api/agents/from-template/${templateId}`, {});
}

/**
 * Update an agent
 */
export async function updateAgent(id: string, data: UpdateUserAgentRequest): Promise<UserAgent> {
  return apiPatch<UserAgent>(`/api/agents/${id}`, data);
}

/**
 * Delete an agent
 */
export async function deleteAgent(id: string): Promise<void> {
  await apiDelete(`/api/agents/${id}`);
}
