#!/bin/bash

# ==============================================================================
# 风七六平台版本管理工具 v2.0.0
# 符合大厂标准的语义化版本自动生成系统
# 基于Git提交历史自动计算语义化版本号
# 遵循Conventional Commits规范
# ==============================================================================

set -e

# 配置常量
VERSION_FILE="VERSION"
VERSION_JSON_FILE="version.json"
ENV_FILE="env/.env.example"
BOM_POM_FILE="services/platform-bom/pom.xml"

COMMIT_ANALYSIS_DEPTH=20
DEFAULT_INITIAL_VERSION="1.0.0"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
GRAY='\033[0;90m'
NC='\033[0m' # No Color

# 参数解析
ENVIRONMENT="development"
BRANCH=""
BUILD_NUMBER=""
DRY_RUN=false
QUIET=false
UPDATE_POM=false
UPDATE_JSON=true
UPDATE_ENV=false
CUSTOM_TAG=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        -e|--environment)
            ENVIRONMENT="$2"
            shift 2
            ;;
        -b|--branch)
            BRANCH="$2"
            shift 2
            ;;
        -n|--build-number)
            BUILD_NUMBER="$2"
            shift 2
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        -q|--quiet)
            QUIET=true
            shift
            ;;
        --update-pom)
            UPDATE_POM=true
            shift
            ;;
        --update-json)
            UPDATE_JSON=true
            shift
            ;;
        --update-env)
            UPDATE_ENV=true
            shift
            ;;
        --no-json)
            UPDATE_JSON=false
            shift
            ;;
        -t|--tag)
            CUSTOM_TAG="$2"
            shift 2
            ;;
        *)
            echo "未知参数: $1"
            exit 1
            ;;
    esac
done

# 颜色输出函数
print_color() {
    local color=$1
    local message=$2
    if [ "$QUIET" = false ]; then
        echo -e "${color}${message}${NC}"
    fi
}

# 获取Git信息
get_git_info() {
    local current_branch=""
    local commit_hash=""
    local commit_count=""
    local is_dirty=""

    if command -v git &> /dev/null; then
        current_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
        commit_hash=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
        commit_count=$(git rev-list --count HEAD 2>/dev/null || echo "0")
        
        if [ -n "$(git status --porcelain 2>/dev/null)" ]; then
            is_dirty="-dirty"
        fi
    else
        current_branch="unknown"
        commit_hash="unknown"
        commit_count="0"
    fi

    echo "$current_branch|$commit_hash|$commit_count|$is_dirty"
}

