# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt

"""
Jingrow Local Embedding API
提供文本转向量和向量搜索功能
"""

from fastapi import APIRouter, HTTPException, Request
from typing import Dict, Any, List
import logging
from jingrow.utils.jingrow_cloud import call_jembedding
from jingrow.utils.embedding import search_vectors

logger = logging.getLogger(__name__)
router = APIRouter()

@router.post("/jingrow/embedding/batch")
async def embedding_batch_endpoint(request: Request):
    """
    文本转向量批量处理端点
    """
    try:
        # 获取请求数据
        request_data = await request.json()
        texts = request_data.get('texts', [])
        
        if not texts:
            raise HTTPException(status_code=400, detail="缺少文本数据")
        
        # 调用embedding函数
        result = call_jembedding(texts)
        
        if not result.get('success', False):
            raise HTTPException(status_code=500, detail=result.get('error', 'Embedding处理失败'))
        
        return {
            "success": True,
            "data": result.get('data', [])
        }
        
    except Exception as e:
        logger.error(f"Embedding batch error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/jingrow/embedding/search")
async def search_vectors_endpoint(request: Request):
    """
    向量搜索端点
    """
    try:
        # 获取请求数据
        request_data = await request.json()
        
        collection_name = request_data.get('collection_name', 'knowledge_base')
        query_vector = request_data.get('query_vector', [])
        limit = request_data.get('limit', 10)
        score_threshold = request_data.get('score_threshold', 0.7)
        
        if not query_vector:
            raise HTTPException(status_code=400, detail="缺少查询向量")
        
        # 调用搜索函数
        results = search_vectors(collection_name, query_vector, limit, score_threshold)
        
        return {
            "success": True,
            "data": results
        }
        
    except Exception as e:
        logger.error(f"Vector search error: {e}")
        raise HTTPException(status_code=500, detail=str(e))
