import { exists } from "jsr:@std/fs";

/**
 * Return the path to Eve's configuration directory and ensures its existence.
 *
 * On macOS, the directory is located at "$HOME/Library/Application Support/eve/arx/Eve".
 * On other systems, it defaults to "$XDG_CONFIG_HOME/arx/Eve" or
 * "$HOME/.config/arx/Eve" if XDG_CONFIG_HOME is not set.
 *
 * If the directory does not exist, it is created automatically.
 *
 * @returns A promise that resolves to the path of the configuration directory.
 */

export async function getEveConfigHome(): Promise<string> {
  let storagePath: string;
  if (Deno.build.os === "darwin") {
    storagePath = `${
      Deno.env.get("HOME")
    }/Library/Application Support/eve/arx/Eve`;
  } else {
    const xdgConfigHome = Deno.env.get("XDG_CONFIG_HOME") ??
      `${Deno.env.get("HOME")}/.config`;
    storagePath = `${xdgConfigHome}/arx/Eve`;
  }
  if (!(await exists(storagePath))) {
    await Deno.mkdir(storagePath, { recursive: true });
  }
  return storagePath;
}

/**
 * Return the path to the file in Eve's configuration directory.
 *
 * @param file The name of the file to return the path for.
 * @returns The path to the file in Eve's configuration directory.
 */
export async function getEveFilePath(file: string): Promise<string> {
  const storagePath = await getEveConfigHome();
  return `${storagePath}/${file}`;
}