from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field
from app.schemas.base import BaseModelSchema
from datetime import datetime

class SearchEngineBase(BaseModel):
    name: str = Field(..., description="引擎名称")
    engine_type: str = Field(..., description="引擎类型")
    base_url: Optional[str] = Field(None, description="基础URL")
    api_key: Optional[str] = Field(None, description="API Key")
    description: Optional[str] = Field(None, description="描述")
    status: Optional[str] = Field("normal", description="状态")

class SearchEngineCreate(SearchEngineBase):
    """创建检索引擎请求参数"""
    pass

class SearchEngineUpdate(BaseModel):
    """更新检索引擎请求参数"""
    name: Optional[str] = None
    engine_type: Optional[str] = None
    base_url: Optional[str] = None
    api_key: Optional[str] = None
    description: Optional[str] = None
    status: Optional[str] = None

class SearchEngineResponse(BaseModelSchema):
    """检索引擎响应模型"""
    id: str
    name: str
    engine_type: str
    base_url: Optional[str]
    api_key: Optional[str]
    description: Optional[str]
    status: str
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda v: v.strftime("%Y-%m-%d %H:%M:%S") if v else None
        }

# --- 新增：知识库搜索相关模型 ---

class KBSearchRequest(BaseModel):
    """知识库搜索请求"""
    kb_id: str = Field(..., description="知识库ID或集合名称")
    query: str = Field(..., description="检索关键字")
    metadata_field: Optional[str] = Field(None, description="元数据字典字段")
    metadata_value: Optional[str] = Field(None, description="元数据字典值")
    top_k: int = Field(10, description="返回结果数量")
    score_threshold: float = Field(0.0, description="相似度阈值")

class KBSearchResultItem(BaseModel):
    """单条搜索结果"""
    id: str
    kb_name: str
    doc_name: str
    content: str
    meta_info: str
    score: float
    
class KBSearchResponse(BaseModel):
    """搜索响应"""
    results: List[KBSearchResultItem]
    total: int
