#!/bin/bash
# YG_FT_Base 虚拟环境创建脚本 (Linux/Mac/WSL)
# 使用方法: bash create_venv.sh 或 ./create_venv.sh

# 自动修复脚本换行符（如果是从 Windows 传来的文件）
if grep -q $'\r' "$0"; then
    echo "检测到 Windows 换行符，自动修复中..."
    sed -i 's/\r$//' "$0"
    echo "修复完成，重新执行脚本..."
    exec "$0"
fi

echo "===================================="
echo "YG_FT_Base 虚拟环境创建脚本"
echo "===================================="
echo ""

# 设置虚拟环境名称
VENV_NAME="B_venv"

# 检查 Python 版本
echo "检查 Python 版本..."
if command -v python3 &> /dev/null; then
    PYTHON_CMD="python3"
    python3 --version
elif command -v python &> /dev/null; then
    PYTHON_CMD="python"
    python --version
else
    echo "错误: 未找到 Python！请先安装 Python 3.10 或更高版本。"
    exit 1
fi

# 检查并安装 python3-venv（仅限 Debian/Ubuntu 系统）
echo ""
echo "检查 python3-venv..."
if [ -f /etc/debian_version ]; then
    echo "检测到 Debian/Ubuntu 系统"
    if ! dpkg -l | grep -q python3-venv; then
        echo "python3-venv 未安装，尝试安装..."
        if [ -x "$(command -v apt)" ]; then
            apt update && apt install -y python3-venv python3-pip
            if [ $? -ne 0 ]; then
                echo "警告: 安装 python3-venv 失败，请手动运行："
                echo "  apt install python3-venv python3-pip"
                echo "然后重新运行此脚本。"
                exit 1
            fi
            echo "python3-venv 安装成功！"
        else
            echo "错误: 未找到 apt 包管理器，请手动安装 python3-venv。"
            exit 1
        fi
    else
        echo "python3-venv 已安装。"
    fi
elif [ -f /etc/redhat-release ]; then
    echo "检测到 RedHat/CentOS/Fedora 系统"
    if ! rpm -qa | grep -q python3-virtualenv; then
        echo "python3-virtualenv 未安装，尝试安装..."
        if [ -x "$(command -v yum)" ]; then
            yum install -y python3-virtualenv python3-pip
        elif [ -x "$(command -v dnf)" ]; then
            dnf install -y python3-virtualenv python3-pip
        fi
    fi
fi

# 检查是否已存在虚拟环境
if [ -d "$VENV_NAME" ]; then
    echo "警告: 虚拟环境 '$VENV_NAME' 已存在！"
    read -p "是否删除并重新创建? (y/n): " choice
    if [[ "$choice" == "y" || "$choice" == "Y" ]]; then
        echo "删除旧虚拟环境..."
        rm -rf "$VENV_NAME"
    else
        echo "已取消操作。"
        exit 0
    fi
fi

# 创建虚拟环境
echo ""
echo "创建虚拟环境..."
$PYTHON_CMD -m venv "$VENV_NAME"
if [ $? -ne 0 ]; then
    echo "错误: 创建虚拟环境失败！"
    exit 1
fi
echo "虚拟环境创建成功！"

# 激活虚拟环境并升级 pip
echo ""
echo "激活虚拟环境并升级 pip..."
source "$VENV_NAME/bin/activate"
python -m pip install --upgrade pip setuptools wheel
echo "pip 升级完成！"

# 安装依赖
echo ""
echo "安装项目依赖..."
if [ -f "requirements.txt" ]; then
    pip install -r requirements.txt
    if [ $? -eq 0 ]; then
        echo "依赖安装成功！"
    else
        echo "警告: 依赖安装过程中出现一些问题。"
    fi
else
    echo "未找到 requirements.txt，跳过依赖安装。"
fi

# 完成信息
echo ""
echo "===================================="
echo "虚拟环境创建完成！"
echo "===================================="
echo ""
echo "激活虚拟环境:"
echo "  source $VENV_NAME/bin/activate"
echo ""
echo "运行项目:"
echo "  python src/main.py"
echo ""
