#!/bin/bash

# macOS版本的Flutter APK构建脚本
# 基于Windows版本的flutter_build_apk_onwindows.bat改写

# 设置错误处理
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"
}

# 获取项目根目录
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$PROJECT_DIR"

log_info "项目目录: $PROJECT_DIR"

# 1. 终止相关进程
log_info "终止相关进程..."
pkill -f "java.*gradle" 2>/dev/null || true
pkill -f "gradle" 2>/dev/null || true
sleep 2

# 强制删除函数
force_delete() {
    local target="$1"
    local max_retries=3
    local retry_delay=1
    
    if [ ! -e "$target" ]; then
        return 0
    fi
    
    for ((i=1; i<=max_retries; i++)); do
        log_info "尝试删除 $target (第 $i 次，共 $max_retries 次)"
        
        # 尝试删除
        rm -rf "$target" 2>/dev/null || true
        
        # 检查是否删除成功
        if [ ! -e "$target" ]; then
            log_success "成功删除 $target"
            return 0
        fi
        
        # 如果未成功，等待后重试
        if [ $i -lt $max_retries ]; then
            sleep $retry_delay
            retry_delay=$((retry_delay * 2))  # 指数退避策略
        fi
    done
    
    log_warning "警告: 无法完全删除 $target，某些文件可能正在使用中"
    return 1
}

# 2. Flutter清理
log_info "运行 flutter clean..."
if ! flutter clean; then
    log_error "flutter clean 失败，错误码: $?"
    exit 1
fi

# 3. 强制删除构建目录
log_info "删除残留文件"
force_delete "build"
force_delete ".dart_tool"
force_delete "pubspec.lock"

# 4. 获取依赖包
log_info "运行 flutter pub get..."
if ! flutter pub get; then
    log_error "flutter pub get 失败，错误码: $?"
    exit 1
fi

# 5. 运行build_runner
log_info "运行 build_runner..."
if ! flutter packages pub run build_runner build --delete-conflicting-outputs; then
    log_error "build_runner 失败，错误码: $?"
    exit 1
fi

# 6. 构建release APK
log_info "构建 release APK..."
if ! flutter build apk --release; then
    log_error "APK 构建失败，错误码: $?"
    exit 1
fi

# 7. 打开APK所在文件夹
log_info "打开 APK 目录"
APK_DIR="$PROJECT_DIR/build/app/outputs/flutter-apk"
if [ -d "$APK_DIR" ]; then
    # macOS使用open命令打开Finder
    open "$APK_DIR"
else
    log_warning "APK 目录不存在: $APK_DIR"
fi

echo
log_success "所有步骤成功完成!"
log_success "APK 文件生成位置: $APK_DIR"
echo

# 显示生成的APK文件信息
if [ -d "$APK_DIR" ]; then
    echo "生成的APK文件:"
    ls -la "$APK_DIR"/*.apk 2>/dev/null || log_warning "未找到APK文件"
fi

sleep 3
exit 0
