"""Define API routes for knowledge."""

from __future__ import annotations

from fastapi import APIRouter, HTTPException

from app.api.models import SearchResponse, SearchResultItem, SearchRequest
from app.shared.bootstrap import get_retrieval_service
# Keep route handlers close to their transport-layer wiring for easier auditing.


router = APIRouter(prefix="/knowledge", tags=["knowledge"])


@router.post("/search", response_model=SearchResponse)
async def search_knowledge(request: SearchRequest):
    """Search knowledge."""
    if not request.query or not request.query.strip():
        raise HTTPException(status_code=400, detail="查询文本不能为空")

    results = get_retrieval_service().retrieve(
        query=request.query,
        top_k=request.top_k,
        filters=request.filters,
    )
    return SearchResponse(
        query=request.query,
        total=len(results),
        results=[
            SearchResultItem(
                id=index + 1,
                content=item.text,
                score=item.score,
                metadata={
                    "doc_id": item.doc_id,
                    "doc_title": item.doc_title,
                    "chunk_id": item.chunk_id,
                    "chunk_type": item.chunk_type,
                    "section_title": item.section_title,
                    "page_start": item.page_start,
                    "page_end": item.page_end,
                    "section_level": item.section_level,
                    "chunk_index": item.chunk_index,
                    "piece_index": item.piece_index,
                    **item.metadata,
                },
            )
            for index, item in enumerate(results)
        ],
    )


@router.post("/retrieval", response_model=SearchResponse)
async def knowledge_retrieval(request: SearchRequest):
    """Handle knowledge retrieval."""
    return await search_knowledge(request)
