import { api } from "./client";

export type AgentSkillEntry = {
  skillId: string;
  source: "managed" | "native";
  installedAt: number;
};

export type SkillListItem = {
  id: string;
  name: string;
  description: string | null;
  sourceId: string;
  category: string | null;
  activeVersionId: string | null;
  removedAt: number | null;
  averageRating: number | null;
  ratingCount: number | null;
  taskCount: number | null;
  avgCostUsd: number | null;
  lastUsedAt: number | null;
};

export type PersonalRating = {
  id: string;
  skillId: string;
  versionId: string | null;
  stars: number;
  note: string | null;
  createdAt: number;
  updatedAt: number;
};

export type SkillVersion = {
  id: string;
  skillId: string;
  version: string;
  fetchedAt: number;
  cacheDir: string | null;
};

function skillPath(skillId: string): string {
  const [sourceId, ...slugParts] = skillId.split("/");
  const slug = slugParts.join("/");
  return `/skill-registry/skills/${sourceId}/${slug}`;
}

export const skillRegistryApi = {
  list: (opts?: { includeRemoved?: boolean }) =>
    api.get<SkillListItem[]>(
      `/skill-registry/skills${opts?.includeRemoved ? "?includeRemoved=true" : ""}`,
    ),
  getById: (skillId: string) =>
    api.get<SkillListItem>(skillPath(skillId)),
  getVersions: (skillId: string) =>
    api.get<SkillVersion[]>(`${skillPath(skillId)}/versions`),
  fetch: () =>
    api.post<{ fetched: number; errors: string[] }>("/skill-registry/fetch", {}),
  install: (skillId: string, agentId: string) =>
    api.post(`${skillPath(skillId)}/install`, { agentId }),
  uninstall: (skillId: string, agentId: string) =>
    api.delete(`${skillPath(skillId)}?agentId=${encodeURIComponent(agentId)}`),
  rollback: (skillId: string, versionId: string, agentId: string) =>
    api.post(`${skillPath(skillId)}/rollback`, { versionId, agentId }),
  remove: (skillId: string) =>
    api.delete(skillPath(skillId)),
  getRatings: (skillId: string) =>
    api.get<PersonalRating[]>(`${skillPath(skillId)}/ratings`),
  addRating: (skillId: string, body: { stars: number; versionId?: string; note?: string }) =>
    api.post(`${skillPath(skillId)}/ratings`, body),
};
