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

const BASE_URL = API_BASE_URL;

// --- Types ---

export type SkillInfo = {
  name: string;
  description: string;
  path: string;
  scripts: string[];
  references: string[];
  enabled: boolean;
  license: string | null;
  compatibility: string | null;
  metadata: Record<string, unknown> | null;
};

export type SkillDetail = SkillInfo & {
  content: string;
};

export type CreateSkillRequest = {
  name: string;
  description: string;
  instructions?: string;
};

// --- API Functions ---

export async function fetchSkills(): Promise<SkillInfo[]> {
  const res = await fetch(`${BASE_URL}/api/skills/`);
  if (!res.ok) throw new Error("Failed to fetch skills");
  return res.json();
}

export async function fetchSkillDetail(name: string): Promise<SkillDetail> {
  const res = await fetch(`${BASE_URL}/api/skills/${encodeURIComponent(name)}`);
  if (!res.ok) throw new Error("Failed to fetch skill detail");
  return res.json();
}

export async function createSkill(req: CreateSkillRequest): Promise<SkillInfo> {
  const res = await fetch(`${BASE_URL}/api/skills/`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(req),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to create skill");
  }
  return res.json();
}

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

export async function updateSkill(
  name: string,
  updates: { enabled?: boolean; description?: string; instructions?: string }
): Promise<SkillInfo> {
  const res = await fetch(`${BASE_URL}/api/skills/${encodeURIComponent(name)}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(updates),
  });
  if (!res.ok) throw new Error("Failed to update skill");
  return res.json();
}

export async function reloadSkills(): Promise<{ status: string; count: number }> {
  const res = await fetch(`${BASE_URL}/api/skills/reload`, { method: "POST" });
  if (!res.ok) throw new Error("Failed to reload skills");
  return res.json();
}

export async function uploadSkillZip(file: File): Promise<SkillInfo> {
  const formData = new FormData();
  formData.append("file", file);
  const res = await fetch(`${BASE_URL}/api/skills/upload`, {
    method: "POST",
    body: formData,
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to upload skill zip");
  }
  return res.json();
}

export async function importSkillFromPath(path: string): Promise<SkillInfo> {
  const res = await fetch(`${BASE_URL}/api/skills/import`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ path }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Failed to import skill from path");
  }
  return res.json();
}
