#!/bin/bash

# 获取当前目录
BASE_DIR=$(cd "$(dirname "$0")"; pwd)
USER_NAME=$(whoami)

echo "项目路径: $BASE_DIR"

# ========= 自动检测 Python =========
detect_python() {
    if command -v python >/dev/null 2>&1; then
        PY=python
    elif command -v python3 >/dev/null 2>&1; then
        PY=python3
    else
        echo "❌ 未检测到 Python，请先安装 Python 3.6+"
        exit 1
    fi

    # 获取版本号
    VERSION=$($PY -c 'import sys; print(".".join(map(str, sys.version_info[:3])))')

    echo "检测到 Python: $PY ($VERSION)"

    # 校验版本 >= 3.6
    MAJOR=$(echo $VERSION | cut -d. -f1)
    MINOR=$(echo $VERSION | cut -d. -f2)

    if [ "$MAJOR" -lt 3 ] || { [ "$MAJOR" -eq 3 ] && [ "$MINOR" -lt 6 ]; }; then
        echo "❌ Python 版本过低（需要 >= 3.6）"
        exit 1
    fi

    PYTHON_CMD=$PY
}

detect_python

# ========= 检查 pip 是否可用 =========
if ! $PYTHON_CMD -m pip --version >/dev/null 2>&1; then
    echo "❌ pip 未安装或不可用，请先安装 pip"
    exit 1
fi

# ========= 安装依赖 =========
if [ -f "$BASE_DIR/requirements.txt" ]; then
    echo "安装 Python 依赖..."
    # 升级 pip 到最新版本
    $PYTHON_CMD -m pip install --upgrade pip
    $PYTHON_CMD -m pip install -r "$BASE_DIR/requirements.txt"
else
    echo "⚠️ 未找到 requirements.txt，跳过依赖安装"
fi

# ========= 创建必要的目录结构 =========
mkdir -p "$BASE_DIR/resources/log"
mkdir -p "$BASE_DIR/resources/history"
mkdir -p "$BASE_DIR/resources/db"

# ========= 创建 PyBot 服务 =========
sudo bash -c "cat > /etc/systemd/system/PyBot.service" <<EOF
[Unit]
Description=PyBot Core Service
After=network.target

[Service]
Type=simple
User=$USER_NAME
WorkingDirectory=$BASE_DIR
ExecStart=$PYTHON_CMD $BASE_DIR/Core.py
Restart=always
RestartSec=3
StartLimitInterval=0
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
EOF

# ========= 创建 PyBot_Web 服务 =========
sudo bash -c "cat > /etc/systemd/system/PyBot_Web.service" <<EOF
[Unit]
Description=PyBot Web Service
After=network.target

[Service]
Type=simple
User=$USER_NAME
WorkingDirectory=$BASE_DIR
ExecStart=$PYTHON_CMD $BASE_DIR/web/app.py
Restart=always
RestartSec=3
StartLimitInterval=0
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
EOF

# ========= 重新加载 =========
sudo systemctl daemon-reexec
sudo systemctl daemon-reload

# ========= 启用 + 启动 =========
sudo systemctl enable PyBot
sudo systemctl enable PyBot_Web

sudo systemctl restart PyBot
sudo systemctl restart PyBot_Web

echo "===================================="
echo "✅ 服务已创建并启动"
echo "PyBot        → core.py"
echo "PyBot_Web    → web/app.py"
echo "Web服务已于本地9801端口启动，请使用反向代理创建网站"
echo "===================================="