#!/bin/bash

# 一键启动所有服务并执行测试脚本
# 作者: 张翔
# 日期: 2026-04-15

set -e

echo "=========================================="
echo "企业级后台管理系统 - 一键启动与测试"
echo "=========================================="
echo "作者: 张翔 (全栈质量保障与效能工程师)"
echo "日期: 2026-04-15"
echo "原则: 质量是设计出来的，并通过自动化流水线保障"
echo "=========================================="
echo ""

# 颜色定义
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_dependencies() {
    log_info "检查系统依赖..."
    
    local missing_deps=()
    
    # 检查Docker
    if ! command -v docker &> /dev/null; then
        missing_deps+=("Docker")
    fi
    
    # 检查docker-compose
    if ! command -v docker-compose &> /dev/null; then
        missing_deps+=("docker-compose")
    fi
    
    # 检查Java
    if ! command -v java &> /dev/null; then
        missing_deps+=("Java (JDK 21+)")
    fi
    
    # 检查Maven
    if ! command -v mvn &> /dev/null; then
        missing_deps+=("Maven 3.8+")
    fi
    
    # 检查Node.js
    if ! command -v node &> /dev/null; then
        missing_deps+=("Node.js 18+")
    fi
    
    # 检查包管理器
    if ! command -v pnpm &> /dev/null && ! command -v npm &> /dev/null; then
        missing_deps+=("包管理器 (pnpm 或 npm)")
    fi
    
    if [ ${#missing_deps[@]} -gt 0 ]; then
        log_error "缺少以下依赖:"
        for dep in "${missing_deps[@]}"; do
            echo "  - $dep"
        done
        echo ""
        echo "请参考项目README安装依赖:"
        echo "  https://github.com/your-repo/novalon-manage-system#环境准备要求"
        exit 1
    fi
    
    log_success "所有依赖检查通过"
}

# 显示服务信息
show_service_info() {
    echo ""
    echo "=========================================="
    echo "服务启动信息"
    echo "=========================================="
    echo ""
    echo "📊 数据库服务"
    echo "   地址: localhost:55432"
    echo "   数据库: manage_system"
    echo "   用户名: novalon"
    echo "   密码: novalon123"
    echo ""
    echo "⚙️  后端服务"
    echo "   网关: http://localhost:8080"
    echo "   应用: http://localhost:8084"
    echo "   API文档: http://localhost:8084/swagger-ui.html"
    echo "   健康检查: http://localhost:8084/actuator/health"
    echo ""
    echo "🎨 前端服务"
    echo "   应用: http://localhost:3000"
    echo "   API代理: http://localhost:3000/api → http://localhost:8080/api"
    echo ""
    echo "🧪 测试信息"
    echo "   测试类型: 冒烟测试 (登录登出)"
    echo "   测试账号: admin/Test@123"
    echo "   测试报告: novalon-manage-web/playwright-report/"
    echo ""
    echo "=========================================="
}

# 主函数
main() {
    log_info "开始启动所有服务..."
    
    # 检查依赖
    check_dependencies
    
    # 步骤1: 启动数据库
    log_info "步骤1: 启动数据库容器..."
    if ./scripts/start-database.sh; then
        log_success "数据库启动成功"
    else
        log_error "数据库启动失败"
        exit 1
    fi
    
    echo ""
    log_info "步骤2: 启动后端服务..."
    echo "注意: 后端服务将在当前终端启动，请勿关闭此终端"
    echo "      按 Ctrl+C 可停止后端服务"
    echo ""
    read -p "是否继续启动后端服务? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_warning "用户取消启动后端服务"
        exit 0
    fi
    
    # 步骤2: 启动后端服务 (在新终端中)
    log_info "正在启动后端服务 (网关:8080 + 应用:8084)..."
    echo "启动命令: ./scripts/start-backend.sh"
    echo ""
    log_warning "请在新终端中执行以下命令:"
    echo "cd $(pwd)"
    echo "./scripts/start-backend.sh"
    echo ""
    read -p "是否已在新终端中启动后端服务? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_warning "请先启动后端服务"
        exit 1
    fi
    
    # 等待后端服务启动
    log_info "等待后端服务启动..."
    for i in {1..60}; do
        if curl -s http://localhost:8084/actuator/health | grep -q '"status":"UP"'; then
            log_success "后端服务启动成功"
            break
        fi
        echo "等待后端服务... ($i/60)"
        sleep 2
    done
    
    # 验证后端服务
    if ! curl -s http://localhost:8084/actuator/health | grep -q '"status":"UP"'; then
        log_error "后端服务启动超时"
        exit 1
    fi
    
    echo ""
    log_info "步骤3: 启动前端服务..."
    echo "注意: 前端服务将在新终端中启动"
    echo ""
    read -p "是否继续启动前端服务? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_warning "用户取消启动前端服务"
        exit 0
    fi
    
    # 步骤3: 启动前端服务 (在新终端中)
    log_info "正在启动前端开发服务器 (端口:3000)..."
    echo "启动命令: ./scripts/start-frontend.sh"
    echo ""
    log_warning "请在新终端中执行以下命令:"
    echo "cd $(pwd)"
    echo "./scripts/start-frontend.sh"
    echo ""
    read -p "是否已在新终端中启动前端服务? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_warning "请先启动前端服务"
        exit 1
    fi
    
    # 等待前端服务启动
    log_info "等待前端服务启动..."
    sleep 5
    
    echo ""
    log_info "步骤4: 执行用户旅程测试..."
    echo ""
    read -p "是否执行E2E冒烟测试? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_warning "用户取消执行测试"
        show_service_info
        exit 0
    fi
    
    # 步骤4: 执行E2E测试
    log_info "执行冒烟测试..."
    if ./scripts/run-e2e-tests.sh; then
        log_success "测试执行完成"
    else
        log_error "测试执行失败"
        exit 1
    fi
    
    # 显示服务信息
    show_service_info
    
    log_success "所有服务启动并测试完成！"
    echo ""
    echo "🎉 系统已就绪，可以开始使用！"
    echo ""
    echo "访问地址:"
    echo "  前端应用: http://localhost:3000"
    echo "  API文档: http://localhost:8084/swagger-ui.html"
    echo ""
    echo "测试账号:"
    echo "  管理员: admin / Test@123"
    echo "  普通用户: user / Test@123"
}

# 执行主函数
main "$@"