import { COMPONENTS_DIR, SRC_DIR } from './meta';
import { readdir, readFile, stat, writeFile } from 'fs/promises';
import path from 'path';
const componentsVersionFilePath = path.resolve(SRC_DIR, 'storybook/components-version.json');
const componentsVersion = {};
const listComponentsVersion = async (dir) => {
  const directoriesShared = await readdir(dir + '/shared/');
  const directoriesCustom = await readdir(dir + '/customs/');
  for (const directory of directoriesShared) {
    const fileExists = await stat(`${dir}/shared/${directory}/package.json`)
      .then(statInfo => statInfo.isFile())
      .catch(() => false);
    if (fileExists) {
      const rawData = await readFile(`${dir}/shared/${directory}/package.json`);
      componentsVersion[directory] = JSON.parse(rawData.toString()).version;
    }
  }
  for (const directory of directoriesCustom) {
    const fileExists = await stat(`${dir}/customs/${directory}/package.json`)
      .then(statInfo => statInfo.isFile())
      .catch(() => false);
    if (fileExists) {
      const rawData2 = await readFile(`${dir}/customs/${directory}/package.json`);
      componentsVersion[directory] = JSON.parse(rawData2.toString()).version;
    }
  }
  return Promise.resolve();
};
const main = async () => {
  console.log('Scanning components');
  await listComponentsVersion(COMPONENTS_DIR);
  console.log('Process finished', componentsVersion);
  console.log('Writing to file');
  await writeFile(componentsVersionFilePath, JSON.stringify(componentsVersion, null, 2))
    .then(() => console.log('File write success'))
    .catch(err => console.error('File write error', err));
};
main();
