import inquirer from 'inquirer'
const { default: packageInfo } = await import(
    "../package.json",
    {
      with: { type: "json" },
    }
  );
import git from 'simple-git'
import { promiseSpawn, getCurBranch, addPkgInfoTagAndPushGitOrigin, pushCurTagToOrigin, findLatestVersion } from './utils.js'

async function setPackage() {
    git().fetch()
    const { all }  = await git().tags()
    const preVersion = packageInfo.version
    const bigVersion = findLatestVersion(all)
    // 0.9.0-beta.19
    // const [, betaVersion = ''] = preVersion.split('-')
    let [f, s, t] = bigVersion.split('.').map(Number)
    let b = 1
    let nb = 1
    const curBranch = await getCurBranch()
    const isMain = curBranch === 'master'
    const prefix = curBranch === 'test' ? 'beta' : curBranch === 'dev' ? 'dev' : 'alpha'
    const prefixTip = isMain ? '主' : curBranch === 'test' ? '测试' : curBranch === 'dev' ? '开发' : '不稳定'
    console.log(`当前所在分支：${curBranch}，只能发布${prefixTip}版本`)
    if (isMain) {
        while (!!all.find(item => item === `v${f}.${s}.${t + 1}`)) {
            t++
        }
    } else {
        while (!!all.find(item => item === `v${f}.${s}.${t}-${prefix}.${Number(b)}`)) {
            b = Number(b) + 1
        }
        while (!!all.find(item => item === `v${f}.${s}.${t + 1}-${prefix}.${nb}`)) {
            nb++
        }
    }
    const versionChoices = isMain ? [
        `下一个小版本:${f}.${s}.${t + 1}`,
        `下一个中版本:${f}.${s + 1}.0`,
        `下一个大版本:${f + 1}.0.0`,
        '当前版本（不推荐，仅用于特殊情况下手动设置）:' + preVersion,
    ] : [
        `当前小版本下一个${prefixTip}版:${f}.${s}.${t}-${prefix}.${b}`,
        `下一个小版本${prefixTip}版:${f}.${s}.${t + 1}-${prefix}.${nb}`,
        '当前版本（不推荐，仅用于特殊情况下手动设置）:' + preVersion,
    ]
    const { versionText } = await inquirer.prompt({
        type: 'list',
        name: 'versionText',
        message: '请选择即将发布的版本',
        choices: versionChoices, // 可选选项
        default: preVersion,
    })
    const { tagMessage } = isMain ? await inquirer.prompt({
        type: 'input',
        name: 'tagMessage',
        message: "请输入本次发版原因",
        validate(value) {
            if (value) {
                return true
            }
            return '发版原因必须填写'
        },
    }) : { tagMessage: '测试版本' }
    const version = versionText.split(':')[1]
    const versionTag = `v${version}`
    console.log(`v${version} 即将发布，发布原因：${isMain ? '正式版本：' : ''}${tagMessage}`)
    if (version !== preVersion) {
        await addPkgInfoTagAndPushGitOrigin(versionTag)
    }
    await pushCurTagToOrigin(versionTag, tagMessage)
}

setPackage()