#!/bin/bash

# AI Chat 生产环境部署脚本
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"
}

# 检查必要的工具
check_requirements() {
    log_info "检查部署环境..."
    
    if ! command -v docker &> /dev/null; then
        log_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
    
    log_success "环境检查通过"
}

# 创建必要的目录
create_directories() {
    log_info "创建必要的目录..."
    
    mkdir -p logs/nginx
    mkdir -p logs/proxy
    mkdir -p ssl
    mkdir -p backups
    
    log_success "目录创建完成"
}

# 备份当前部署
backup_current() {
    if [ -d "dist" ]; then
        log_info "备份当前部署..."
        timestamp=$(date +%Y%m%d_%H%M%S)
        tar -czf "backups/backup_${timestamp}.tar.gz" dist/ logs/ 2>/dev/null || true
        log_success "备份完成: backups/backup_${timestamp}.tar.gz"
    fi
}

# 构建应用
build_app() {
    log_info "构建应用..."
    
    if [ ! -f "package.json" ]; then
        log_error "package.json 不存在，请确保在项目根目录运行此脚本"
        exit 1
    fi
    
    # 检查是否有pnpm
    if command -v pnpm &> /dev/null; then
        log_info "使用 pnpm 安装依赖..."
        pnpm install --frozen-lockfile
        pnpm run build:h5
    elif command -v npm &> /dev/null; then
        log_info "使用 npm 安装依赖..."
        npm ci
        npm run build:h5
    else
        log_error "未找到 npm 或 pnpm"
        exit 1
    fi
    
    if [ ! -d "dist" ]; then
        log_error "构建失败，dist 目录不存在"
        exit 1
    fi
    
    log_success "应用构建完成"
}

# 部署应用
deploy_app() {
    local mode=$1
    
    log_info "开始部署应用 (模式: $mode)..."
    
    case $mode in
        "basic")
            docker-compose -f docker-compose.prod.yml down 2>/dev/null || true
            docker-compose -f docker-compose.prod.yml up -d --build
            ;;
        "https")
            if [ ! -f "ssl/fullchain.pem" ] || [ ! -f "ssl/privkey.pem" ]; then
                log_warning "SSL证书不存在，请先配置SSL证书"
                log_info "将使用基础模式部署..."
                docker-compose -f docker-compose.prod.yml down 2>/dev/null || true
                docker-compose -f docker-compose.prod.yml up -d --build
            else
                docker-compose -f docker-compose.prod.yml --profile https down 2>/dev/null || true
                docker-compose -f docker-compose.prod.yml --profile https up -d --build
            fi
            ;;
        "monitoring")
            docker-compose -f docker-compose.prod.yml --profile monitoring down 2>/dev/null || true
            docker-compose -f docker-compose.prod.yml --profile monitoring up -d --build
            ;;
        *)
            log_error "未知的部署模式: $mode"
            exit 1
            ;;
    esac
    
    log_success "应用部署完成"
}

# 等待服务启动
wait_for_service() {
    log_info "等待服务启动..."
    
    local max_attempts=30
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if curl -s http://localhost/health > /dev/null 2>&1; then
            log_success "服务启动成功"
            return 0
        fi
        
        log_info "等待服务启动... ($attempt/$max_attempts)"
        sleep 2
        ((attempt++))
    done
    
    log_warning "服务启动超时，请检查日志"
    return 1
}

# 显示部署信息
show_deployment_info() {
    log_success "🎉 部署完成！"
    echo ""
    echo "📋 部署信息:"
    echo "  - 访问地址: http://localhost"
    echo "  - 健康检查: http://localhost/health"
    echo "  - 日志目录: ./logs/"
    echo ""
    echo "🔧 管理命令:"
    echo "  - 查看状态: docker-compose -f docker-compose.prod.yml ps"
    echo "  - 查看日志: docker-compose -f docker-compose.prod.yml logs -f"
    echo "  - 停止服务: docker-compose -f docker-compose.prod.yml down"
    echo "  - 重启服务: docker-compose -f docker-compose.prod.yml restart"
    echo ""
    echo "📊 监控:"
    echo "  - 容器状态: docker stats"
    echo "  - 系统资源: htop"
    echo ""
}

# 主函数
main() {
    echo "🚀 AI Chat 生产环境部署脚本"
    echo "================================"
    
    # 检查参数
    if [ $# -eq 0 ]; then
        echo "请选择部署模式："
        echo "1) 基础模式 (HTTP)"
        echo "2) HTTPS模式"
        echo "3) 监控模式"
        echo "4) 仅构建"
        echo ""
        read -p "请输入选择 (1-4): " choice
        
        case $choice in
            1) MODE="basic" ;;
            2) MODE="https" ;;
            3) MODE="monitoring" ;;
            4) MODE="build-only" ;;
            *) log_error "无效选择"; exit 1 ;;
        esac
    else
        MODE=$1
    fi
    
    # 执行部署步骤
    check_requirements
    create_directories
    backup_current
    build_app
    
    if [ "$MODE" != "build-only" ]; then
        deploy_app $MODE
        wait_for_service
        show_deployment_info
    else
        log_success "构建完成，跳过部署"
    fi
}

# 运行主函数
main "$@"
