#!/bin/bash
# 环境设置脚本

set -e

ENV_TYPE=${1:-development}
FORCE_SETUP=${2:-false}

echo "=== 考培练系统环境设置 ==="
echo "环境类型: $ENV_TYPE"
echo "设置时间: $(date)"
echo ""

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

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查必要的工具
check_requirements() {
    print_message $BLUE "检查系统要求..."
    
    # 检查Docker
    if ! command -v docker &> /dev/null; then
        print_message $RED "❌ Docker未安装，请先安装Docker"
        exit 1
    fi
    
    # 检查Docker Compose
    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        print_message $RED "❌ Docker Compose未安装，请先安装Docker Compose"
        exit 1
    fi
    
    # 检查Node.js (如果需要本地开发)
    if [ "$ENV_TYPE" = "development" ] && ! command -v node &> /dev/null; then
        print_message $YELLOW "⚠️  Node.js未安装，建议安装以支持本地开发"
    fi
    
    # 检查Python (如果需要本地开发)
    if [ "$ENV_TYPE" = "development" ] && ! command -v python3 &> /dev/null; then
        print_message $YELLOW "⚠️  Python3未安装，建议安装以支持本地开发"
    fi
    
    print_message $GREEN "✅ 系统要求检查完成"
}

# 设置前端环境
setup_frontend_env() {
    print_message $BLUE "设置前端环境配置..."
    
    local env_file="kaopeilian-frontend/.env.$ENV_TYPE"
    local example_file="kaopeilian-frontend/.env.example"
    
    if [ ! -f "$env_file" ] || [ "$FORCE_SETUP" = "true" ]; then
        if [ -f "$example_file" ]; then
            cp "$example_file" "$env_file"
            print_message $GREEN "✅ 创建前端环境配置: $env_file"
        else
            print_message $YELLOW "⚠️  前端配置模板不存在: $example_file"
        fi
    else
        print_message $GREEN "✅ 前端环境配置已存在: $env_file"
    fi
    
    # 根据环境类型更新配置
    if [ -f "$env_file" ]; then
        case $ENV_TYPE in
            development)
                sed -i.bak 's/VITE_APP_TITLE=.*/VITE_APP_TITLE=考培练系统（开发）/' "$env_file"
                sed -i.bak 's/VITE_APP_ENV=.*/VITE_APP_ENV=development/' "$env_file"
                sed -i.bak 's/VITE_API_BASE_URL=.*/VITE_API_BASE_URL=http:\/\/localhost:8000/' "$env_file"
                sed -i.bak 's/VITE_ENABLE_DEVTOOLS=.*/VITE_ENABLE_DEVTOOLS=true/' "$env_file"
                rm -f "$env_file.bak"
                ;;
            production)
                sed -i.bak 's/VITE_APP_TITLE=.*/VITE_APP_TITLE=考培练系统/' "$env_file"
                sed -i.bak 's/VITE_APP_ENV=.*/VITE_APP_ENV=production/' "$env_file"
                sed -i.bak 's/VITE_API_BASE_URL=.*/VITE_API_BASE_URL=https:\/\/aiedu.ireborn.com.cn/' "$env_file"
                sed -i.bak 's/VITE_ENABLE_DEVTOOLS=.*/VITE_ENABLE_DEVTOOLS=false/' "$env_file"
                rm -f "$env_file.bak"
                ;;
        esac
        print_message $GREEN "✅ 前端环境配置已更新"
    fi
}

