from uuid import uuid4

from starlette.requests import Request
from starlette.responses import FileResponse
from starlette.exceptions import HTTPException

from api.route import Route
from core.logger import APILogger

logger = APILogger(__name__)


@Route.get("/api/files/{file_path:path}")
async def get_file(request: Request):
    file_path = request.path_params["file_path"]
    name = file_path
    if "/" in file_path:
        name = file_path.split("/")[-1]

    try:
        return FileResponse(
            path=f"files/{file_path}",
            filename=name,
            media_type="application/octet-stream",
        )
    except HTTPException as e:
        if e.status_code == 404:
            return {"error": "File not found"}, 404
        else:
            error_id = uuid4()
            logger.error(f"Error {error_id} getting file {file_path}", e)
            return {"error": f"File error. ErrorId: {error_id}"}, 500
