from fastapi import HTTPException
from fastapi.responses import FileResponse
from nicegui import run

from xmas_app.settings import get_settings
from xmas_app.util.db import get_doc_by_name


async def get_document_from_db(plan_id: str, filename: str) -> FileResponse:
    """Retrieves a document from the database.

    Supports GET, HEAD as well as range requests, e.g. from GDAL regarding COG.
    """
    file_dir = get_settings().static_file_dir / plan_id

    file_dir.mkdir(exist_ok=True)

    file = file_dir / filename

    if not file.exists():
        doc = await run.io_bound(get_doc_by_name, plan_id, filename)
        if doc:
            file.write_bytes(doc.filedata)
        else:
            raise HTTPException(404)

    return FileResponse(
        path=file,
    )
