#!/bin/bash

# 定义颜色变量
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # 重置颜色

# 读取package.json中的版本号
VERSION=$(node -p "require('./package.json').version")

# 添加版本号校验
if [[ -z "$VERSION" ]]; then
    printf "${RED}无法读取package.json中的版本号${NC}\n"
    exit 1
fi

printf "${GREEN}当前版本号: $VERSION${NC}\n"


# 添加pnpm命令校验
if ! command -v pnpm &> /dev/null; then
    printf "${RED}pnpm未安装，请先安装pnpm${NC}\n"
    exit 1
fi

# 选择版本升级类型
printf "${YELLOW}请选择版本升级类型:${NC}\n"
echo "1) major（主版本）"
echo "2) minor（次版本）"
echo "3) patch（补丁版本）"
echo "4) beta（测试版本）"
read -p "请输入选项 (1-4): " upgrade_choice

case $upgrade_choice in
    1)
        pnpm version major
        ;;
    2)
        pnpm version minor
        ;;
    3)
        pnpm version patch
        ;;
    4)
        pnpm version prerelease --preid=beta
        ;;
    *)
        printf "${RED}无效的选项${NC}\n"
        exit 1
        ;;
esac

# 重新获取更新后的版本号
VERSION=$(node -p "require('./package.json').version")
printf "${GREEN}更新后的版本号: $VERSION${NC}\n"

# 选择发布版本类型
printf "${YELLOW}请选择发布版本类型:${NC}\n"
echo "1) 正式版"
echo "2) Beta版"
read -p "请输入选项 (1-2): " version_choice

case $version_choice in
    1)
        PUBLISH_TAG=""
        printf "${GREEN}您选择了发布正式版${NC}\n"
        ;;
    2)
        PUBLISH_TAG="--tag beta"
        printf "${GREEN}您选择了发布Beta版${NC}\n"
        ;;
    *)
        printf "${RED}无效的选项${NC}\n"
        exit 1
        ;;
esac


# 添加发布前的确认提示
read -p "是否确认发布版本 $VERSION? (y/n) " confirm
if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
    printf "${YELLOW}发布已取消${NC}\n"
    exit 0
fi

# 发布到npm
if [ -z "$PUBLISH_TAG" ]; then
    # 发布正式版
    if npm publish; then
        printf "${GREEN}正式版发布成功!${NC}\n"
        printf "${GREEN}当前版本: $VERSION${NC}\n"
    else
        printf "${RED}发布失败，正在回退版本...${NC}\n"
        git checkout -- package.json
        printf "${YELLOW}版本已回退${NC}\n"
        exit 1
    fi
else
    # 发布beta版
    if npm publish $PUBLISH_TAG; then
        printf "${GREEN}发布成功!${NC}\n"
        printf "${GREEN}当前版本: $VERSION${NC}\n"
    else
        printf "${RED}发布失败，正在回退版本...${NC}\n"
        git checkout -- package.json
        printf "${YELLOW}版本已回退${NC}\n"
        exit 1
    fi
fi
