#!/usr/bin/env bash
# ZP2 Startup Script for macOS/Linux / ZP2 macOS/Linux 启动脚本

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
BACKEND_DIR="$PROJECT_DIR/backend"
FRONTEND_DIR="$PROJECT_DIR/frontend"

# Colors / 颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info()  { echo -e "${GREEN}[INFO]${NC}  $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check prerequisites / 检查依赖
check_prereqs() {
    info "Checking prerequisites / 检查依赖..."

    if ! command -v java &>/dev/null; then
        error "Java not found. Please install Java 17+. / 未找到 Java，请安装 Java 17+。"
        exit 1
    fi

    JAVA_VER=$(java -version 2>&1 | head -1 | cut -d'"' -f2 | cut -d'.' -f1)
    if [ "$JAVA_VER" -lt 17 ]; then
        error "Java 17+ required, found Java $JAVA_VER / 需要 Java 17+，当前为 Java $JAVA_VER"
        exit 1
    fi
    info "Java $JAVA_VER OK"

    if ! command -v mvn &>/dev/null; then
        error "Maven not found. Please install Maven. / 未找到 Maven，请安装 Maven。"
        exit 1
    fi
    info "Maven OK"

    if ! command -v node &>/dev/null; then
        error "Node.js not found. Please install Node.js. / 未找到 Node.js，请安装 Node.js。"
        exit 1
    fi
    info "Node.js $(node -v) OK"
}

# Build backend / 构建后端
build_backend() {
    info "Building backend / 构建后端..."
    cd "$BACKEND_DIR"
    mvn package -q
    info "Backend built successfully / 后端构建成功"
}

# Start backend / 启动后端
start_backend() {
    info "Starting backend server on port 8080 / 启动后端服务器 (端口 8080)..."
    cd "$PROJECT_DIR"
    nohup java -jar backend/target/zombie-crisis-server-1.0.0.jar > "$PROJECT_DIR/backend.log" 2>&1 &
    BACKEND_PID=$!
    echo "$BACKEND_PID" > "$PROJECT_DIR/.backend.pid"
    info "Backend started (PID: $BACKEND_PID) / 后端已启动 (PID: $BACKEND_PID)"
}

# Start frontend / 启动前端
start_frontend() {
    info "Starting frontend dev server / 启动前端开发服务器..."
    cd "$FRONTEND_DIR"

    if [ ! -d "node_modules" ]; then
        info "Installing frontend dependencies / 安装前端依赖..."
        npm install
    fi

    info "Frontend dev server starting at http://localhost:3000 / 前端开发服务器地址: http://localhost:3000"
    npm run dev
}

# Handle Ctrl+C / 处理 Ctrl+C
cleanup() {
    if [ -f "$PROJECT_DIR/.backend.pid" ]; then
        PID=$(cat "$PROJECT_DIR/.backend.pid")
        info "Stopping backend (PID: $PID) / 停止后端 (PID: $PID)..."
        kill "$PID" 2>/dev/null || true
        rm -f "$PROJECT_DIR/.backend.pid"
    fi
    exit 0
}

trap cleanup INT TERM

# Main / 主流程
echo "=================================="
echo "  ZP2 Game Server Launcher"
echo "  ZP2 游戏服务器启动器"
echo "=================================="
echo ""

check_prereqs
build_backend
start_backend
start_frontend
