export const PREINSTALL_TOOLS = ["docker", "node", "python", "go", "lua", "build-essential"] as const;

export type PreinstallTool = typeof PREINSTALL_TOOLS[number];

const toolSet = new Set<string>(PREINSTALL_TOOLS);
const APT_PACKAGE_RE = /^[A-Za-z0-9.+:-]+$/;

export function normalizePreinstallTools(input: unknown, useDockerCompose = false): PreinstallTool[] {
  const tools = Array.isArray(input)
    ? input.filter((tool): tool is PreinstallTool => typeof tool === "string" && toolSet.has(tool))
    : [];
  if (useDockerCompose && !tools.includes("docker")) tools.push("docker");
  return [...new Set(tools)];
}

export function normalizeNodeVersion(input: unknown, nodeSelected: boolean): string | null {
  if (!nodeSelected) return null;
  const value = typeof input === "string" ? input.trim() : "";
  if (!value) return "lts/*";
  return /^[A-Za-z0-9._/*+-]+$/.test(value) ? value.slice(0, 64) : "lts/*";
}

export function normalizeAptPackages(input: unknown): string[] {
  const packages = Array.isArray(input)
    ? input.filter((pkg): pkg is string => typeof pkg === "string" && APT_PACKAGE_RE.test(pkg))
    : [];
  return [...new Set(packages)];
}
