#!/bin/bash

# 构建脚本 - 支持多平台交叉编译
set -e

# 获取脚本所在目录，然后切换到项目根目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"

# 颜色输出
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 创建输出目录
OUTPUT_DIR="target/release"
mkdir -p "$OUTPUT_DIR"

echo -e "${BLUE}开始构建多平台二进制文件...${NC}\n"

# 定义目标平台
# 注意：在 macOS 上交叉编译的推荐配置
TARGETS=(
    "x86_64-unknown-linux-musl"     # Linux x86_64 (静态链接，无需交叉工具链)
    "aarch64-unknown-linux-musl"    # Linux ARM64 (静态链接，无需交叉工具链)
    "x86_64-pc-windows-gnu"         # Windows x86_64 (GNU 工具链，macOS 可用)
    "x86_64-apple-darwin"           # macOS Intel
    "aarch64-apple-darwin"          # macOS Apple Silicon
)

# 可选：如果安装了 cross 工具，使用这些目标
CROSS_TARGETS=(
    "x86_64-unknown-linux-gnu"      # Linux x86_64 (glibc, 需要 cross)
    "aarch64-unknown-linux-gnu"     # Linux ARM64 (glibc, 需要 cross)
    "x86_64-pc-windows-msvc"        # Windows x86_64 (需要 cross)
)

# 检查是否启用 glibc 目标（通过环境变量或参数）
ENABLE_GLIBC=false
if [ "${ENABLE_GLIBC:-}" = "true" ] || [ "${ENABLE_GLIBC:-}" = "1" ]; then
    ENABLE_GLIBC=true
fi

# 如果提供了 --glibc 参数，启用 glibc 目标
for arg in "$@"; do
    if [ "$arg" = "--glibc" ] || [ "$arg" = "-g" ]; then
        ENABLE_GLIBC=true
        break
    fi
done

# 检查并安装必要的工具链
check_toolchain() {
    local missing_tools=()
    
    # 检查 musl 链接器
    if [[ " ${TARGETS[@]} " =~ " x86_64-unknown-linux-musl " ]] || [[ " ${TARGETS[@]} " =~ " aarch64-unknown-linux-musl " ]]; then
        if ! command -v x86_64-linux-musl-gcc &> /dev/null && ! command -v aarch64-linux-musl-gcc &> /dev/null; then
            if command -v brew &> /dev/null; then
                echo -e "${YELLOW}检测到需要 musl 交叉编译工具链...${NC}"
                if brew list musl-cross &> /dev/null 2>&1; then
                    echo -e "${GREEN}musl-cross 已安装，但链接器可能不在 PATH 中${NC}"
                    echo -e "${YELLOW}请确保 /opt/homebrew/bin 或 /usr/local/bin 在 PATH 中${NC}"
                else
                    echo -e "${YELLOW}建议安装 musl-cross: brew install musl-cross${NC}"
                fi
            fi
        fi
    fi
    
    # 检查 MinGW-w64 链接器（Windows GNU 目标）
    if [[ " ${TARGETS[@]} " =~ " x86_64-pc-windows-gnu " ]]; then
        if ! command -v x86_64-w64-mingw32-gcc &> /dev/null; then
            echo -e "${YELLOW}检测到需要 MinGW-w64 工具链（Windows GNU 目标）...${NC}"
            if command -v brew &> /dev/null; then
                if brew list mingw-w64 &> /dev/null 2>&1; then
                    echo -e "${GREEN}mingw-w64 已安装，但链接器可能不在 PATH 中${NC}"
                else
                    echo -e "${YELLOW}建议安装 mingw-w64: brew install mingw-w64${NC}"
                    echo -e "${YELLOW}或者使用 cross 工具: cargo install cross --git https://github.com/cross-rs/cross${NC}"
                fi
            fi
        fi
    fi
    echo ""
}

