#!/bin/bash

SERVICES=("PyBot" "PyBot_Web")

echo "=============================="
echo "开始卸载 PyBot 系统服务"
echo "=============================="

# 检查是否以 root 权限运行（部分操作需要）
if [ "$EUID" -ne 0 ]; then
    echo "⚠️  某些操作可能需要 sudo 权限"
fi

for SERVICE in "${SERVICES[@]}"; do
    echo ""
    echo ">>> 处理服务: $SERVICE"

    # 1. 停止服务
    if systemctl is-active --quiet $SERVICE; then
        echo "停止服务..."
        sudo systemctl stop $SERVICE
        sleep 2  # 等待服务完全停止
    else
        echo "服务未运行"
    fi

    # 2. 禁用开机自启
    if systemctl is-enabled --quiet $SERVICE 2>/dev/null; then
        echo "取消开机自启..."
        sudo systemctl disable $SERVICE
    else
        echo "未启用开机自启"
    fi

    # 3. 删除 service 文件
    SERVICE_FILE="/etc/systemd/system/${SERVICE}.service"
    if [ -f "$SERVICE_FILE" ]; then
        echo "删除服务文件: $SERVICE_FILE"
        sudo rm -f "$SERVICE_FILE"
    else
        echo "未找到服务文件"
    fi

    # 4. 杀残留进程（更精确的匹配）
    echo "检查残留进程..."
    # 使用更精确的进程匹配方式，避免误杀其他进程
    PIDS=$(pgrep -f "${SERVICE}\.py" 2>/dev/null || pgrep -f "python.*${SERVICE}" 2>/dev/null)
    if [ -n "$PIDS" ]; then
        echo "杀死残留进程: $PIDS"
        sudo kill -15 $PIDS 2>/dev/null  # 先尝试正常终止
        sleep 2
        # 如果进程仍然存在，强制终止
        if ps -p $PIDS > /dev/null; then
            sudo kill -9 $PIDS 2>/dev/null
        fi
    else
        echo "无残留进程"
    fi

done

# 5. 重载 systemd
echo ""
echo "重新加载 systemd..."
sudo systemctl daemon-reload
sudo systemctl daemon-reexec

# 6. 可选清理日志和数据
echo ""
read -p "是否清理 PyBot 日志文件？(y/n): " CLEAN_LOG
if [ "$CLEAN_LOG" == "y" ] || [ "$CLEAN_LOG" == "Y" ]; then
    echo "清理应用日志..."
    rm -f ./resources/log/core.log
    rm -f ./resources/log/app.log
    echo "清理 journal 日志（保留1天）..."
    sudo journalctl --vacuum-time=1d 2>/dev/null || echo "journalctl 清理跳过（可能无权限）"
fi

read -p "是否清理历史数据和缓存？(y/n): " CLEAN_DATA
if [ "$CLEAN_DATA" == "y" ] || [ "$CLEAN_DATA" == "Y" ]; then
    echo "清理历史数据..."
    rm -f ./resources/history/*.md
    rm -f ./resources/JSON/*.json
    echo "注意：配置文件已保留，如需删除请手动操作 config/ 目录"
fi

# 7. 可选：询问是否删除虚拟环境（如果存在）
if [ -d "venv" ] || [ -d ".venv" ]; then
    read -p "是否删除 Python 虚拟环境？(y/n): " CLEAN_VENV
    if [ "$CLEAN_VENV" == "y" ] || [ "$CLEAN_VENV" == "Y" ]; then
        echo "删除虚拟环境..."
        rm -rf venv .venv
    fi
fi

echo ""
echo "=============================="
echo "卸载完成 ✅"
echo "=============================="
echo ""
echo "📝 提示："
echo "  - 配置文件保留在 config/ 目录"
echo "  - 如需完全删除项目，请手动删除整个项目文件夹"
echo "  - Python 依赖包未卸载，如需要可运行: pip uninstall -r requirements.txt"
echo ""

# 8. 验证
for SERVICE in "${SERVICES[@]}"; do
    echo "验证服务: $SERVICE"
    if systemctl status $SERVICE 2>&1 | grep -q "could not be found"; then
        echo "  ✔ 服务已彻底删除"
    else
        echo "  ⚠ 服务可能仍存在，请检查"
    fi
done

echo ""
echo "感谢使用 PyBot！👋"