#!/bin/bash

# 智能部署脚本 - 自动检测权限并选择合适的安装方式

set -e

echo "=== 云盘后端智能部署脚本 ==="

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

echo "当前目录: $(pwd)"
echo "当前用户: $(whoami)"
echo "用户ID: $EUID"

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

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

# 3. 创建和使用虚拟环境
echo ""
echo "3. 创建Python虚拟环境..."
if [ ! -d "venv" ]; then
    echo "正在创建新的虚拟环境..."
    python3 -m venv venv
    echo "✓ 虚拟环境创建成功"
else
    echo "✓ 虚拟环境已存在"
fi

# 4. 激活虚拟环境并安装依赖
echo ""
echo "4. 激活虚拟环境并安装依赖..."

if [ -f "venv/bin/activate" ]; then
    source venv/bin/activate
    echo "✓ 虚拟环境已激活 (Linux)"
elif [ -f "venv/Scripts/activate" ]; then
    source venv/Scripts/activate
    echo "✓ 虚拟环境已激活 (Windows)"
else
    echo "✗ 虚拟环境激活文件不存在，重新创建..."
    rm -rf venv
    python3 -m venv venv
    source venv/bin/activate
    echo "✓ 虚拟环境重新创建并激活成功"
fi

# 升级pip
echo "升级虚拟环境中的pip..."
pip install --upgrade pip

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

# 安装其他依赖
echo "安装其他依赖..."
if [ -f "requirements.txt" ]; then
    echo "从requirements.txt安装..."
    pip install -r requirements.txt
else
    echo "安装核心依赖..."
    pip install fastapi uvicorn sqlalchemy pymysql redis python-jose passlib python-multipart pydantic pydantic-settings httpx python-dotenv loguru alembic bcrypt
fi

echo "✓ 依赖安装完成 (虚拟环境中)"

# 5. 验证安装
echo ""
echo "5. 验证依赖安装..."
python -c "
import sys
try:
    import email_validator
    print('✓ email-validator')
except ImportError:
    print('✗ email-validator 导入失败')
    sys.exit(1)

try:
    from pydantic import EmailStr
    print('✓ Pydantic EmailStr')
except Exception as e:
    print(f'✗ Pydantic EmailStr 失败: {e}')
    sys.exit(1)

packages = ['fastapi', 'uvicorn', 'sqlalchemy', 'pymysql', 'redis']
for pkg in packages:
    try:
        __import__(pkg)
        print(f'✓ {pkg}')
    except ImportError:
        print(f'✗ {pkg} 导入失败')
        sys.exit(1)

print('\\n✓ 所有依赖验证成功!')
"

# 6. 配置环境变量
echo ""
echo "6. 配置环境变量..."
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 文件"
else
    echo "✓ .env 文件已存在"
fi

# 7. 创建启动脚本（可选，用于手动启动）
echo ""
echo "7. 创建启动脚本（用于手动启动）..."
cat > start_app.sh << 'EOF'
#!/bin/bash
# 云盘后端启动脚本

cd "$(dirname "$0")"

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

mkdir -p logs uploads

# 激活虚拟环境
if [ -f "venv/bin/activate" ]; then
    source venv/bin/activate
elif [ -f "venv/Scripts/activate" ]; then
    source venv/Scripts/activate
fi

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

python main.py
EOF

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

# 8. 测试应用配置
echo ""
echo "8. 测试应用配置..."
python -c "
import sys
sys.path.insert(0, '.')
try:
    from app.core.config import settings
    print('✓ 应用配置加载成功')
    print(f'  环境: {settings.ENVIRONMENT}')
    print(f'  调试模式: {settings.DEBUG}')
except Exception as e:
    print(f'✗ 应用配置加载失败: {e}')
    print('请检查.env文件和应用代码')
    sys.exit(1)
"

echo ""
echo "=== 智能部署完成 ==="
echo ""
echo "管理命令："
echo "手动启动: ./start_app.sh"
echo "直接启动: source venv/bin/activate && python main.py"
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 "虚拟环境: venv/"

# 9. 直接启动应用（在虚拟环境中）
echo ""
echo "=== 正在启动服务 ==="
echo "在虚拟环境中启动云盘后端服务..."
echo "服务地址: http://localhost:8002"
echo "API文档: http://localhost:8002/docs"
echo "按 Ctrl+C 停止服务"
echo ""

python main.py