const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});

const root = process.cwd();
const file = path.join(root, 'UPDATE.md');
const packageFile = path.join(process.cwd(), 'package.json');

readline.question(`您这次更新的内容是什么?`, (desc) => {
  readline.close();
  try {
    const packages = fs.readFileSync(packageFile, 'utf-8');

    const packageJson = JSON.parse(packages || '{}');

    const { version } = packageJson || {};

    const versions = version.split('.');

    versions[2] = Number(versions[2]) + 1;

    packageJson.version = versions.join('.');

    fs.writeFileSync(packageFile, JSON.stringify(packageJson));

    execSync('npx prettier -w package.json');

    const message = fs.readFileSync(file, 'utf-8');

    const messageList = message.split('\r\n').filter(Boolean);
    const newMessage = []
      .concat([`- ${packageJson.version} ${desc}`])
      .concat(messageList)
      .join('\r\n\r\n');
    fs.writeFileSync(file, newMessage);

    execSync('git add .');

    execSync(`git commit -m "feat: ${desc}"`);

    execSync('git push');

    execSync('npm publish --access public');
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
});
