"""
Storage Backend Factory

Creates appropriate storage backend based on configuration
"""

from loguru import logger

from config.settings import settings
from .base import StorageBackend
from .filesystem import LocalStorage
from .s3 import S3Storage


def get_storage_backend() -> StorageBackend:
    """
    Get storage backend based on configuration

    Returns:
        StorageBackend instance (LocalStorage or S3Storage)

    Raises:
        ValueError: If storage type is invalid
    """

    if settings.use_local_storage:
        logger.info(f"Using LocalStorage: {settings.storage_path}")
        return LocalStorage(base_path=settings.storage_path)

    elif settings.use_s3_storage:
        logger.info(f"Using S3Storage: bucket={settings.storage_bucket}")

        if not settings.aws_access_key_id or not settings.aws_secret_access_key:
            raise ValueError("AWS credentials not configured for S3 storage")

        return S3Storage(
            bucket=settings.storage_bucket,
            access_key=settings.aws_access_key_id,
            secret_key=settings.aws_secret_access_key,
            endpoint=settings.s3_endpoint,
            region=settings.aws_region
        )

    else:
        raise ValueError(f"Unknown storage type: {settings.storage_type}")


# Create a singleton instance for convenience
_storage_instance = None


def get_storage() -> StorageBackend:
    """
    Get singleton storage instance

    Returns:
        Global storage backend instance
    """
    global _storage_instance

    if _storage_instance is None:
        _storage_instance = get_storage_backend()

    return _storage_instance
