import { API_BASE_URL } from "@/lib/config";

const BASE_URL = API_BASE_URL;

// --- Types ---

export type MemoryCategory = "preference" | "context" | "pattern" | "fact";

export type MemoryItem = {
  id: string;
  content: string;
  category: MemoryCategory;
  is_pinned: boolean;
  created_at: string;
  updated_at: string;
};

export type MemorySettings = {
  enabled: boolean;
  max_memories: number;
  max_injection_tokens: number;
  compression_threshold: number;
};

// --- Helpers ---

async function jsonOrThrow<T>(res: Response, errorMsg: string): Promise<T> {
  const ct = res.headers.get("content-type") || "";
  if (!res.ok || !ct.includes("application/json")) {
    throw new Error(errorMsg);
  }
  return res.json();
}

// --- API ---

export async function fetchMemories(): Promise<MemoryItem[]> {
  const res = await fetch(`${BASE_URL}/api/memory/`);
  return jsonOrThrow(res, "Failed to fetch memories");
}

export async function createMemory(content: string, category: MemoryCategory = "fact"): Promise<MemoryItem> {
  const res = await fetch(`${BASE_URL}/api/memory/`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ content, category }),
  });
  return jsonOrThrow(res, "Failed to create memory");
}

export async function updateMemory(id: string, updates: Partial<Pick<MemoryItem, "content" | "category">>): Promise<MemoryItem> {
  const res = await fetch(`${BASE_URL}/api/memory/${id}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(updates),
  });
  return jsonOrThrow(res, "Failed to update memory");
}

export async function deleteMemory(id: string): Promise<void> {
  const res = await fetch(`${BASE_URL}/api/memory/${id}`, {
    method: "DELETE",
  });
  if (!res.ok) throw new Error("Failed to delete memory");
}

export async function toggleMemoryPin(id: string): Promise<MemoryItem> {
  const res = await fetch(`${BASE_URL}/api/memory/${id}/pin`, { method: "PATCH" });
  return jsonOrThrow(res, "Failed to toggle pin");
}

export async function clearAllMemories(): Promise<{ deleted: number }> {
  const res = await fetch(`${BASE_URL}/api/memory/`, {
    method: "DELETE",
  });
  return jsonOrThrow(res, "Failed to clear memories");
}

export async function fetchMemorySettings(): Promise<MemorySettings> {
  const res = await fetch(`${BASE_URL}/api/settings/memory`);
  return jsonOrThrow(res, "Failed to fetch memory settings");
}

export async function updateMemorySettings(updates: Partial<MemorySettings>): Promise<MemorySettings> {
  const res = await fetch(`${BASE_URL}/api/settings/memory`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(updates),
  });
  return jsonOrThrow(res, "Failed to update memory settings");
}