# 设置后端环境
setup_backend_env() {
    print_message $BLUE "设置后端环境配置..."
    
    local env_file="kaopeilian-backend/.env.$ENV_TYPE"
    local example_file="kaopeilian-backend/.env.example"
    
    if [ ! -f "$env_file" ] || [ "$FORCE_SETUP" = "true" ]; then
        if [ -f "$example_file" ]; then
            cp "$example_file" "$env_file"
            print_message $GREEN "✅ 创建后端环境配置: $env_file"
        else
            print_message $YELLOW "⚠️  后端配置模板不存在: $example_file"
        fi
    else
        print_message $GREEN "✅ 后端环境配置已存在: $env_file"
    fi
    
    # 根据环境类型更新配置
    if [ -f "$env_file" ]; then
        case $ENV_TYPE in
            development)
                sed -i.bak 's/ENV=.*/ENV=development/' "$env_file"
                sed -i.bak 's/DEBUG=.*/DEBUG=true/' "$env_file"
                sed -i.bak 's/DATABASE_URL=.*/DATABASE_URL=mysql+aiomysql:\/\/root:Kaopeilian2025!@#@localhost:3306\/kaopeilian?charset=utf8mb4/' "$env_file"
                sed -i.bak 's/MYSQL_HOST=.*/MYSQL_HOST=localhost/' "$env_file"
                rm -f "$env_file.bak"
                ;;
            production)
                sed -i.bak 's/ENV=.*/ENV=production/' "$env_file"
                sed -i.bak 's/DEBUG=.*/DEBUG=false/' "$env_file"
                sed -i.bak 's/DATABASE_URL=.*/DATABASE_URL=mysql+aiomysql:\/\/root:Kaopeilian2025!@#@mysql:3306\/kaopeilian?charset=utf8mb4/' "$env_file"
                sed -i.bak 's/MYSQL_HOST=.*/MYSQL_HOST=mysql/' "$env_file"
                rm -f "$env_file.bak"
                ;;
        esac
        print_message $GREEN "✅ 后端环境配置已更新"
    fi
}

# 设置Docker环境
setup_docker_env() {
    print_message $BLUE "设置Docker环境..."
    
    case $ENV_TYPE in
        development)
            if [ ! -f "docker-compose.dev.yml" ]; then
                print_message $RED "❌ 开发环境Docker配置不存在: docker-compose.dev.yml"
                return 1
            fi
            print_message $GREEN "✅ 开发环境Docker配置已就绪"
            ;;
        production)
            if [ ! -f "docker-compose.yml" ]; then
                print_message $RED "❌ 生产环境Docker配置不存在: docker-compose.yml"
                return 1
            fi
            print_message $GREEN "✅ 生产环境Docker配置已就绪"
            ;;
    esac
}

# 启动环境
start_environment() {
    print_message $BLUE "启动$ENV_TYPE环境..."
    
    case $ENV_TYPE in
        development)
            if command -v docker-compose &> /dev/null; then
                docker-compose -f docker-compose.dev.yml up -d
            else
                docker compose -f docker-compose.dev.yml up -d
            fi
            ;;
        production)
            if command -v docker-compose &> /dev/null; then
                docker-compose up -d
            else
                docker compose up -d
            fi
            ;;
    esac
    
    if [ $? -eq 0 ]; then
        print_message $GREEN "✅ 环境启动成功"
        
        # 等待服务启动
        print_message $BLUE "等待服务启动..."
        sleep 10
        
        # 检查服务状态
        ./scripts/check_environment.sh
    else
        print_message $RED "❌ 环境启动失败"
        return 1
    fi
}

# 显示使用说明
show_usage() {
    echo "用法: $0 [环境类型] [强制设置]"
    echo ""
    echo "环境类型:"
    echo "  development  - 开发环境 (默认)"
    echo "  production   - 生产环境"
    echo ""
    echo "强制设置:"
    echo "  true         - 强制重新创建配置文件"
    echo "  false        - 保留已存在的配置文件 (默认)"
    echo ""
    echo "示例:"
    echo "  $0                           # 设置开发环境"
    echo "  $0 development               # 设置开发环境"
    echo "  $0 production                # 设置生产环境"
    echo "  $0 development true          # 强制重新设置开发环境"
}

# 主函数
main() {
    if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
        show_usage
        exit 0
    fi
    
    if [ "$ENV_TYPE" != "development" ] && [ "$ENV_TYPE" != "production" ]; then
        print_message $RED "❌ 无效的环境类型: $ENV_TYPE"
        show_usage
        exit 1
    fi
    
    check_requirements
    setup_frontend_env
    setup_backend_env
    setup_docker_env
    
    # 询问是否启动环境
    read -p "是否启动$ENV_TYPE环境? [y/N]: " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        start_environment
    fi
    
    print_message $GREEN "=== 环境设置完成 ==="
    print_message $BLUE "环境类型: $ENV_TYPE"
    print_message $BLUE "前端地址: http://localhost:3001"
    print_message $BLUE "后端地址: http://localhost:8000"
    print_message $BLUE "API文档: http://localhost:8000/docs"
}

main "$@"
