# pylint: disable=import-outside-toplevel
import io
import logging
from typing import List, Dict, Any

logger = logging.getLogger(__name__)


class StorageService:
    """Service for storage operations (MinIO/S3)."""

    def __init__(self, storage=None):
        """
        Initialize storage service.

        Args:
            storage: Storage instance (defaults to StorageFactory.from_env())
        """
        if storage is None:
            from mini_videorag.storage.factory import StorageFactory

            self.storage = StorageFactory.from_env()
        else:
            self.storage = storage

    async def upload_file(self, key: str, content: bytes) -> Dict[str, Any]:
        """
        Upload a file to storage.

        Args:
            key: Storage key (e.g., 'videos/myvideo.mp4')
            content: File content as bytes

        Returns:
            Dict with key, s3_path, size, message
        """
        file_obj = io.BytesIO(content)

        self.storage.upload(file_obj, key)

        logger.info(f"Uploaded file to storage: {key} ({len(content)} bytes)")

        return {
            "key": key,
            "s3_path": f"s3://{self.storage.bucket_name}/{key}",
            "size": len(content),
            "message": f"File uploaded successfully. Use 's3://{self.storage.bucket_name}/{key}' in workflows.",
        }

    def list_objects(self, prefix: str = "") -> List[Dict[str, Any]]:
        """
        List objects in storage.

        Args:
            prefix: Prefix filter for object keys

        Returns:
            List of object dicts with key, size, last_modified, content_type
        """
        objects = self.storage.list(prefix=prefix)

        return [
            {
                "key": obj.key,
                "size": obj.size,
                "last_modified": obj.last_modified,
                "content_type": obj.content_type,
            }
            for obj in objects
        ]

    def get_presigned_url(self, key: str, expires_in: int = 3600) -> Dict[str, str]:
        """
        Get presigned URL for a storage object.

        Args:
            key: Storage object key
            expires_in: URL expiration time in seconds (default: 1 hour)

        Returns:
            Dict with key, url, expires_in

        Raises:
            ValueError: If object doesn't exist
        """
        if not self.storage.exists(key):
            raise ValueError(
                f"Object not found: {key}. Use /storage/objects to list available objects."
            )

        url = self.storage.get_url(key, expires_in=expires_in)

        return {"key": key, "url": url, "expires_in": expires_in}
