from pathlib import Path

from mmar_files.constants import SUFFIX_DIR, ResourceId
from mmar_files.file_storage_api import FileStorageAPI


class FileStorageBasic(FileStorageAPI):
    """resource_id(file) == absolute_path(file), only reading operations supported"""

    def get_fname(self, resource_id: ResourceId) -> str | None:
        return Path(resource_id).name

    def download(self, resource_id: ResourceId) -> bytes:
        return Path(resource_id).read_bytes()

    async def download_async(self, resource_id: ResourceId) -> bytes:
        return self.download(resource_id)

    def download_text(self, resource_id: ResourceId) -> str:
        return Path(resource_id).read_text(encoding="utf-8")

    def read_dir_or_none(self, resource_id: ResourceId) -> list[ResourceId] | None:
        if not self.is_dir(resource_id):
            return None
        res = self.download_text(resource_id).split("\n")
        return res

    def get_path(self, resource_id: ResourceId | None) -> Path | None:
        return self._get_path(resource_id)

    def _get_path(self, resource_id: ResourceId | None) -> Path | None:
        if not resource_id:
            return None
        path = Path(resource_id)
        return path if (path.exists() and path.is_file()) else None

    def is_valid(self, resource_id: ResourceId | None) -> bool:
        path = self._get_path(resource_id)
        return path is not None

    def is_file(self, resource_id: ResourceId | None) -> bool:
        path = self._get_path(resource_id)
        return bool(path and path.suffix != SUFFIX_DIR)

    def is_dir(self, resource_id: ResourceId | None) -> bool:
        path = self._get_path(resource_id)
        return bool(path and path.suffix == SUFFIX_DIR)

    def get_dtype(self, resource_id: ResourceId | None) -> str | None:
        return resource_id and resource_id.rsplit(".")[-1].lower()
