import { homedir } from "node:os";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";

export function resolveKeepDirectory(config = {}, homeDirectory = homedir()) {
  const configured = String(config.keepDirectory || "").trim();
  if (configured) return resolve(configured);
  const directories = config.directories || [];
  const named = directories.find((directory) => basename(directory) === "Private Reel");
  if (named) return resolve(named);
  return join(homeDirectory, "Documents", "Private Reel");
}

export function resolveCookingDirectory(config = {}, homeDirectory = homedir()) {
  const configured = String(config.cookingDirectory || "").trim();
  return configured ? resolve(configured) : join(homeDirectory, "Documents", "cooking");
}

export function resolveLibraryDirectories(config = {}, homeDirectory = homedir()) {
  return [...new Set([
    ...(config.directories || []).map((directory) => resolve(directory)),
    resolveKeepDirectory(config, homeDirectory),
  ])];
}

export function isKeptSeriesPath(path, config = {}, homeDirectory = homedir()) {
  const keepDirectory = resolveKeepDirectory(config, homeDirectory);
  const relativePath = relative(keepDirectory, resolve(path));
  if (
    !relativePath
    || relativePath === ".."
    || relativePath.startsWith(`..${sep}`)
    || isAbsolute(relativePath)
  ) {
    return false;
  }
  return dirname(relativePath) !== ".";
}
