from fastapi import APIRouter, HTTPException, UploadFile, File from app.models.schemas import DocumentResponse from app.services.document_service import document_service from app.utils.logger import logger from app.utils.errors import DocumentProcessingError from typing import List from datetime import datetime router = APIRouter(prefix="/documents", tags=["documents"]) @router.post("/upload", response_model=DocumentResponse) async def upload_document(file: UploadFile = File(...)): try: content = await file.read() file_path = document_service.save_uploaded_file(content, file.filename) result = await document_service.process_document(file_path) document_service.delete_file(file_path) return DocumentResponse( id=result["doc_id"], filename=result["file_name"], chunk_count=result["num_chunks"], status="success", created_at=datetime.utcnow() ) except DocumentProcessingError as e: logger.error(f"Processing error: {str(e)}") raise HTTPException(status_code=400, detail=str(e)) except Exception as e: logger.error(f"Upload error: {str(e)}") raise HTTPException(status_code=500, detail="Upload failed") @router.get("/", response_model=List[dict]) async def list_documents(): try: documents = await document_service.get_all_documents() for doc in documents: doc["_id"] = str(doc["_id"]) return documents except Exception as e: logger.error(f"List error: {str(e)}") raise HTTPException(status_code=500, detail="Failed to list documents") @router.get("/stats") async def get_stats(): try: stats = await document_service.get_document_stats() return stats except Exception as e: logger.error(f"Stats error: {str(e)}") raise HTTPException(status_code=500, detail="Failed to get stats") @router.delete("/{doc_id}") async def delete_document(doc_id: str): try: success = await document_service.delete_document(doc_id) if not success: raise HTTPException(status_code=404, detail="Document not found") return {"message": "Document deleted successfully", "doc_id": doc_id} except HTTPException: raise except Exception as e: logger.error(f"Delete error: {str(e)}") raise HTTPException(status_code=500, detail="Delete failed")