"""
Token认证中间件
"""
from fastapi import HTTPException, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from typing import Optional
from token_auth import AuthenticatedUser
from db_token_manager import DatabaseTokenManager, get_db_token_manager


# HTTP Bearer认证方案（支持Authorization: Bearer <token>）
bearer_scheme = HTTPBearer(auto_error=False)


def get_current_user(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer_scheme),
    token_mgr: DatabaseTokenManager = Depends(get_db_token_manager)
) -> AuthenticatedUser:
    """
    获取当前认证用户
    
    支持两种Token传递方式：
    1. Authorization: Bearer <token>
    2. X-Access-Token: <token> (兼容性)
    """
    token = None
    
    # 方式1: Bearer Token
    if credentials:
        token = credentials.credentials
    
    # 如果没有找到token，抛出认证错误
    if not token:
        raise HTTPException(
            status_code=401,
            detail="缺少访问令牌，请在请求头中添加 Authorization: Bearer <token>"
        )
    
    # 验证Token
    auth_user = token_mgr.verify_token(token)
    if not auth_user:
        raise HTTPException(
            status_code=401,
            detail="无效或过期的访问令牌"
        )
    
    return auth_user


def check_dataset_permission(user: AuthenticatedUser, dataset_id: str) -> bool:
    """检查用户是否有访问指定数据集的权限（简化版：所有用户可访问所有数据集）"""
    # 管理员可以访问所有数据集
    if user.role.value == "admin":
        return True
    
    # 简化版本：所有用户可以访问所有数据集
    return True


def check_file_size_permission(user: AuthenticatedUser, file_size: int) -> bool:
    """检查用户是否有上传指定大小文件的权限"""
    return file_size <= user.max_file_size


def require_role(required_role: str):
    """
    角色权限装饰器工厂
    
    使用方式：
    @require_role("admin")
    def admin_only_endpoint(user: AuthenticatedUser = Depends(get_current_user)):
        pass
    """
    def role_checker(user: AuthenticatedUser = Depends(get_current_user)) -> AuthenticatedUser:
        role_hierarchy = {
            "guest": 0,
            "user": 1,
            "admin": 2
        }
        
        user_level = role_hierarchy.get(user.role.value, 0)
        required_level = role_hierarchy.get(required_role, 2)
        
        if user_level < required_level:
            raise HTTPException(
                status_code=403,
                detail=f"需要{required_role}权限才能访问此资源"
            )
        
        return user
    
    return role_checker


# 便捷的权限检查依赖
def require_admin(user: AuthenticatedUser = Depends(require_role("admin"))) -> AuthenticatedUser:
    """要求管理员权限"""
    return user


def require_user(user: AuthenticatedUser = Depends(require_role("user"))) -> AuthenticatedUser:
    """要求用户权限（user或admin）"""
    return user
