"""
检索引擎视图路由
"""
from fastapi import APIRouter, Depends, Query, Path, Body
from sqlalchemy.ext.asyncio import AsyncSession

from app.base.async_mysql_connection import get_db
from app.services.search_engine_service import search_engine_service
from app.sample.schemas.search_engine import (
    SearchEngineCreate, 
    SearchEngineUpdate, 
    SearchEngineResponse,
    KBSearchRequest,
    KBSearchResponse
)
from app.schemas.base import PaginatedResponseSchema, ResponseSchema
from app.services.jwt_token import verify_token
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

router = APIRouter(prefix="/sample/search-engine", tags=["样本中心-检索引擎"])
security = HTTPBearer()

# --- 新增：知识库搜索接口 ---
@router.post("/search", response_model=ResponseSchema)
async def search_knowledge_base(
    payload: KBSearchRequest,
    db: AsyncSession = Depends(get_db),
    credentials: HTTPAuthorizationCredentials = Depends(security)
):
    """知识库语义搜索"""
    payload_token = verify_token(credentials.credentials)
    if not payload_token:
        return ResponseSchema(code=401, message="无效的访问令牌")

    result = await search_engine_service.search_kb(db, payload)
    return ResponseSchema(code=0, message="搜索成功", data=result)


# --- 原有接口 ---
@router.get("", response_model=PaginatedResponseSchema)
async def get_search_engines(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: str = Query(None, description="搜索关键词"),
    status: str = Query(None, description="状态筛选"),
    db: AsyncSession = Depends(get_db),
    credentials: HTTPAuthorizationCredentials = Depends(security)
):
    """获取检索引擎列表"""
    # 鉴权
    payload = verify_token(credentials.credentials)
    if not payload:
        return PaginatedResponseSchema(code=401, message="无效的访问令牌", data=[], meta=None)

    items, meta = await search_engine_service.get_list(
        db, page=page, page_size=page_size, keyword=keyword, status=status
    )

    return PaginatedResponseSchema(
        code=0,
        message="获取检索引擎列表成功",
        data=[SearchEngineResponse.model_validate(item) for item in items],
        meta=meta,
    )

@router.post("", response_model=ResponseSchema)
async def create_search_engine(
    payload: SearchEngineCreate,
    db: AsyncSession = Depends(get_db),
    credentials: HTTPAuthorizationCredentials = Depends(security)
):
    """创建新检索引擎"""
    payload_token = verify_token(credentials.credentials)
    if not payload_token:
        return ResponseSchema(code=401, message="无效的访问令牌")

    new_engine = await search_engine_service.create(db, payload)
    return ResponseSchema(code=0, message="创建成功", data=SearchEngineResponse.model_validate(new_engine))

@router.post("/{id}", response_model=ResponseSchema)
async def update_search_engine(
    payload: SearchEngineUpdate,
    id: str = Path(..., description="检索引擎ID"),
    db: AsyncSession = Depends(get_db),
    credentials: HTTPAuthorizationCredentials = Depends(security)
):
    """更新检索引擎信息"""
    payload_token = verify_token(credentials.credentials)
    if not payload_token:
        return ResponseSchema(code=401, message="无效的访问令牌")

    engine = await search_engine_service.update(db, id, payload)
    return ResponseSchema(code=0, message="更新成功", data=SearchEngineResponse.model_validate(engine))

@router.post("/{id}/status", response_model=ResponseSchema)
async def update_search_engine_status(
    id: str = Path(..., description="检索引擎ID"),
    status: str = Query(..., description="状态: normal/disabled"),
    db: AsyncSession = Depends(get_db),
    credentials: HTTPAuthorizationCredentials = Depends(security)
):
    """更新检索引擎状态"""
    payload_token = verify_token(credentials.credentials)
    if not payload_token:
        return ResponseSchema(code=401, message="无效的访问令牌")

    await search_engine_service.update_status(db, id, status)
    return ResponseSchema(code=0, message=f"状态已更新为 {status}")

@router.post("/{id}/delete", response_model=ResponseSchema)
async def delete_search_engine(
    id: str = Path(..., description="检索引擎ID"),
    db: AsyncSession = Depends(get_db),
    credentials: HTTPAuthorizationCredentials = Depends(security)
):
    """删除检索引擎"""
    payload_token = verify_token(credentials.credentials)
    if not payload_token:
        return ResponseSchema(code=401, message="无效的访问令牌")

    await search_engine_service.delete(db, id)
    return ResponseSchema(code=0, message="删除成功")
