#!/bin/bash

# 虚拟环境修复脚本

echo "=== 虚拟环境修复工具 ==="

# 检查当前目录
if [ ! -f "main.py" ]; then
    echo "错误: 请在包含main.py的项目根目录下运行此脚本"
    exit 1
fi

echo "当前目录: $(pwd)"
echo "当前Python版本: $(python3 --version)"

# 备份现有虚拟环境（如果存在）
if [ -d "venv" ]; then
    echo "发现现有虚拟环境，正在备份..."
    mv venv venv_backup_$(date +%Y%m%d_%H%M%S)
    echo "✓ 现有虚拟环境已备份"
fi

# 创建新的虚拟环境
echo "正在创建新的虚拟环境..."
python3 -m venv venv

if [ $? -eq 0 ]; then
    echo "✓ 虚拟环境创建成功"
else
    echo "✗ 虚拟环境创建失败"
    echo "可能的原因:"
    echo "1. python3-venv 未安装"
    echo "2. 权限不足"
    echo "3. 磁盘空间不足"
    echo ""
    echo "尝试安装 python3-venv:"
    echo "sudo apt-get install python3-venv  # Ubuntu/Debian"
    echo "sudo yum install python3-virtualenv  # CentOS/RHEL"
    exit 1
fi

# 验证虚拟环境文件
echo "验证虚拟环境文件..."
if [ -f "venv/bin/activate" ]; then
    echo "✓ 激活脚本存在: venv/bin/activate"

    # 显示虚拟环境信息
    echo "虚拟环境内容:"
    ls -la venv/bin/ | head -5

    # 测试激活
    echo "测试虚拟环境激活..."
    source venv/bin/activate
    echo "✓ 虚拟环境激活成功"
    echo "Python路径: $(which python)"
    echo "Python版本: $(python --version)"

    # 升级pip
    echo "升级pip..."
    pip install --upgrade pip
    echo "✓ pip升级完成"

else
    echo "✗ 激活脚本不存在"
    echo "显示venv目录内容:"
    ls -la venv/ 2>/dev/null || echo "venv目录为空或不存在"
    exit 1
fi

echo ""
echo "=== 修复完成 ==="
echo "虚拟环境已成功创建并可以正常使用"
echo ""
echo "下一步操作:"
echo "1. 重新运行部署脚本: ./deploy_linux.sh"
echo "2. 或者手动激活并安装依赖:"
echo "   source venv/bin/activate"
echo "   pip install -r requirements.txt"