import { fetchJson } from "./client";
import type {
  ApiResult,
  GateDiagnosticsResponse,
  SkillFileResponse,
  SkillTreeResponse,
  SkillUploadResponse,
  SkillsResponse,
  WebPerformanceSummaryResponse,
  WebPerformanceWindow
} from "@/types";

export interface SkillUploadFileInput {
  relativePath: string;
  contentText: string;
}

export const systemAPI = {
  gateDiagnostics: (): Promise<ApiResult<GateDiagnosticsResponse>> => fetchJson("/v1/diagnostics/gate", { timeoutMs: 12000, timeoutName: "gate diagnostics" }),
  performanceSummary: (window: WebPerformanceWindow = "15m"): Promise<ApiResult<WebPerformanceSummaryResponse>> => fetchJson(`/v1/web-performance/summary?window=${encodeURIComponent(window)}`, { timeoutMs: 12000, timeoutName: "web performance summary" }),
  skills: (): Promise<ApiResult<SkillsResponse>> => fetchJson("/v1/skills", { timeoutMs: 12000, timeoutName: "skills" }),
  uploadSkill: (name: string, files: SkillUploadFileInput[]): Promise<ApiResult<SkillUploadResponse>> => fetchJson("/v1/skills/uploads", { method: "POST", body: JSON.stringify({ name: name.trim() || undefined, files }), timeoutMs: 30000, timeoutName: "skill upload" }),
  skillTree: (skillId: string): Promise<ApiResult<SkillTreeResponse>> => fetchJson(`/v1/skills/${encodeURIComponent(skillId)}/tree`, { timeoutMs: 12000, timeoutName: "skill tree" }),
  skillFile: (skillId: string, path = "SKILL.md"): Promise<ApiResult<SkillFileResponse>> => fetchJson(`/v1/skills/${encodeURIComponent(skillId)}/files?path=${encodeURIComponent(path)}`, { timeoutMs: 12000, timeoutName: "skill file" })
};
