// 写入文件，安装依赖
import fs = require('fs-extra');
import chalk = require('chalk');
import path = require('path');
// import createQuestions from './questions/creator';
import clearConsole from './utils/clearConsole';
import createSpawnCmd from './utils/createSpawnCmd';
import { ejsRender } from './createTemplate';
import options, { fetchTemplateFiles } from './options';

let startTime: number, endTime: number;

export default async function (name: string): Promise<void> {
  // CLI 模板文件夹路径
  options.src = path.resolve(__dirname, '../template');
  // 获取基础参数
  options.name = name;
  options.dest = path.resolve(process.cwd(), name);
  const cmdIgnore = createSpawnCmd(options.dest, 'ignore');
  const cmdInherit = createSpawnCmd(options.dest, 'inherit');

  clearConsole('cyan', `KK-CLI v${options.version}`);

  // 执行自定义选项
  // await createQuestions();

  // 开始记录用时
  startTime = new Date().getTime()
  // 拷贝基础模板文件
  await fs.copy(options.src, options.dest);
  // 编译 ejs 模板文件
  await Promise.all(fetchTemplateFiles().map(file => ejsRender(file)));
  console.log(`> Project template directory ${chalk.yellow(options.dest)}`);
  // 生成 gitignore
  await fs.move(
    path.resolve(options.dest, '.gitignore.ejs'),
    path.resolve(options.dest, '.gitignore'),
    { overwrite: true }
  );
  // Git 初始化
  await cmdIgnore('git', ['init'])
  await cmdIgnore('git', ['add .'])
  await cmdIgnore('git', ['commit -m "create vite-app by KK-CLI"'])
  console.log(`> Git init successful`);

  // 依赖安装
  console.log(`> Dependencies are being installed automatically, please waiting...`);
  console.log('');
  await cmdInherit('pnpm', ['install']);

  clearConsole('cyan', `KK-CLI v${options.version}`);
  endTime = new Date().getTime();
  const usageTime = (endTime - startTime) / 1000
  console.log(`> Project creation completed after${chalk.cyan(usageTime)}s，please continue by follow options...`);
  console.log('');
  console.log(chalk.cyan(' $ ') + chalk.blueBright(`cd ${name}`));
  console.log(chalk.cyan(' $ ') + chalk.blueBright('pnpm serve'));
}
