"""Object storage for uploaded files.

Phase 3 ships a local filesystem backend (build plan Section 3: "local volume or
S3-compatible"). The S3 backend is added in a later phase.
"""

from __future__ import annotations

import os
import uuid

from legate.config import Settings, get_settings


class LocalStorage:
    backend = "local"

    def __init__(self, base_dir: str) -> None:
        self._base = os.path.abspath(base_dir)

    def _abs(self, uri: str) -> str:
        return os.path.join(self._base, uri)

    def save(
        self, *, workspace_id: uuid.UUID, document_id: uuid.UUID, filename: str, data: bytes
    ) -> str:
        safe_name = os.path.basename(filename) or "upload"
        uri = f"{workspace_id}/{document_id}/{safe_name}"
        path = self._abs(uri)
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "wb") as fh:
            fh.write(data)
        return uri

    def read(self, uri: str) -> bytes:
        with open(self._abs(uri), "rb") as fh:
            return fh.read()

    def delete(self, uri: str) -> None:
        path = self._abs(uri)
        if os.path.exists(path):
            os.remove(path)


def build_storage(settings: Settings | None = None) -> LocalStorage:
    settings = settings or get_settings()
    if settings.storage_backend != "local":
        # S3 backend arrives in Phase 8; default to local for now.
        pass
    return LocalStorage(settings.storage_local_dir)
