import fs from "fs";
import path from "path";

export function resolveServiceCwd(productDir, maybeRelative) {
  return path.resolve(productDir, maybeRelative || ".");
}

export function ensureExistingPath(productDir, relativePath, label) {
  const absolute = resolveServiceCwd(productDir, relativePath);
  if (!fs.existsSync(absolute)) {
    throw new Error(`${label} does not exist: ${relativePath}`);
  }
}

export function normalizePath(value) {
  return String(value || "")
    .split(path.sep)
    .join("/")
    .replace(/^\.\/+/, "");
}

export function resolveProductDir(cwd, explicitDir) {
  const dir = explicitDir ? path.resolve(cwd, explicitDir) : cwd;
  if (!fs.existsSync(dir)) {
    throw new Error(`Product directory does not exist: ${dir}`);
  }
  return dir;
}
