#!/bin/bash
# HZHub Admin 前端项目启动脚本
# 功能：后台启动 hzhub-admin 前端开发服务器

PROJECT_NAME="hzhub-admin"
PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
PID_FILE="$PROJECT_DIR/.pid"
LOG_FILE="$PROJECT_DIR/logs/dev.log"

# 创建日志目录
mkdir -p "$PROJECT_DIR/logs"

echo "========================================="
echo "启动 $PROJECT_NAME 开发服务器"
echo "========================================="

# 检查是否已经在运行
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p "$PID" > /dev/null 2>&1; then
        echo "⚠️  服务已在运行中 (PID: $PID)"
        echo "如需重启，请先执行 ./stop.sh"
        exit 1
    else
        echo "清理无效的PID文件"
        rm -f "$PID_FILE"
    fi
fi

# 启动服务
echo "🚀 启动开发服务器..."
cd "$PROJECT_DIR"

# 使用nohup后台运行pnpm dev
nohup pnpm dev > "$LOG_FILE" 2>&1 &
PID=$!

# 等待一秒检查进程是否成功启动
sleep 2
if ps -p "$PID" > /dev/null 2>&1; then
    echo "$PID" > "$PID_FILE"
    echo "✅ 服务启动成功"
    echo "   PID: $PID"
    echo "   日志: $LOG_FILE"
    echo "   访问: http://localhost:5666"
    echo ""
    echo "查看日志: tail -f $LOG_FILE"
    echo "查看状态: ./status.sh"
else
    echo "❌ 服务启动失败"
    echo "请查看日志: $LOG_FILE"
    exit 1
fi