# 分析Git提交历史
analyze_commits() {
    local has_major="false"
    local has_minor="false"
    local has_patch="false"

    if command -v git &> /dev/null; then
        while IFS= read -r line; do
            if [[ -z "$line" ]]; then
                continue
            fi
            
            if [[ "$line" =~ BREAKING[[:space:]_-]CHANGE || "$line" =~ !: ]]; then
                has_major="true"
            elif [[ "$line" =~ ^[a-zA-Z0-9]+\s+feat(:|\() ]]; then
                has_minor="true"
            elif [[ "$line" =~ ^[a-zA-Z0-9]+\s+(fix|perf|refactor)(:|\() ]]; then
                has_patch="true"
            fi
        done < <(git log --oneline -"$COMMIT_ANALYSIS_DEPTH" 2>/dev/null || echo "")
    fi

    echo "$has_major|$has_minor|$has_patch"
}

# 解析版本号
parse_version() {
    local version_string="$1"
    local clean_version="${version_string#v}"
    
    IFS='.' read -r major minor patch <<< "$clean_version"
    
    echo "${major:-1}.${minor:-0}.${patch:-0}"
}

# 格式化版本号
format_version() {
    local major=$1
    local minor=$2
    local patch=$3
    local branch=$4
    local commit=$5
    local build_number=$6
    local environment=$7
    local dirty_flag=$8

    local base_version="${major}.${minor}.${patch}"
    local qualified_version="v${base_version}"

    # 添加环境后缀
    if [[ "$environment" != "production" && "$environment" != "prod" ]]; then
        qualified_version="${qualified_version}-${environment}"
    fi

    # 添加分支信息
    if [[ -n "$branch" && "$branch" != "main" && "$branch" != "master" && "$branch" != "develop" ]]; then
        local sanitized_branch=$(echo "$branch" | sed 's/[/_]/-/g')
        qualified_version="${qualified_version}-${sanitized_branch}"
    fi

    # 添加提交哈希
    if [[ -n "$commit" && "$commit" != "unknown" ]]; then
        qualified_version="${qualified_version}-${commit}"
    fi

    # 添加构建号
    if [[ -n "$build_number" && "$build_number" != "0" ]]; then
        qualified_version="${qualified_version}-${build_number}"
    fi

    # 添加脏标记
    if [[ -n "$dirty_flag" ]]; then
        qualified_version="${qualified_version}${dirty_flag}"
    fi

    echo "${base_version}|${qualified_version}"
}

# 更新VERSION文件
update_version_file() {
    local version="$1"
    
    if [ "$DRY_RUN" = true ]; then
        print_color "$CYAN" "[DRY RUN] 将会更新 $VERSION_FILE: BASE_VERSION=$version"
        return
    fi

    echo "BASE_VERSION=$version" > "$VERSION_FILE"
    print_color "$GREEN" "已更新 $VERSION_FILE: BASE_VERSION=$version"
}

# 更新version.json文件
update_version_json() {
    local base_version="$1"
    local qualified_version="$2"
    local commit="$3"
    local branch="$4"
    local build_number="$5"
    local environment="$6"

    local json_content=$(cat <<EOF
{
  "version": "$qualified_version",
  "baseVersion": "v$base_version",
  "commit": "$commit",
  "branch": "$branch",
  "buildNumber": "$build_number",
  "commitCount": "$build_number",
  "buildTime": "$(date -u +"%Y-%m-%dT%H:%M:%S.000000")",
  "generatedAt": "$(date +"%Y-%m-%d %H:%M:%S")",
  "environment": "$environment"
}
EOF
)

    if [ "$DRY_RUN" = true ]; then
        print_color "$CYAN" "[DRY RUN] 将会更新 $VERSION_JSON_FILE"
        print_color "$GRAY" "$json_content"
        return
    fi

    echo "$json_content" > "$VERSION_JSON_FILE"
    print_color "$GREEN" "已更新 $VERSION_JSON_FILE"
}

# 更新BOM pom.xml版本
update_bom_pom() {
    local version="$1"

    if [ ! -f "$BOM_POM_FILE" ]; then
        print_color "$YELLOW" "警告: $BOM_POM_FILE 不存在"
        return
    fi

    local old_version=$(grep -oP '<version>\K[^<]+(?=</version>\s*<packaging>pom</packaging>)' "$BOM_POM_FILE" || echo "")
    
    if [ -z "$old_version" ]; then
        print_color "$YELLOW" "警告: 无法找到pom.xml中的版本号"
        return
    fi

    if [ "$DRY_RUN" = true ]; then
        print_color "$CYAN" "[DRY RUN] 将会更新 $BOM_POM_FILE: $old_version -> $version"
        return
    fi

    sed -i "s/<version>$old_version<\/version>/<version>$version<\/version>/" "$BOM_POM_FILE"
    print_color "$GREEN" "已更新 $BOM_POM_FILE: $old_version -> $version"
}

# 更新环境变量文件
update_env_file() {
    local version="$1"

    if [ ! -f "$ENV_FILE" ]; then
        print_color "$YELLOW" "警告: $ENV_FILE 不存在"
        return
    fi

    if grep -q "^APP_VERSION=" "$ENV_FILE"; then
        sed -i "s/^APP_VERSION=.*/APP_VERSION=$version/" "$ENV_FILE"
    else
        echo "APP_VERSION=$version" >> "$ENV_FILE"
    fi

    if [ "$DRY_RUN" = true ]; then
        print_color "$CYAN" "[DRY RUN] 将会更新 $ENV_FILE: APP_VERSION=$version"
        return
    fi

    print_color "$GREEN" "已更新 $ENV_FILE: APP_VERSION=$version"
}

# 主执行流程
main() {
    # 获取项目根目录
    SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
    cd "$SCRIPT_DIR/.."

    print_color "$CYAN" "========================================"
    print_color "$CYAN" "    风七六平台版本管理工具 v2.0.0"
    print_color "$CYAN" "========================================"

    # 获取Git信息
    print_color "$NC" "\n[1/4] 获取Git仓库信息..."
    IFS='|' read -r git_branch git_commit git_count git_dirty <<< "$(get_git_info)"
    print_color "$GRAY" "  分支: $git_branch"
    print_color "$GRAY" "  提交: $git_commit"
    print_color "$GRAY" "  提交数: $git_count"

    # 分析提交历史
    print_color "$NC" "\n[2/4] 分析最近 $COMMIT_ANALYSIS_DEPTH 次提交..."
    IFS='|' read -r has_major has_minor has_patch <<< "$(analyze_commits)"
    print_color "$GRAY" "  包含重大变更: $has_major"
    print_color "$GRAY" "  包含新功能: $has_minor"
    print_color "$GRAY" "  包含修复: $has_patch"

    # 读取当前版本
    print_color "$NC" "\n[3/4] 读取当前版本..."
    current_version="$DEFAULT_INITIAL_VERSION"
    if [ -f "$VERSION_FILE" ]; then
        current_version=$(grep -oP 'BASE_VERSION=\K.*' "$VERSION_FILE" | tr -d '\r')
    fi
    print_color "$GRAY" "  当前版本: v$current_version"

    # 解析版本号
    IFS='.' read -r major minor patch <<< "$(parse_version "$current_version")"

    # 计算新版本
    print_color "$NC" "\n[4/4] 计算新版本..."
    
    if [ "$has_major" = "true" ]; then
        major=$((major + 1))
        minor=0
        patch=0
        print_color "$MAGENTA" "  BREAKING CHANGE 检测到 - 升级 MAJOR 版本"
    elif [ "$has_minor" = "true" ]; then
        minor=$((minor + 1))
        patch=0
        print_color "$CYAN" "  feat 检测到 - 升级 MINOR 版本"
    elif [ "$has_patch" = "true" ]; then
        patch=$((patch + 1))
        print_color "$GREEN" "  fix/perf/refactor 检测到 - 升级 PATCH 版本"
    else
        print_color "$GRAY" "  未检测到版本变更 - 保持当前版本"
    fi

    # 生成版本信息
    local branch_to_use="${BRANCH:-$git_branch}"
    local build_num_to_use="${BUILD_NUMBER:-$git_count}"

    IFS='|' read -r base_version qualified_version <<< "$(format_version \
        "$major" "$minor" "$patch" \
        "$branch_to_use" "$git_commit" \
        "$build_num_to_use" "$ENVIRONMENT" \
        "$git_dirty")"

    # 输出版本信息
    print_color "$CYAN" "\n========================================"
    print_color "$CYAN" "           版本计算结果"
    print_color "$CYAN" "========================================"
    print_color "$YELLOW" "\n基础版本: v$base_version"
    print_color "$GREEN" "完整版本: $qualified_version"
    print_color "$GRAY" "环境: $ENVIRONMENT"
    print_color "$GRAY" "分支: $branch_to_use"
    print_color "$CYAN" "\n========================================"

    # 更新文件
    if [ "$DRY_RUN" = false ]; then
        print_color "$NC" "\n[更新文件]"
    fi

    # 更新VERSION文件
    update_version_file "$base_version"

    # 更新version.json
    if [ "$UPDATE_JSON" = true ]; then
        update_version_json "$base_version" "$qualified_version" "$git_commit" "$git_branch" "$git_count" "$ENVIRONMENT"
    fi

    # 更新pom.xml
    if [ "$UPDATE_POM" = true ]; then
        update_bom_pom "$base_version"
    fi

    # 更新环境变量
    if [ "$UPDATE_ENV" = true ]; then
        update_env_file "$qualified_version"
    fi

    # 输出结果
    if [ "$QUIET" = false ]; then
        print_color "$GREEN" "\n版本生成完成！"
    fi

    # 返回版本号供脚本调用
    echo "$qualified_version"
}

main "$@"