# 安装目标平台工具链（如果未安装）
install_targets() {
    echo -e "${YELLOW}检查并安装目标平台工具链...${NC}"
    for target in "${TARGETS[@]}"; do
        if ! rustup target list --installed | grep -q "^${target}$"; then
            echo -e "${YELLOW}安装 ${target}...${NC}"
            rustup target add "$target" || echo -e "${YELLOW}警告: 无法安装 ${target}，可能需要手动安装${NC}"
        fi
    done
    
    # 如果启用了 glibc，也安装 glibc 目标
    if [ "$ENABLE_GLIBC" = true ]; then
        for target in "${CROSS_TARGETS[@]}"; do
            if [[ "$target" == *"linux-gnu"* ]]; then
                if ! rustup target list --installed | grep -q "^${target}$"; then
                    echo -e "${YELLOW}安装 ${target} (glibc)...${NC}"
                    rustup target add "$target" || echo -e "${YELLOW}警告: 无法安装 ${target}，可能需要手动安装${NC}"
                fi
            fi
        done
    fi
    echo ""
    
    # 检查必要的交叉编译工具链
    check_toolchain
}

# 检查是否安装了 cross 工具
check_cross() {
    if command -v cross &> /dev/null; then
        return 0
    else
        return 1
    fi
}

# 确保 PATH 包含必要的工具链路径
setup_path() {
    # 添加 Homebrew 路径（如果存在）
    if [ -d "/opt/homebrew/bin" ]; then
        export PATH="/opt/homebrew/bin:$PATH"
    fi
    # 添加 Intel Mac Homebrew 路径（如果存在）
    if [ -d "/usr/local/bin" ]; then
        export PATH="/usr/local/bin:$PATH"
    fi
}

