#!/bin/bash

# 快速部署脚本 - 修复虚拟环境问题

set -e

echo "=== 云盘后端快速部署脚本 ==="

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

echo "当前目录: $(pwd)"

# 1. 检查Python环境
echo "1. 检查Python环境..."
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到python3，请先安装Python 3.8+"
    exit 1
fi
echo "✓ Python版本: $(python3 --version)"

# 2. 创建必要目录
echo "2. 创建必要目录..."
mkdir -p logs uploads
echo "✓ 目录创建完成"

# 3. 直接安装依赖（不使用虚拟环境）
echo "3. 安装Python依赖（系统级）..."
echo "注意: 这将在系统级别安装依赖包"

# 检查是否为root用户
if [ "$EUID" -eq 0 ]; then
    echo "检测到root用户，使用pip3安装..."
    pip3 install --upgrade pip

    # 先安装email-validator
    echo "安装email-validator..."
    pip3 install email-validator

    if [ -f "requirements.txt" ]; then
        echo "从requirements.txt安装依赖..."
        pip3 install -r requirements.txt
    else
        echo "安装基础依赖包..."
        pip3 install fastapi uvicorn sqlalchemy pymysql redis python-jose passlib python-multipart pydantic pydantic-settings httpx python-dotenv loguru alembic bcrypt
    fi
else
    echo "使用用户级pip安装..."

    # 检查是否有用户目录写入权限
    USER_LOCAL="$HOME/.local"
    if [ ! -w "$USER_LOCAL" ]; then
        echo "⚠ 用户目录无写入权限，尝试使用系统级安装..."
        pip3 install --upgrade pip
        pip3 install email-validator
        if [ -f "requirements.txt" ]; then
            pip3 install -r requirements.txt
        else
            pip3 install fastapi uvicorn sqlalchemy pymysql redis python-jose passlib python-multipart pydantic pydantic-settings httpx python-dotenv loguru alembic bcrypt
        fi
    else
        pip3 install --user --upgrade pip

        # 先安装email-validator
        echo "安装email-validator..."
        pip3 install --user email-validator

        if [ -f "requirements.txt" ]; then
            echo "从requirements.txt安装依赖..."
            pip3 install --user -r requirements.txt
        else
            echo "安装基础依赖包..."
            pip3 install --user fastapi uvicorn sqlalchemy pymysql redis python-jose passlib python-multipart pydantic pydantic-settings httpx python-dotenv loguru alembic bcrypt
        fi
    fi
fi

echo "✓ 依赖安装完成"

# 4. 配置环境变量
echo "4. 配置环境变量..."
if [ ! -f ".env" ]; then
    echo "创建默认 .env 文件..."
    cat > .env << EOF
# 基础配置
ENVIRONMENT=production
DEBUG=false

# 数据库配置
DATABASE_URL=mysql+pymysql://用户名:密码@localhost:3306/数据库名

# Redis配置
REDIS_URL=redis://localhost:6379

# JWT配置
JWT_SECRET_KEY=your-super-secret-jwt-key-change-in-production-$(date +%s)
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=30

# 文件上传配置
UPLOAD_DIR=uploads
MAX_FILE_SIZE=10485760

# CORS配置
ALLOWED_HOSTS=["*"]
EOF
    echo "✓ 已创建默认 .env 文件"
    echo "请编辑 .env 文件配置数据库连接等参数"
else
    echo "✓ .env 文件已存在"
fi

# 5. 创建启动脚本
echo "5. 创建启动脚本..."
cat > start_service.sh << 'STARTEOF'
#!/bin/bash
# 云盘后端启动脚本

# 进入脚本所在目录
cd "$(dirname "$0")"

# 检查环境文件
if [ ! -f ".env" ]; then
    echo "错误: .env 文件不存在"
    exit 1
fi

# 创建必要目录
mkdir -p logs uploads

# 启动服务
echo "启动云盘后端服务..."
echo "服务地址: http://localhost:8002"
echo "API文档: http://localhost:8002/docs"
echo "按 Ctrl+C 停止服务"
echo ""

python3 main.py
STARTEOF

chmod +x start_service.sh
echo "✓ 启动脚本创建完成: start_service.sh"

# 6. 创建停止脚本
echo "6. 创建停止脚本..."
cat > stop_service.sh << 'STOPEOF'
#!/bin/bash
# 云盘后端停止脚本

echo "停止云盘后端服务..."
pkill -f "python3 main.py" || echo "服务未运行"
echo "服务已停止"
STOPEOF

chmod +x stop_service.sh
echo "✓ 停止脚本创建完成: stop_service.sh"

# 7. 创建状态检查脚本
echo "7. 创建状态检查脚本..."
cat > check_status.sh << 'STATUSEOF'
#!/bin/bash
# 云盘后端状态检查脚本

if pgrep -f "python3 main.py" > /dev/null; then
    echo "✓ 云盘后端服务正在运行"
    echo "进程ID: $(pgrep -f 'python3 main.py')"
    echo "端口: 8002"
    echo "服务地址: http://localhost:8002"
    echo "API文档: http://localhost:8002/docs"

    # 测试健康检查
    if command -v curl &> /dev/null; then
        if curl -s http://localhost:8002/api/v1/health > /dev/null; then
            echo "✓ 服务响应正常"
        else
            echo "⚠ 服务运行但可能有问题"
        fi
    else
        echo "⚠ curl命令不可用，无法测试服务响应"
    fi
else
    echo "✗ 云盘后端服务未运行"
    echo "启动服务: ./start_service.sh"
fi
STATUSEOF

chmod +x check_status.sh
echo "✓ 状态检查脚本创建完成: check_status.sh"

# 8. 完成提示
echo ""
echo "=== 快速部署完成 ==="
echo "当前目录: $(pwd)"
echo ""
echo "管理命令："
echo "1. 启动服务: ./start_service.sh"
echo "2. 停止服务: ./stop_service.sh"
echo "3. 查看状态: ./check_status.sh"
echo ""
echo "访问地址："
echo "- 服务地址: http://localhost:8002"
echo "- API文档: http://localhost:8002/docs"
echo "- 健康检查: http://localhost:8002/api/v1/health"
echo ""
echo "配置文件: .env"
echo "日志目录: logs/"
echo "上传目录: uploads/"
echo ""
echo "注意: 请确保数据库和Redis服务已启动并正确配置"

# 9. 自动启动服务
echo ""
echo "=== 正在启动服务 ==="
echo "启动云盘后端服务..."
./start_service.sh