#!/bin/bash

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "AIOps 版本管理工具"
    echo
    echo "用法: $0 <command> [options]"
    echo
    echo "命令:"
    echo "  bump <type>     - 升级版本号 (major|minor|patch)"
    echo "  set <version>   - 设置指定版本号"
    echo "  show            - 显示当前版本信息"
    echo "  list            - 列出所有版本"
    echo "  clean           - 清理旧版本"
    echo "  validate        - 验证版本配置"
    echo
    echo "示例:"
    echo "  $0 bump minor    # 升级次版本号 1.0.0 -> 1.1.0"
    echo "  $0 set 2.0.0     # 设置版本为 2.0.0"
    echo "  $0 show          # 显示当前版本"
    echo "  $0 list          # 列出所有版本"
}

# 获取当前版本
get_current_version() {
    if [[ -f "config/VERSION" ]]; then
        cat config/VERSION
    else
        echo "0.0.0"
    fi
}

# 设置版本号
set_version() {
    local new_version="$1"
    
    # 验证版本号格式
    if [[ ! "$new_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        log_error "无效的版本号格式: $new_version"
        log_info "版本号格式应为: major.minor.patch (如: 1.2.3)"
        exit 1
    fi
    
    echo "$new_version" > config/VERSION
    log_success "版本号已设置为: $new_version"
}

# 升级版本号
bump_version() {
    local bump_type="$1"
    local current_version=$(get_current_version)
    
    # 解析当前版本号
    IFS='.' read -r major minor patch <<< "$current_version"
    
    case "$bump_type" in
        "major")
            major=$((major + 1))
            minor=0
            patch=0
            ;;
        "minor")
            minor=$((minor + 1))
            patch=0
            ;;
        "patch")
            patch=$((patch + 1))
            ;;
        *)
            log_error "无效的升级类型: $bump_type"
            log_info "支持的类型: major, minor, patch"
            exit 1
            ;;
    esac
    
    local new_version="$major.$minor.$patch"
    set_version "$new_version"
    log_success "版本号已从 $current_version 升级到 $new_version"
}

