from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile from pydantic import BaseModel from app.dependencies import get_document_service from app.document_service import ( DocumentNotFoundError, DocumentService, FileTooLargeError, InvalidPathError, UnsupportedFileTypeError, ) router = APIRouter() class SaveDocumentRequest(BaseModel): content: str contentType: str @router.get("/api/documents") def list_documents(path: str = "", service: DocumentService = Depends(get_document_service)): return service.list_documents(path) @router.get("/api/documents/{key:path}") def get_document(key: str, service: DocumentService = Depends(get_document_service)): try: return service.get_document(key) except DocumentNotFoundError: raise HTTPException(status_code=404, detail="Document not found") except InvalidPathError as exc: raise HTTPException(status_code=400, detail=str(exc)) @router.put("/api/documents/{key:path}") def save_document( key: str, body: SaveDocumentRequest, service: DocumentService = Depends(get_document_service) ): try: return service.save_document(key, body.content.encode("utf-8"), body.contentType) except InvalidPathError as exc: raise HTTPException(status_code=400, detail=str(exc)) @router.delete("/api/documents/{key:path}", status_code=204) def delete_document(key: str, service: DocumentService = Depends(get_document_service)): try: service.delete_document(key) except InvalidPathError as exc: raise HTTPException(status_code=400, detail=str(exc)) return None @router.post("/api/upload", status_code=201) async def upload_document( file: UploadFile = File(...), path: str = Form(...), relative_path: str | None = Form(None), service: DocumentService = Depends(get_document_service), ): data = await file.read() name = relative_path if relative_path else file.filename key = f"{path.rstrip('/')}/{name}" if path else name content_type = file.content_type or "application/octet-stream" try: return service.upload_document(key, data, content_type) except (UnsupportedFileTypeError, FileTooLargeError, InvalidPathError) as exc: raise HTTPException(status_code=400, detail=str(exc))