#!/bin/bash

source "$(dirname "$0")/common.sh"

while getopts "p:e:" opt; do
    case $opt in
    p)
        product_code="${OPTARG}"
        ;;
    e)
        env="${OPTARG}"
        ;;
    *)
        echo "用法：$0 -p 产品code [-e 发布环境]"
        exit 1
        ;;
    esac
done

if [ -z "$product_code" ]; then
    echo "错误：必须指定产品 code (-p)"
    echo "用法：$0 -p 产品code [-e 发布环境]"
    exit 1
fi

env=${env:-test}

echo "${MAGENTA}正在合并代码到 ${product_code}-test 分支...${RESET}"

# 切换并拉取 main 分支
execute_command "git checkout main" "切换至 main 分支失败"
execute_command "git pull" "拉取 main 分支最新内容失败"

# 合并 main 到 ${product_code}-test
execute_command "git checkout ${product_code}-test" "切换至 ${product_code}-test 分支失败"
execute_command "git pull" "拉取 ${product_code}-test 分支最新内容失败"
execute_command "git merge main" "合并 main 到 ${product_code}-test 分支失败" "false"
merge_m2t_status=$?
if [ $merge_m2t_status -ne 0 ]; then
    # 检查是否有冲突
    if [[ $(git ls-files -u | wc -l) -gt 0 ]]; then
        echo "${YELLOW}检测到合并冲突，请手动解决冲突...${RESET}"
        echo "${YELLOW}解决冲突后，按任意键继续...${RESET}"
        read -n 1 -s -r -p ""

        if [[ $(git ls-files -u | wc -l) -gt 0 ]]; then
            echo "${RED}错误：仍存在未解决的冲突，请处理后再继续${RESET}"
            exit 1
        fi

        execute_command "git commit -m 'chore(merge): 解决冲突'" "提交冲突解决方案失败"
    else
        exit ${merge_m2t_status}
    fi
fi
execute_command "git push" "推送 ${product_code}-test 分支失败"

# 合并 ${product_code}-test 到 ${product_code}-prod
if [ "$env" = "prod" ]; then
    echo "${MAGENTA}正在合并代码到 ${product_code}-prod 分支...${RESET}"
    execute_command "git checkout ${product_code}-prod" "切换至 ${product_code}-prod 分支失败"
    execute_command "git pull" "拉取 ${product_code}-prod 分支最新内容失败"
    execute_command "git merge ${product_code}-test" "合并 ${product_code}-test 到 ${product_code}-prod 分支失败" "false"
    merge_t2p_status=$?
    if [ $merge_t2p_status -ne 0 ]; then
        # 检查是否有冲突
        if [[ $(git ls-files -u | wc -l) -gt 0 ]]; then
            echo "${YELLOW}检测到合并冲突，请手动解决冲突...${RESET}"
            echo "${YELLOW}解决冲突后，按任意键继续...${RESET}"
            read -n 1 -s -r -p ""

            if [[ $(git ls-files -u | wc -l) -gt 0 ]]; then
                echo "${RED}错误：仍存在未解决的冲突，请处理后再继续${RESET}"
                exit 1
            fi

            execute_command "git commit -m 'chore(merge): 解决冲突'" "提交冲突解决方案失败"
        else
            exit ${merge_t2p_status}
        fi
    fi
    execute_command "git push" "推送 ${product_code}-prod 分支失败"
fi

# 切换到 xiaom 分支
execute_command "git checkout xiaom" "切换至 xiaom 分支失败"
