"""
Token认证API路由
"""
from fastapi import APIRouter, HTTPException, Depends
from typing import List, Dict, Any
from token_auth import TokenRequest, TokenResponse, UserRole
from db_token_manager import DatabaseTokenManager, get_db_token_manager


router = APIRouter(prefix="/api/token", tags=["Token认证"])


@router.post("/generate", response_model=TokenResponse)
async def generate_token(
    request: TokenRequest,
    token_mgr: DatabaseTokenManager = Depends(get_db_token_manager)
):
    """
    生成访问令牌
    
    用户提供基本信息后，返回一个访问令牌用于后续API调用
    类似于HuggingFace的使用方式
    """
    try:
        # 基本验证
        if not request.user_id or not request.user_name:
            raise HTTPException(status_code=400, detail="user_id和user_name不能为空")
        
        # 生成Token（永不过期）
        token_response = token_mgr.generate_token(request)
        
        return token_response
        
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"生成Token失败: {str(e)}")


@router.post("/verify")
async def verify_token(
    token: str,
    token_mgr: DatabaseTokenManager = Depends(get_db_token_manager)
):
    """
    验证Token（用于测试）
    """
    auth_user = token_mgr.verify_token(token)
    if not auth_user:
        raise HTTPException(status_code=401, detail="无效或过期的Token")
    
    return {
        "valid": True,
        "user_id": auth_user.user_id,
        "user_name": auth_user.user_name,
        "role": auth_user.role.value,
        "max_file_size": auth_user.max_file_size,
        "daily_remaining": auth_user.daily_remaining
    }


@router.delete("/revoke")
async def revoke_token(
    token: str,
    token_mgr: DatabaseTokenManager = Depends(get_db_token_manager)
):
    """
    撤销Token
    """
    success = token_mgr.revoke_token(token)
    if not success:
        raise HTTPException(status_code=404, detail="Token不存在")
    
    return {"message": "Token已撤销"}


@router.get("/user/{user_id}/tokens")
async def get_user_tokens(
    user_id: str,
    token_mgr: DatabaseTokenManager = Depends(get_db_token_manager)
) -> List[Dict[str, Any]]:
    """
    获取用户的所有Token信息
    """
    tokens = token_mgr.get_user_tokens(user_id)
    return tokens


@router.get("/roles")
async def get_available_roles():
    """
    获取可用的用户角色
    """
    return {
        "roles": [
            {"value": UserRole.ADMIN.value, "label": "管理员", "description": "拥有所有权限"},
            {"value": UserRole.USER.value, "label": "普通用户", "description": "标准用户权限"},
            {"value": UserRole.GUEST.value, "label": "访客", "description": "只读权限"}
        ]
    }
