from fastapi import APIRouter, Query
from app.infra.cache.redis_client import redis_client

router = APIRouter()

@router.post("/clearrediskey/", summary="清除单个缓存键", description="根据键名清除单个Redis缓存")
async def fastapi_clear_redis_key(key: str = Query(..., description="缓存键名")):
    """
    清除单个缓存键
    
    根据指定的键名删除Redis中对应的缓存
    """
    redis_client.delete(key)
    return True


@router.post("/clearrediskeys/", summary="清除匹配的缓存键", description="根据模式清除匹配的Redis缓存键")
async def fastapi_clear_redis_keys(keys: str = Query(..., description="缓存键模式（支持通配符）")):
    """
    清除匹配的缓存键
    
    根据指定的模式删除Redis中所有匹配的缓存键
    """
    # delete keys contains the key
    matched_keys = redis_client.keys(f"*{keys}*")
    if matched_keys:
        redis_client.delete(*matched_keys)

    return True


@router.post("/clearallredis/", summary="清除所有缓存", description="清空整个Redis数据库的所有缓存")
async def fastapi_clear_all_redis():
    """
    清除所有缓存
    
    清空Redis数据库中的所有缓存键值对
    """
    redis_client.flushdb()
    return True


@router.get("/queryredis/", summary="查询缓存键列表", description="获取Redis中所有的缓存键")
async def fastapi_query_redis():
    """
    查询缓存键列表
    
    获取Redis数据库中所有的缓存键列表
    """
    # Helper to decode bytes to str for JSON response if needed, 
    # but original just returned keys (which might be bytes in redis-py unless decode_responses=True)
    # create_redis_client usually sets decode_responses=False by default.
    # We will assume user handles bytes or we should decode. 
    # Original just returned redis_client.keys("*")
    keys = redis_client.keys("*")
    # Clean output for API
    return [k.decode('utf-8') if isinstance(k, bytes) else k for k in keys]
