"""Factory for user-scoped cloud storage backends."""
from __future__ import annotations

from storage.cloud_base import CloudResourceAdapter


def build_cloud_backend(provider: str, credentials: dict):
    if provider == "google_drive":
        from storage.google_drive_backend import GoogleDriveBackend  # lazy import

        return GoogleDriveBackend(credentials)

    if provider == "onedrive":
        from storage.onedrive_backend import OneDriveBackend  # lazy import

        return OneDriveBackend(credentials)

    if provider == "nextcloud":
        from storage.nextcloud_backend import NextcloudBackend  # lazy import

        return NextcloudBackend(
            credentials["server_url"],
            credentials["username"],
            credentials["password"],
        )

    if provider == "webdav":
        from storage.webdav_backend import WebDAVBackend  # lazy import

        return WebDAVBackend(
            credentials["server_url"],
            credentials["username"],
            credentials["password"],
        )

    raise ValueError(f"Unknown provider: {provider}")


def build_cloud_resource_adapter(provider: str, credentials: dict) -> CloudResourceAdapter:
    """Build a CloudResourceAdapter for the given provider and credentials.

    Returns a provider instance that implements the CloudResourceAdapter read-only
    interface (list_folder, get_capabilities, merge_item_capabilities). All four
    supported providers implement CloudResourceAdapter as a mixin alongside
    their StorageBackend interface.

    Raises:
        ValueError: If provider is not one of the four supported cloud providers.
    """
    backend = build_cloud_backend(provider, credentials)
    if not isinstance(backend, CloudResourceAdapter):
        raise ValueError(
            f"Provider {provider!r} backend does not implement CloudResourceAdapter"
        )
    return backend
