import { getBackendBaseURL } from "@/core/config";

import type { Skill } from "./type";

export async function loadSkills() {
  const skills = await fetch(`${getBackendBaseURL()}/api/skills`);
  const json = await skills.json();
  return json.skills as Skill[];
}

export async function enableSkill(skillName: string, enabled: boolean) {
  const response = await fetch(
    `${getBackendBaseURL()}/api/skills/${skillName}`,
    {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        enabled,
      }),
    },
  );
  return response.json();
}

export interface InstallSkillRequest {
  thread_id: string;
  path: string;
}

export interface InstallSkillResponse {
  success: boolean;
  skill_name: string;
  message: string;
}

// [移植自 main 分支 ef9a071] 添加 skill yaml 解析和远程 skill 初始化 API
export interface MaterializeSkillYamlRequest {
  thread_id: string;
  path: string;
  target_dir?: string;
  clear_target?: boolean;
}

export interface MaterializeSkillYamlResponse {
  success: boolean;
  target_dir: string;
  created_directories: number;
  created_files: number;
  message: string;
}

export interface BootstrapRemoteSkillRequest {
  thread_id: string;
  content_ids: number[];
  language_type?: number;
  target_dir?: string;
  clear_target?: boolean;
}

export interface BootstrapRemoteSkillResponse {
  success: boolean;
  target_dir: string;
  content_ids: number[];
  created_directories: number;
  created_files: number;
  sandbox_id: string | null;
  message: string;
}

export async function installSkill(
  request: InstallSkillRequest,
): Promise<InstallSkillResponse> {
  const response = await fetch(`${getBackendBaseURL()}/api/skills/install`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(request),
  });

  if (!response.ok) {
    // Handle HTTP error responses (4xx, 5xx)
    const errorData = await response.json().catch(() => ({}));
    const errorMessage =
      errorData.detail ?? `HTTP ${response.status}: ${response.statusText}`;
    return {
      success: false,
      skill_name: "",
      message: errorMessage,
    };
  }

  return response.json();
}

// [移植自 main 分支 ef9a071] 解析 skill.yaml 文件并创建目录结构
export async function materializeSkillYaml(
  request: MaterializeSkillYamlRequest,
): Promise<MaterializeSkillYamlResponse> {
  console.log("[skills/api] ========== materializeSkillYaml START ==========");
  console.log("[skills/api] request:", JSON.stringify(request, null, 2));
  console.log(
    "[skills/api] API URL:",
    `${getBackendBaseURL()}/api/skills/materialize-yaml`,
  );

  const response = await fetch(
    `${getBackendBaseURL()}/api/skills/materialize-yaml`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(request),
    },
  );

  console.log(
    "[skills/api] response status:",
    response.status,
    response.statusText,
  );

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    const errorMessage =
      errorData.detail ?? `HTTP ${response.status}: ${response.statusText}`;
    console.error("[skills/api] materializeSkillYaml FAILED:", errorMessage);
    console.error("[skills/api] error data:", errorData);
    throw new Error(errorMessage);
  }

  const result = await response.json();
  console.log("[skills/api] materializeSkillYaml SUCCESS:", result);
  console.log("[skills/api] ========== materializeSkillYaml END ==========");
  return result;
}

// [移植自 main 分支 ef9a071] 从远程平台获取 skill 并初始化
export async function bootstrapRemoteSkill(
  request: BootstrapRemoteSkillRequest,
): Promise<BootstrapRemoteSkillResponse> {
  const response = await fetch(
    `${getBackendBaseURL()}/api/skills/bootstrap-remote`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(request),
    },
  );

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    const errorMessage =
      errorData.detail ?? `HTTP ${response.status}: ${response.statusText}`;
    throw new Error(errorMessage);
  }

  return response.json();
}
