"""
认证依赖函数
统一处理token验证和刷新
"""
import logging
from fastapi import Depends, HTTPException, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from app.services.jwt_token import verify_and_refresh_token

logger = logging.getLogger(__name__)

security = HTTPBearer()


async def get_current_user_with_refresh(
    request: Request,
    credentials: HTTPAuthorizationCredentials = Depends(security)
) -> dict:
    """
    获取当前用户并处理token刷新
    
    这个依赖函数会：
    1. 验证token是否有效
    2. 检查是否需要刷新token
    3. 如果需要刷新，生成新token并存储到request.state
    4. 返回用户信息（payload）
    
    Args:
        request: FastAPI请求对象
        credentials: HTTP Bearer认证凭据
        
    Returns:
        dict: Token payload（包含用户信息）
        
    Raises:
        HTTPException: Token无效时抛出401错误
    """
    logger.info(f">>> [依赖函数] get_current_user_with_refresh 被调用")
    logger.info(f">>> [依赖函数] 请求路径: {request.url.path}")
    
    token = credentials.credentials
    logger.info(f">>> [依赖函数] Token前20字符: {token[:20]}...")
    
    # 验证token并检查是否需要刷新
    logger.info(f">>> [依赖函数] 调用 verify_and_refresh_token")
    payload, new_token = verify_and_refresh_token(token)
    logger.info(f">>> [依赖函数] verify_and_refresh_token 返回: payload={'存在' if payload else '无'}, new_token={'存在' if new_token else '无'}")
    
    if not payload:
        logger.warning(f"无效的访问令牌，路径: {request.url.path}")
        raise HTTPException(
            status_code=401,
            detail="无效的访问令牌"
        )
    
    logger.info(f">>> [依赖函数] Token验证成功，用户: {payload.get('username', 'unknown')}")
    
    # 如果生成了新token，存储到request.state中
    # 稍后在响应中间件中会将其添加到响应头
    if new_token:
        request.state.new_token = new_token
        request.state.token_refreshed = True
        logger.info(f">>> [依赖函数] Token已刷新，新token已存储到request.state")
        logger.info(f">>> [依赖函数] 新Token前20字符: {new_token[:20]}...")
        logger.info(f"Token已刷新，用户: {payload.get('username', 'unknown')}, 路径: {request.url.path}")
    else:
        logger.info(f">>> [依赖函数] Token未刷新（未达到阈值或其他原因）")
    
    return payload


async def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security)
) -> dict:
    """
    获取当前用户（不刷新token）
    
    用于不需要token刷新的场景
    
    Args:
        credentials: HTTP Bearer认证凭据
        
    Returns:
        dict: Token payload（包含用户信息）
        
    Raises:
        HTTPException: Token无效时抛出401错误
    """
    from app.services.jwt_token import verify_token
    
    token = credentials.credentials
    payload = verify_token(token)
    
    if not payload:
        raise HTTPException(
            status_code=401,
            detail="无效的访问令牌"
        )
    
    return payload
