from fastapi import APIRouter, Depends, HTTPException from typing import List, Optional from app.api.models import ( QueryRequest, QueryResponse, SearchRequest, SearchResponse, CollectionStatsResponse, HealthResponse ) from app.services.rag_service import RAGService from app.core.config import settings from app.core.security import get_current_active_user from app.db.models import User router = APIRouter() _rag_service = None def get_rag_service(): global _rag_service if _rag_service is None: _rag_service = RAGService() return _rag_service @router.post("/query", response_model=QueryResponse) async def query_documents( request: QueryRequest, rag_service: RAGService = Depends(get_rag_service), current_user: User = Depends(get_current_active_user) # Protege a rota ): """Query documents using RAG with conversation memory""" try: # Extrai os escopos do usuário logado user_scopes = current_user.scopes.split(',') # Passa os escopos para a função de query (será implementado no próximo passo) result = rag_service.query( question=request.question, chat_history=request.chat_history, k=request.k, allowed_scopes=user_scopes # NOVO ) return QueryResponse(**result) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @router.get("/health", response_model=HealthResponse) async def health_check(vector_store: RAGService = Depends(get_rag_service)): try: stats = vector_store.vector_store.get_collection_stats() return HealthResponse( status="healthy", vector_store=bool(stats), chroma_directory=settings.chroma_persist_directory, embeddings_model=settings.embeddings_model ) except Exception as e: return HealthResponse(status=f"error: {e}", vector_store=False)