# 构建指定目标平台
build_target() {
    local target=$1
    local use_cross=false
    
    # 设置 PATH
    setup_path
    
    # 检查是否需要使用 cross 工具
    for cross_target in "${CROSS_TARGETS[@]}"; do
        if [ "$target" == "$cross_target" ]; then
            if check_cross; then
                use_cross=true
                break
            else
                echo -e "${YELLOW}警告: ${target} 需要 cross 工具，但未安装。跳过此目标。${NC}"
                echo -e "${YELLOW}安装方法: cargo install cross --git https://github.com/cross-rs/cross${NC}\n"
                return 1
            fi
        fi
    done
    
    echo -e "${BLUE}正在构建 ${target}...${NC}"
    
    local build_cmd
    if [ "$use_cross" = true ]; then
        build_cmd="cross build --release --target $target"
    else
        build_cmd="cargo build --release --target $target"
    fi
    
    if eval "$build_cmd" 2>&1 | tee /tmp/build_${target//-/_}.log; then
        echo -e "${GREEN}✓ ${target} 构建成功${NC}\n"
        
        # 复制二进制文件到输出目录
        local binary_name="secra-plugin-backend"
        if [[ "$target" == *"windows"* ]]; then
            binary_name="${binary_name}.exe"
        fi
        
        local source_path="target/${target}/release/${binary_name}"
        local dest_path="${OUTPUT_DIR}/${binary_name}-${target}"
        
        if [ -f "$source_path" ]; then
            cp "$source_path" "$dest_path"
            echo -e "${GREEN}  二进制文件已复制到: ${dest_path}${NC}\n"
        fi
        return 0
    else
        local error_log="/tmp/build_${target//-/_}.log"
        echo -e "${YELLOW}✗ ${target} 构建失败${NC}"
        
        # 检查是否是链接器问题
        if grep -q "linker.*not found" "$error_log" 2>/dev/null; then
            if [[ "$target" == *"windows-gnu"* ]]; then
                echo -e "${YELLOW}  原因: 缺少 MinGW-w64 工具链${NC}"
                echo -e "${YELLOW}  解决方案: brew install mingw-w64${NC}"
            elif [[ "$target" == *"linux-musl"* ]]; then
                echo -e "${YELLOW}  原因: 缺少 musl-cross 工具链${NC}"
                echo -e "${YELLOW}  解决方案: brew install musl-cross${NC}"
            fi
        elif grep -q "unknown option" "$error_log" 2>/dev/null; then
            echo -e "${YELLOW}  原因: 链接器不兼容，可能需要使用 cross 工具${NC}"
            echo -e "${YELLOW}  解决方案: cargo install cross --git https://github.com/cross-rs/cross${NC}"
        fi
        
        echo -e "${YELLOW}  详细日志: ${error_log}${NC}\n"
        return 1
    fi
}

# 主函数
main() {
    # 检查是否安装了 rustup
    if ! command -v rustup &> /dev/null; then
        echo -e "${YELLOW}错误: 未找到 rustup，请先安装 Rust 工具链${NC}"
        exit 1
    fi
    
    # 显示平台信息
    echo -e "${BLUE}当前平台: $(uname -s) $(uname -m)${NC}"
    local display_targets=("${TARGETS[@]}")
    if [ "$ENABLE_GLIBC" = true ]; then
        for target in "${CROSS_TARGETS[@]}"; do
            if [[ "$target" == *"linux-gnu"* ]]; then
                display_targets+=("$target")
            fi
        done
    fi
    echo -e "${BLUE}使用目标平台: ${display_targets[*]}${NC}\n"
    
    # 检查 Cargo 配置
    if [ -f ".cargo/config.toml" ]; then
        echo -e "${GREEN}检测到 .cargo/config.toml 配置文件${NC}\n"
    else
        echo -e "${YELLOW}提示: 项目包含 .cargo/config.toml 配置文件用于交叉编译${NC}\n"
    fi
    
    # 检查 cross 工具
    if check_cross; then
        echo -e "${GREEN}检测到 cross 工具，可以使用更多目标平台${NC}\n"
    else
        echo -e "${YELLOW}提示: 安装 cross 工具可以简化交叉编译过程${NC}"
        echo -e "${YELLOW}安装命令: cargo install cross --git https://github.com/cross-rs/cross${NC}\n"
    fi
    
    # 安装目标平台
    install_targets
    
    # 构建所有平台
    local success_count=0
    local fail_count=0
    local skipped_targets=()
    
    # 构建标准目标
    for target in "${TARGETS[@]}"; do
        # 检查链接器是否存在
        local need_skip=false
        
        if [[ "$target" == *"windows-gnu"* ]]; then
            if ! command -v x86_64-w64-mingw32-gcc &> /dev/null && \
               [ ! -f "/opt/homebrew/bin/x86_64-w64-mingw32-gcc" ] && \
               [ ! -f "/usr/local/bin/x86_64-w64-mingw32-gcc" ]; then
                echo -e "${YELLOW}⚠ 跳过 ${target}（需要安装 MinGW-w64: brew install mingw-w64）${NC}\n"
                skipped_targets+=("$target")
                ((fail_count++))
                continue
            fi
        fi
        
        if build_target "$target"; then
            ((success_count++))
        else
            ((fail_count++))
        fi
    done
    
    # 如果启用了 glibc，构建 glibc 目标
    if [ "$ENABLE_GLIBC" = true ]; then
        echo -e "${BLUE}开始构建 glibc 目标...${NC}\n"
        for target in "${CROSS_TARGETS[@]}"; do
            if [[ "$target" == *"linux-gnu"* ]]; then
                if build_target "$target"; then
                    ((success_count++))
                else
                    ((fail_count++))
                fi
            fi
        done
    fi
    
    echo -e "\n${BLUE}构建统计: 成功 ${success_count} 个，失败 ${fail_count} 个${NC}"
    if [ ${#skipped_targets[@]} -gt 0 ]; then
        echo -e "${YELLOW}跳过的目标: ${skipped_targets[*]}${NC}"
        echo -e "${YELLOW}提示: 查看 SETUP.md 了解如何安装必要的工具链${NC}"
    fi
    echo -e "${GREEN}构建完成！二进制文件位于: ${OUTPUT_DIR}${NC}"
    echo -e "${BLUE}构建的文件列表:${NC}"
    ls -lh "$OUTPUT_DIR" | grep "secra-plugin-backend" || echo "未找到构建文件"
}

# 如果提供了参数，只构建指定的平台
if [ $# -gt 0 ]; then
    # 检查是否有 --glibc 或 -g 参数
    targets_to_build=()
    for arg in "$@"; do
        if [ "$arg" != "--glibc" ] && [ "$arg" != "-g" ]; then
            targets_to_build+=("$arg")
        fi
    done
    
    install_targets
    if [ ${#targets_to_build[@]} -gt 0 ]; then
        for target in "${targets_to_build[@]}"; do
            build_target "$target"
        done
    else
        # 如果没有指定具体目标，运行主函数
        main
    fi
else
    main
fi
