#!/bin/bash

# 依赖修复脚本 - 解决email-validator缺失问题

echo "=== 云盘后端依赖修复工具 ==="

# 检查当前用户
echo "当前用户: $(whoami)"
echo "用户ID: $EUID"

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

# 2. 检查pip
echo ""
echo "2. 检查pip..."
if ! command -v pip3 &> /dev/null; then
    echo "错误: 未找到pip3"
    exit 1
fi
echo "✓ pip版本: $(pip3 --version)"

# 3. 升级pip
echo ""
echo "3. 升级pip..."
if [ "$EUID" -eq 0 ]; then
    pip3 install --upgrade pip
else
    pip3 install --user --upgrade pip
fi
echo "✓ pip升级完成"

# 4. 安装email-validator（单独安装确保成功）
echo ""
echo "4. 安装email-validator..."
if [ "$EUID" -eq 0 ]; then
    pip3 install email-validator
else
    pip3 install --user email-validator
fi

if [ $? -eq 0 ]; then
    echo "✓ email-validator安装成功"
else
    echo "✗ email-validator安装失败"
    exit 1
fi

# 5. 验证email-validator安装
echo ""
echo "5. 验证email-validator安装..."
python3 -c "import email_validator; print('✓ email-validator导入成功')" || {
    echo "✗ email-validator验证失败"
    exit 1
}

# 6. 安装其他核心依赖
echo ""
echo "6. 安装其他核心依赖..."
CORE_PACKAGES="fastapi uvicorn sqlalchemy pymysql redis python-jose passlib python-multipart pydantic pydantic-settings httpx python-dotenv alembic bcrypt"

if [ "$EUID" -eq 0 ]; then
    pip3 install $CORE_PACKAGES
else
    pip3 install --user $CORE_PACKAGES
fi

if [ $? -eq 0 ]; then
    echo "✓ 核心依赖安装成功"
else
    echo "✗ 核心依赖安装失败"
    exit 1
fi

# 7. 验证核心包导入
echo ""
echo "7. 验证核心包导入..."
python3 -c "
try:
    import fastapi, uvicorn, sqlalchemy, pymysql, redis, jose, passlib, pydantic, httpx, alembic
    print('✓ 所有核心包导入成功')
except ImportError as e:
    print(f'✗ 包导入失败: {e}')
    exit(1)
" || exit 1

# 8. 测试Pydantic配置
echo ""
echo "8. 测试Pydantic配置..."
python3 -c "
try:
    from pydantic import BaseModel, EmailStr
    print('✓ Pydantic EmailStr类型可用')
except Exception as e:
    print(f'✗ Pydantic EmailStr测试失败: {e}')
    print('尝试重新安装pydantic[email]...')
    exit(1)
" || {
    echo "重新安装pydantic[email]..."
    if [ "$EUID" -eq 0 ]; then
        pip3 install "pydantic[email]"
    else
        pip3 install --user "pydantic[email]"
    fi
}

# 9. 测试应用导入
echo ""
echo "9. 测试应用核心模块导入..."
python3 -c "
import sys
sys.path.insert(0, '.')
try:
    from app.core.config import settings
    print('✓ 应用配置模块导入成功')
except Exception as e:
    print(f'✗ 应用配置导入失败: {e}')
    print('可能需要检查应用代码')
    exit(1)
" || {
    echo "应用导入测试失败，但依赖已安装"
}

echo ""
echo "=== 依赖修复完成 ==="
echo ""
echo "已成功安装的包:"
echo "- email-validator (邮件验证)"
echo "- fastapi (Web框架)"
echo "- uvicorn (ASGI服务器)"
echo "- sqlalchemy (ORM)"
echo "- pymysql (MySQL驱动)"
echo "- redis (Redis客户端)"
echo "- python-jose (JWT处理)"
echo "- passlib (密码处理)"
echo "- pydantic (数据验证)"
echo "- httpx (HTTP客户端)"
echo "- alembic (数据库迁移)"
echo "- bcrypt (密码哈希)"
echo ""
echo "现在可以运行应用:"
echo "python3 main.py"
echo ""
echo "或使用部署脚本:"
echo "./quick_deploy_linux.sh"