import { createCoreAPIClient } from "../../coreClient";
import { CHATBOT_API_ROUTES } from "../constants/api_constants";

const coreClient = createCoreAPIClient();

export async function updateAgent(
  id: string,
  payload: {
    agent_name: string;
    prompt_id: string;
    embed_model: string;
    language_model: string;
    embed_dimension: number;
    is_active: boolean;
    csv_urls?: string[];
    category_key: string;
    tuning_parameters?: Record<string, number>;
  },
  options?: RequestInit,
) {
  return coreClient<any>(`${CHATBOT_API_ROUTES.AGENTS}/${id}`, {
    method: "PUT",
    body: JSON.stringify(payload),
    ...options,
  });
}

export async function createAgent(payload: {
  agent_name: string;
  prompt_id: string;
  embed_model: string;
  language_model: string;
  embed_dimension: number;
  csv_urls?: string[] | null;
  category_key: string;
  tuning_parameters: Record<string, number>;
}) {
  return coreClient<any>(CHATBOT_API_ROUTES.AGENTS, {
    method: "POST",
    body: JSON.stringify(payload),
    cache: "no-store",
  });
}

export async function deleteAgent(id: string) {
  return coreClient<any>(`${CHATBOT_API_ROUTES.AGENTS}/${id}`, {
    method: "DELETE",
    cache: "no-store",
  });
}

export async function testAgent(payload: {
  message: string;
  agent_id?: string;
}) {
  return coreClient<any>(`${CHATBOT_API_ROUTES.AGENTS}/test`, {
    method: "POST",
    body: JSON.stringify(payload),
    cache: "no-store",
  });
}

export async function getGlobalAgent(options?: RequestInit) {
  return coreClient<any>(CHATBOT_API_ROUTES.GLOBAL_AGENT, {
    method: "GET",
    cache: "no-store",
    ...options,
  });
}

export async function updateGlobalAgent(payload: {
  prompt_id?: string;
  csv_urls?: string[] | null;
  tuning_parameters?: Record<string, number>;
  language_model?: string;
  embed_model?: string;
  embed_dimension?: number;
}) {
  return coreClient<any>(CHATBOT_API_ROUTES.GLOBAL_AGENT, {
    method: "PUT",
    body: JSON.stringify(payload),
    cache: "no-store",
  });
}

export async function toggleAgentActive(id: string) {
  return coreClient<any>(CHATBOT_API_ROUTES.AGENT_TOGGLE(id), {
    method: "PATCH",
    body: JSON.stringify({}),
    cache: "no-store",
  });
}

export async function makeAgentGlobal(id: string) {
  return coreClient<any>(CHATBOT_API_ROUTES.AGENT_MAKE_GLOBAL(id), {
    method: "PATCH",
    body: JSON.stringify({}),
    cache: "no-store",
  });
}

export async function uploadFiles(
  files: File[],
): Promise<{ success: boolean; urls: string[] }> {
  const formData = new FormData();
  files.forEach((file) => formData.append("files", file));

  const isBrowser = typeof window !== "undefined";
  const baseUrl = isBrowser
    ? "/api/proxy"
    : (typeof import.meta !== "undefined" && import.meta.env?.VITE_CORE_API) ||
      process.env.VITE_CORE_API ||
      process.env.CORE_API_URL ||
      "";

  const response = await fetch(`${baseUrl}${CHATBOT_API_ROUTES.UPLOAD}`, {
    method: "POST",
    body: formData,
    credentials: "include",
  });

  if (!response.ok) {
    let message = "Upload failed";
    try {
      const json = await response.json();
      message = json?.detail || json?.message || message;
    } catch {}
    throw new Error(message);
  }

  return response.json();
}
