import "@johnlindquist/kit";
const gitHubPAT = await env("PGSM_GITHUB_PAT");
const gitHubOrg = await env("PGSM_GITHUB_ORG");
const gitHubRepo = await env("PGSM_REPO_NAME");
const branch =  await env("PGSM_BRANCH");
const rawContentBaseUri = `https://raw.githubusercontent.com/${gitHubOrg}/${gitHubRepo}/${branch}`;
const apiCall = async (details) => {
  const { url, httpMethod, body, headers, authType } = details;
  return await get(url, {
    method: httpMethod,
    body,
    headers: {
      ...headers,
      "Accept-Encoding": "gzip, deflate, br",
      Authorization: `${authType} ${gitHubPAT}`,
    },
  })
    .then((respData) => respData.data)
    .catch((error) => {
      console.error("Error:", error);
    });
};
const rawFiles = {};
const getRawFile = async (fileName) => {
  if (rawFiles[fileName]) {
    return rawFiles[fileName];
  }
  const url = `${rawContentBaseUri}/${fileName}`;
  const rawFileHeaders = {
    Accept: "application/vnd.github.v3.raw",
  };
  rawFiles[fileName] = await apiCall({
    url,
    httpMethod,
    headers: rawFileHeaders,
    authType: "Token",
  });
  return rawFiles[fileName];
};
const getValueFromComment = (comments, key) => {
  const comment = comments.find((comment) => comment.includes(key));
  if (!comment) return null;
  return comment.match(new RegExp(`${key}: (.*)`))[1];
}
const httpMethod = "GET";
const scriptsUrl = `https://api.github.com/repos/${gitHubOrg}/${gitHubRepo}/git/trees/${branch}?recursive=1`;
const rawScriptsHeaders = {
  Accept: "*/*",
};
const rawScriptsResponse = await apiCall({
  url: scriptsUrl,
  httpMethod,
  headers: rawScriptsHeaders,
  authType: "Bearer",
});
const scriptFiles = rawScriptsResponse.tree
  .filter(
    (f) =>
      f.path.indexOf("src/") === 0 &&
      f.path.indexOf(".test.js") === -1 &&
      f.path.indexOf(".md") === -1
  )
  .map((f) => ({
    path: f.path,
    scriptName: f.path.replace("src/", ""),
  }));
for (const script of scriptFiles) {
  const rawFile = await getRawFile(script.path);
  const comments = rawFile.match(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm);
  script.name = getValueFromComment(comments, "Name");
  script.menu = getValueFromComment(comments, "Menu");
  script.description = getValueFromComment(comments, "Description");
  script.author = getValueFromComment(comments, "Author");
}
const selectedScript = await arg(
  `Select Private Script:`,
  scriptFiles.map(({ name, menu, description, scriptName, path }) => {
    return {
      name: name || menu || scriptName,
      description: description || scriptName,
      value: { scriptName, path },
      preview: async () => {
        const displayName = name || menu || scriptName;
        const displayDescription = description || scriptName;
        return md(`# ${displayName}
${displayDescription}`);
      },
    };
  })
);
const scriptFilePath = `${await env("KENV")}/scripts/${
  selectedScript.scriptName
}`;
const selectedScriptRawFile = await getRawFile(selectedScript.path);
await outputFile(scriptFilePath, selectedScriptRawFile);