# 显示当前版本信息
show_version() {
    local current_version=$(get_current_version)
    log_info "当前版本: $current_version"
    
    if [[ -f "config/checklist" ]]; then
        echo
        echo "组件清单:"
        while IFS= read -r line; do
            [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
            read -r component version dep order <<< "$line"
            if [[ -n "$component" && -n "$version" ]]; then
                echo "  - $component v$version"
            fi
        done < config/checklist
    fi
    
    # 检查是否有对应的 artifact
    local artifact_dir="artifact/$current_version"
    if [[ -d "$artifact_dir" ]]; then
        echo
        echo "已构建的组件:"
        for file in "$artifact_dir"/*.tar.gz; do
            if [[ -f "$file" ]]; then
                local filename=$(basename "$file")
                local size=$(du -h "$file" | cut -f1)
                echo "  - $filename ($size)"
            fi
        done
        
        if [[ -f "$artifact_dir/version.json" ]]; then
            echo
            echo "版本信息文件: $artifact_dir/version.json"
        fi
    else
        echo
        log_warning "未找到对应的构建目录: $artifact_dir"
        log_info "运行 ./package.sh 进行构建"
    fi
}

# 列出所有版本
list_versions() {
    log_info "所有版本列表:"
    echo
    
    if [[ ! -d "artifact" ]]; then
        log_warning "artifact 目录不存在"
        return
    fi
    
    for version_dir in artifact/*/; do
        if [[ -d "$version_dir" ]]; then
            local version=$(basename "$version_dir")
            local current_version=$(get_current_version)
            
            if [[ "$version" == "$current_version" ]]; then
                echo "  * $version (当前版本)"
            else
                echo "    $version"
            fi
            
            # 显示该版本的组件
            local component_count=0
            for file in "$version_dir"/*.tar.gz; do
                if [[ -f "$file" ]]; then
                    component_count=$((component_count + 1))
                fi
            done
            
            if [[ $component_count -gt 0 ]]; then
                echo "      包含 $component_count 个组件"
            fi
        fi
    done
}

# 清理旧版本
clean_versions() {
    local current_version=$(get_current_version)
    local keep_versions=5  # 保留最近5个版本
    
    log_info "清理旧版本 (保留最近 $keep_versions 个版本)..."
    
    if [[ ! -d "artifact" ]]; then
        log_warning "artifact 目录不存在"
        return
    fi
    
    # 获取所有版本目录，按修改时间排序
    local versions=()
    while IFS= read -r -d '' version_dir; do
        versions+=("$(basename "$version_dir")")
    done < <(find artifact -maxdepth 1 -type d -name "[0-9]*" -print0 | sort -z)
    
    local total_versions=${#versions[@]}
    local versions_to_remove=$((total_versions - keep_versions))
    
    if [[ $versions_to_remove -le 0 ]]; then
        log_info "无需清理，当前只有 $total_versions 个版本"
        return
    fi
    
    log_info "将删除 $versions_to_remove 个旧版本..."
    
    for ((i=0; i<versions_to_remove; i++)); do
        local version="${versions[i]}"
        if [[ "$version" != "$current_version" ]]; then
            log_info "删除版本: $version"
            rm -rf "artifact/$version"
        fi
    done
    
    log_success "旧版本清理完成"
}

# 验证版本配置
validate_version() {
    log_info "验证版本配置..."
    
    local errors=0
    
    # 检查 VERSION 文件
    if [[ ! -f "config/VERSION" ]]; then
        log_error "VERSION 文件不存在"
        errors=$((errors + 1))
    else
        local version=$(get_current_version)
        if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            log_error "VERSION 文件格式无效: $version"
            errors=$((errors + 1))
        else
            log_success "VERSION 文件格式正确: $version"
        fi
    fi
    
    # 检查 checklist 文件
    if [[ ! -f "config/checklist" ]]; then
        log_error "checklist 文件不存在"
        errors=$((errors + 1))
    else
        local component_count=0
        while IFS= read -r line; do
            [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
            read -r component version dep order <<< "$line"
            if [[ -n "$component" && -n "$version" ]]; then
                component_count=$((component_count + 1))
                
                # 检查组件目录是否存在
                if [[ ! -d "plugins/$component" ]]; then
                    log_error "组件目录不存在: plugins/$component"
                    errors=$((errors + 1))
                fi
            fi
        done < config/checklist
        
        if [[ $component_count -gt 0 ]]; then
            log_success "checklist 包含 $component_count 个组件"
        else
            log_error "checklist 中没有有效组件"
            errors=$((errors + 1))
        fi
    fi
    
    # 检查 package.sh 文件
    if [[ ! -f "scripts/package_artifact.sh" ]]; then
        log_error "package_artifact.sh 文件不存在"
        errors=$((errors + 1))
    else
        if [[ -x "scripts/package_artifact.sh" ]]; then
            log_success "package_artifact.sh 可执行"
        else
            log_warning "package_artifact.sh 不可执行，请运行: chmod +x scripts/package_artifact.sh"
        fi
    fi
    
    # 检查 install.sh 文件
    if [[ ! -f "scripts/install_artifact.sh" ]]; then
        log_error "install_artifact.sh 文件不存在"
        errors=$((errors + 1))
    else
        if [[ -x "scripts/install_artifact.sh" ]]; then
            log_success "install_artifact.sh 可执行"
        else
            log_warning "install_artifact.sh 不可执行，请运行: chmod +x scripts/install_artifact.sh"
        fi
    fi
    
    if [[ $errors -eq 0 ]]; then
        log_success "版本配置验证通过"
    else
        log_error "发现 $errors 个配置问题"
        exit 1
    fi
}

# 主函数
main() {
    case "${1:-}" in
        "bump")
            if [[ -z "${2:-}" ]]; then
                log_error "请指定升级类型: major, minor, patch"
                exit 1
            fi
            bump_version "$2"
            ;;
        "set")
            if [[ -z "${2:-}" ]]; then
                log_error "请指定版本号"
                exit 1
            fi
            set_version "$2"
            ;;
        "show")
            show_version
            ;;
        "list")
            list_versions
            ;;
        "clean")
            clean_versions
            ;;
        "validate")
            validate_version
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        "")
            show_help
            ;;
        *)
            log_error "未知命令: $1"
            echo
            show_help
            exit 1
            ;;
    esac
}

# 脚本入口
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
