import chalk from 'chalk';
import dirTree from 'directory-tree';
import { ask } from 'stdio';
import { compilePackage, compileTemplateFile, createTempProjectInstance } from './lib';
import { COMPONENTS_DIR, PROJECT_DIR } from './meta';
import { logStatus } from './log';
import { mkdir, rmdir, stat } from "fs/promises";
import { existsSync } from "fs";
let nonInteractive = false;
const checkComponentWasBuilt = async (componentName) => {
  let isBuildInCustom = false;
  let isBuildInShared = false;
  isBuildInCustom = await existsSync(`${COMPONENTS_DIR}/customs/${componentName}/readme.md`).valueOf();
  isBuildInShared = await existsSync(`${COMPONENTS_DIR}/shared/${componentName}/readme.md`).valueOf();
  return !!(isBuildInCustom || isBuildInShared);
};
const checkComponentExistance = async (componentName) => {
  let isBuildInCustom = false;
  let isBuildInShared = false;
  isBuildInCustom = await existsSync(`${COMPONENTS_DIR}/customs/${componentName}`).valueOf();
  isBuildInShared = await existsSync(`${COMPONENTS_DIR}/shared/${componentName}`).valueOf();
  return !!(isBuildInCustom || isBuildInShared);
};
const isolateAll = async () => {
  dirTree(COMPONENTS_DIR, {
    extensions: /\.tsx$/,
  }, async (_item) => {
    let componentName = _item.name;
    componentName = componentName.replace('.tsx', '');
    const exist = await checkComponentExistance(componentName);
    if (!exist) {
      console.log(`Component ${componentName} ${chalk.red('not found')}, create it with ${chalk.blue('nx run stencil:generate')} first or enter another component name.`);
    }
    else {
      const built = await checkComponentWasBuilt(componentName);
      if (!built) {
        console.log(`Component ${componentName} ${chalk.redBright('build error')}`);
        return;
      }
    }
    logStatus({
      actionDoing: 'Isolating',
      subject: componentName,
    });
    // componentName = await existsSync(`${COMPONENTS_DIR}/customs/${componentName}/readme.md`).valueOf() ?'/customs/'+componentName:await existsSync(`${COMPONENTS_DIR}/shared/${componentName}/readme.md`).valueOf()?'/shared/'+componentName:componentName;
    const subdir = await existsSync(`${COMPONENTS_DIR}/customs/${componentName}/readme.md`).valueOf() ? '/customs/' : await existsSync(`${COMPONENTS_DIR}/shared/${componentName}/readme.md`).valueOf() ? 'shared' : '';
    await compilePackage(componentName, subdir);
    await compileTemplateFile(componentName, '.gitlab-ci.yml', subdir);
    await createTempProjectInstance(componentName, subdir);
  });
};
if (process.argv.length === 3) {
  nonInteractive = true;
  console.log(`${chalk.yellow('Non-interactive mode')}`);
}
const main = async () => {
  console.log('Make .build dir with script ISOLATE ALL');
  console.log(`This script will ${chalk.green('isolate ALL')} stencil components with package.json already created into a set of isolated separate projects, ready to be individually published.`);
  if (!nonInteractive) {
    const continueTask = await ask('Continue?', { options: ['Y', 'y', 'n', ''], maxRetries: 3 });
    if (continueTask === 'n') {
      return;
    }
  }
  const buildDirExist = await stat(`${PROJECT_DIR}/.build`)
    .then(statInfo => statInfo.isDirectory())
    .catch(_error => {
    // will be noticed at line 40
  });
  if (!buildDirExist) {
    await mkdir(PROJECT_DIR + '/.build').then(() => console.log('.build created'));
  }
  else {
    await rmdir(PROJECT_DIR + '/.build', { recursive: true });
    await mkdir(PROJECT_DIR + '/.build').then(() => console.log('.build re-created'));
  }
  await isolateAll();
};
main();
