const { existsSync, writeFileSync, readdirSync } = require('fs');
const { join } = require('path');
const { yParser } = require('@umijs/utils');

(async () => {
  const args = yParser(process.argv);
  const version = '1.0.0-beta.1';
  // readdirSync(join(__dirname, '../packages')).filter((pkg) => pkg.charAt(0) !== '.');
  const pkgs = ['base-components', 'extend-components']
    .map((dir) => {
      const list = readdirSync(join(__dirname, '../packages', dir)).map((item) => `${item}!${dir}`);
      return list.filter((pkg) => pkg.charAt(0) !== '.');
    })
    .flat();

  pkgs.forEach((shortName) => {
    const [name, dir] = shortName.split('!');
    const desc = `@wisdom-components/pro-${name}`;
    const pkgJSONPath = join(__dirname, '..', 'packages', dir, name, 'package.json');

    const pkgJSONExists = existsSync(pkgJSONPath);
    let json;
    if (args.force || !pkgJSONExists) {
      json = {
        name,
        version,
        description: desc,
        module: 'es/index.js',
        main: 'lib/index.js',
        types: 'lib/index.d.ts',
        files: ['lib', 'src', 'dist', 'es'],
        repository: {
          type: 'git',
          url: 'https://g.civnet.cn:8443/ReactWeb5/winsdom-components',
        },
        browserslist: ['last 2 versions', 'Firefox ESR', '> 1%', 'ie >= 11'],
        keywords: ['antd', 'admin', 'ant-design', 'ant-design-pro'],
        authors: ['dengxiaofeng'],
        license: 'MIT',
        bugs: 'https://g.civnet.cn:8443/ReactWeb5/winsdom-components/plugins/issues',
        homepage: `https://g.civnet.cn:8443/ReactWeb5/winsdom-components/tree/master/packages/${name}#readme`,
        peerDependencies: {
          umi: '3.x',
        },
        publishConfig: {
          access: 'public',
        },
      };
      if (pkgJSONExists) {
        // eslint-disable-next-line global-require,import/no-dynamic-require
        const pkg = require(pkgJSONPath);
        [
          'dependencies',
          'devDependencies',
          'peerDependencies',
          'bin',
          'version',
          'files',
          'authors',
          'types',
          'sideEffects',
          'main',
          'module',
          'description',
        ].forEach((key) => {
          if (pkg[key]) json[key] = pkg[key];
        });
      }
      writeFileSync(pkgJSONPath, `${JSON.stringify(json, null, 2)}\n`);
    }

    const readmePath = join(__dirname, '..', 'packages', name, 'README.md');
    if (args.force || !existsSync(readmePath)) {
      writeFileSync(
        readmePath,
        `# ${name}
> ${json.description}.
See our website [${name}](https://umijs.org/plugins/${name}) for more information.
## Install
Using npm:
\`\`\`bash
$ npm install --save ${name}
\`\`\`
or using yarn:
\`\`\`bash
$ yarn add ${name}
\`\`\`
`,
      );
    }
  });
})();
