from query import search_query
import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

async def handle(params_kw):
    logger.info(f'{params_kw=}')
    
    # 调用 search_query
    results = await search_query(
        query=params_kw.prompt,
        userid=params_kw.userid,
        db_type=params_kw.db_type,
        limit=params_kw.limit,
        offset=params_kw.offset
    )
    logger.debug(f'{results=}')
    
    # 处理结果
    rows = []
    for result in results:
        row = result['metadata'].copy()
        row.update({
            'content': result['text'],
            'distance': result['distance']
        })
        rows.append(row)
    
    # 空结果处理
    if not rows:
        return {
            "widgettype": "Message",
            "options": {
                "archor": "cc",
                "timeout": 5,
                "auto_open": True,
                "auto_dismiss": True,
                "auto_destroy": True,
                "cwidth": 23,
                "cheight": 17,
                "title": "Info",
                "message": "未找到匹配的文档"
            }
        }
    
    return {
        "total": len(rows),
        "rows": rows
    }