from __future__ import annotations

from backend.app.api.schemas import BrowseResponse, DirectoryEntry, FileEntry
from backend.app.fs.filesystem_adapter import FilesystemAdapter
from backend.app.security.path_guard import PathGuard


class BrowseService:
    def __init__(self, path_guard: PathGuard, filesystem: FilesystemAdapter):
        self._path_guard = path_guard
        self._filesystem = filesystem

    def browse(self, path: str, show_hidden: bool) -> BrowseResponse:
        if self._path_guard.is_virtual_volumes_path(path):
            directories = [
                DirectoryEntry(name=item["name"], path=item["path"], modified="")
                for item in self._path_guard.virtual_volumes_entries()
            ]
            return BrowseResponse(path="/Volumes", directories=directories, files=[])

        resolved = self._path_guard.resolve_directory_path(path)
        directories_raw, files_raw = self._filesystem.list_directory(resolved.absolute, show_hidden=show_hidden)

        directories = [
            DirectoryEntry(
                name=item["name"],
                path=self._path_guard.entry_relative_path(
                    resolved.alias, item["absolute"], display_style=resolved.display_style
                ),
                modified=item["modified"],
            )
            for item in directories_raw
        ]

        files = [
            FileEntry(
                name=item["name"],
                path=self._path_guard.entry_relative_path(
                    resolved.alias, item["absolute"], display_style=resolved.display_style
                ),
                size=item["size"],
                modified=item["modified"],
            )
            for item in files_raw
        ]

        return BrowseResponse(path=resolved.relative, directories=directories, files=files)
