#!/bin/bash

# Paper Burner X - 启动脚本

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

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
BACKEND_PORT=3456
FRONTEND_PORT=8080
PID_DIR="$PROJECT_DIR/.pids"

echo -e "${BLUE}"
echo "======================================"
echo "   Paper Burner X - 启动脚本"
echo "======================================"
echo -e "${NC}"

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

# 函数：根据端口查找并杀死进程
kill_port() {
    local port=$1
    local pids=$(lsof -t -i:$port 2>/dev/null)
    if [ -n "$pids" ]; then
        echo -e "${YELLOW}→ 发现端口 $port 被占用，正在终止进程...${NC}"
        for pid in $pids; do
            kill -9 $pid 2>/dev/null && echo -e "  ${GREEN}已终止进程 $pid${NC}"
        done
        sleep 1
    fi
}

# 函数：根据 PID 文件杀死进程
kill_pid_file() {
    local pid_file=$1
    local service_name=$2
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if [ -n "$pid" ] && kill -0 $pid 2>/dev/null; then
            echo -e "${YELLOW}→ 终止 $service_name (PID: $pid)...${NC}"
            kill -9 $pid 2>/dev/null
            echo -e "  ${GREEN}已终止${NC}"
        fi
        rm -f "$pid_file"
    fi
}

# 1. 清除之前的进程
echo -e "${YELLOW}[1/3] 清除之前的进程...${NC}"

# 通过 PID 文件清理
kill_pid_file "$PID_DIR/backend.pid" "后端服务"
kill_pid_file "$PID_DIR/frontend.pid" "前端服务"

# 通过端口清理（确保彻底）
kill_port $BACKEND_PORT
kill_port $FRONTEND_PORT

echo -e "${GREEN}✓ 进程清理完成${NC}"
echo ""

# 2. 启动后端
echo -e "${YELLOW}[2/3] 启动后端服务 (端口 $BACKEND_PORT)...${NC}"
cd "$PROJECT_DIR/local-proxy"

# 检查 node_modules
if [ ! -d "node_modules" ]; then
    echo -e "${YELLOW}→ 安装后端依赖...${NC}"
    npm install
fi

# 后台启动后端（输出同时显示在控制台和日志文件）
npm start 2>&1 | tee "$PROJECT_DIR/logs/backend.log" &
BACKEND_PID=$!
echo $BACKEND_PID > "$PID_DIR/backend.pid"
echo -e "${GREEN}✓ 后端已启动 (PID: $BACKEND_PID)${NC}"
echo -e "  日志: $PROJECT_DIR/logs/backend.log"
echo ""

# 3. 启动前端
echo -e "${YELLOW}[3/3] 启动前端服务 (端口 $FRONTEND_PORT)...${NC}"
cd "$PROJECT_DIR"

# 后台启动前端（输出同时显示在控制台和日志文件）
npx serve -p $FRONTEND_PORT 2>&1 | tee "$PROJECT_DIR/logs/frontend.log" &
FRONTEND_PID=$!
echo $FRONTEND_PID > "$PID_DIR/frontend.pid"
echo -e "${GREEN}✓ 前端已启动 (PID: $FRONTEND_PID)${NC}"
echo -e "  日志: $PROJECT_DIR/logs/frontend.log"
echo ""

# 等待服务启动
sleep 2

# 检查服务状态
echo -e "${YELLOW}→ 检查服务状态...${NC}"

BACKEND_OK=false
FRONTEND_OK=false

# 检查后端
if curl -s "http://localhost:$BACKEND_PORT/health" > /dev/null 2>&1; then
    BACKEND_OK=true
    echo -e "  ${GREEN}✓ 后端服务正常${NC}"
else
    echo -e "  ${RED}✗ 后端服务启动中...${NC}"
fi

# 检查前端
if curl -s "http://localhost:$FRONTEND_PORT" > /dev/null 2>&1; then
    FRONTEND_OK=true
    echo -e "  ${GREEN}✓ 前端服务正常${NC}"
else
    echo -e "  ${RED}✗ 前端服务启动中...${NC}"
fi

echo ""
echo -e "${GREEN}"
echo "======================================"
echo "   启动完成！"
echo "======================================"
echo -e "${NC}"
echo ""
echo -e "${BLUE}访问地址：${NC}"
echo -e "  前端:    ${GREEN}http://localhost:$FRONTEND_PORT${NC}"
echo -e "  后端:    ${GREEN}http://localhost:$BACKEND_PORT${NC}"
echo -e "  健康检查: ${GREEN}http://localhost:$BACKEND_PORT/health${NC}"
echo ""
echo -e "${BLUE}日志文件：${NC}"
echo -e "  后端: $PROJECT_DIR/logs/backend.log"
echo -e "  前端: $PROJECT_DIR/logs/frontend.log"
echo ""
echo -e "${BLUE}停止服务：${NC}"
echo -e "  运行: ${YELLOW}./stop.sh${NC} 或手动终止进程"
echo ""