import { promises as fs } from "fs";
import path from "path";
import { config } from "../config.js";
import type { AnythingLLMUploadMetadata, AnythingLLMUploadResponse } from "./anythingllm.types.js";

function baseHeaders(): Record<string, string> {
  return {
    Authorization: `Bearer ${config.ANYTHINGLLM_API_KEY}`
  };
}

async function parseJsonResponse<T>(response: Response, label: string): Promise<T> {
  const contentType = response.headers.get("content-type") ?? "";
  if (!contentType.includes("application/json")) {
    const text = await response.text();
    throw new Error(`${label} beklenmeyen yanit: ${response.status} ${text.slice(0, 200)}`);
  }
  return (await response.json()) as T;
}

export async function uploadDocument(filePath: string, metadata: AnythingLLMUploadMetadata): Promise<AnythingLLMUploadResponse> {
  const form = new FormData();
  const fileBuffer = await fs.readFile(filePath);
  const fileBlob = new Blob([fileBuffer], { type: "text/markdown" });
  form.append("file", fileBlob, path.basename(filePath));
  form.append("addToWorkspaces", config.ANYTHINGLLM_WORKSPACE_SLUG);
  form.append("metadata", JSON.stringify(metadata));

  const response = await fetch(`${config.ANYTHINGLLM_ROOT_API_URL}/v1/document/upload`, {
    method: "POST",
    headers: {
      ...baseHeaders()
    },
    body: form
  });

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

  return await parseJsonResponse<AnythingLLMUploadResponse>(response, "Upload");
}

export async function updateEmbeddings(adds: string[], deletes: string[]): Promise<void> {
  const response = await fetch(
    `${config.ANYTHINGLLM_ROOT_API_URL}/v1/workspace/${config.ANYTHINGLLM_WORKSPACE_SLUG}/update-embeddings`,
    {
      method: "POST",
      headers: {
        ...baseHeaders(),
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ adds, deletes })
    }
  );

  if (!response.ok) {
    const text = await response.text();
    throw new Error(`Embeddings guncelleme basarisiz: ${response.status} ${text}`);
  }
  await parseJsonResponse(response, "Embeddings guncelleme");
}

export async function removeDocuments(locations: string[]): Promise<void> {
  const response = await fetch(`${config.ANYTHINGLLM_ROOT_API_URL}/v1/system/remove-documents`, {
    method: "DELETE",
    headers: {
      ...baseHeaders(),
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ names: locations })
  });

  if (!response.ok) {
    const text = await response.text();
    throw new Error(`Dokuman temizleme basarisiz: ${response.status} ${text}`);
  }
  await parseJsonResponse(response, "Dokuman temizleme");
}
