import { existsSync, mkdirSync, lstatSync, readdirSync, writeFileSync, readFileSync } from 'node:fs';
import { join, basename, extname } from 'node:path';

const fileExtensionWhitelist = [
  ".woff2",
  ".svg",
  ".img",
  ".jpg",
  ".jpeg",
  ".png"
];
function copyFileSync(source, target) {
  let targetFile = target;
  if (existsSync(target)) {
    if (lstatSync(target).isDirectory()) {
      targetFile = join(target, basename(source));
    }
  }
  if (!fileExtensionWhitelist.includes(extname(source))) {
    return;
  }
  writeFileSync(targetFile, readFileSync(source));
}
function copyFolderRecursiveSync(source, target) {
  let files = [];
  const targetFolder = join(target, basename(source));
  if (!existsSync(targetFolder)) {
    mkdirSync(targetFolder);
  }
  if (lstatSync(source).isDirectory()) {
    files = readdirSync(source);
    for (const file of files) {
      const curSource = join(source, file);
      if (lstatSync(curSource).isDirectory()) {
        copyFolderRecursiveSync(curSource, targetFolder);
      } else {
        copyFileSync(curSource, targetFolder);
      }
    }
  }
}
const copyAssets = (assetDir, assets) => {
  if (!existsSync(assetDir)) {
    mkdirSync(assetDir, { recursive: true });
  }
  copyFolderRecursiveSync(assets, assetDir);
};

export { copyAssets };
