#!/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=5173
PID_DIR="$PROJECT_DIR/.pids"

echo -e "${BLUE}"
echo "======================================"
echo "   Paper Burner X - 停止脚本"
echo "======================================"
echo -e "${NC}"

# 函数：根据端口查找并杀死进程
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 -15 $pid 2>/dev/null
            if kill -0 $pid 2>/dev/null; then
                sleep 1
                kill -9 $pid 2>/dev/null
            fi
            echo -e "  ${GREEN}已终止进程 $pid${NC}"
        done
        return 0
    else
        return 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 -15 $pid 2>/dev/null
            # 等待进程退出
            local count=0
            while kill -0 $pid 2>/dev/null && [ $count -lt 5 ]; do
                sleep 0.5
                count=$((count + 1))
            done
            # 如果进程还在，强制终止
            if kill -0 $pid 2>/dev/null; then
                kill -9 $pid 2>/dev/null
            fi
            echo -e "  ${GREEN}已终止${NC}"
        fi
        rm -f "$pid_file"
    fi
}

STOPPED_SOMETHING=false

# 1. 通过 PID 文件停止
echo -e "${YELLOW}[1/2] 通过 PID 文件停止服务...${NC}"

if [ -f "$PID_DIR/backend.pid" ]; then
    kill_pid_file "$PID_DIR/backend.pid" "后端服务"
    STOPPED_SOMETHING=true
fi

if [ -f "$PID_DIR/frontend.pid" ]; then
    kill_pid_file "$PID_DIR/frontend.pid" "前端服务"
    STOPPED_SOMETHING=true
fi

# 2. 通过端口确保彻底清理
echo -e "${YELLOW}[2/2] 确保端口已释放...${NC}"

if kill_port $BACKEND_PORT; then
    STOPPED_SOMETHING=true
else
    echo -e "  ${GREEN}端口 $BACKEND_PORT 已空闲${NC}"
fi

if kill_port $FRONTEND_PORT; then
    STOPPED_SOMETHING=true
else
    echo -e "  ${GREEN}端口 $FRONTEND_PORT 已空闲${NC}"
fi

echo ""
if [ "$STOPPED_SOMETHING" = true ]; then
    echo -e "${GREEN}"
    echo "======================================"
    echo "   服务已停止"
    echo "======================================"
    echo -e "${NC}"
else
    echo -e "${YELLOW}"
    echo "======================================"
    echo "   没有运行中的服务"
    echo "======================================"
    echo -e "${NC}"
fi