"""
Object Storage Service for FTC Team Website
Uses official Replit Object Storage SDK
"""

from replit.object_storage import Client
from uuid import uuid4
from werkzeug.utils import secure_filename
import os


class ObjectStorageService:
    def __init__(self):
        """Initialize the Replit Object Storage client"""
        self.client = Client()
        self.bucket_name = os.environ.get('OBJECT_STORAGE_BUCKET', 'default')
    
    def upload_file(self, file, folder='uploads'):
        """
        Upload a file to object storage
        
        Args:
            file: Werkzeug FileStorage object
            folder: Folder name (prefix) for organization
        
        Returns:
            str: Path to the uploaded file for serving
        """
        if not file or not file.filename:
            return None
        
        original_filename = secure_filename(file.filename)
        file_extension = os.path.splitext(original_filename)[1]
        unique_filename = f"{uuid4()}{file_extension}"
        object_name = f"{folder}/{unique_filename}"
        
        file_content = file.read()
        
        self.client.upload_from_bytes(object_name, file_content)
        
        return f"/storage/{object_name}"
    
    def get_file_bytes(self, path):
        """Download a file as bytes"""
        object_name = path.replace("/storage/", "")
        return self.client.download_as_bytes(object_name)
    
    def delete_file(self, path):
        """Delete a file from object storage"""
        try:
            object_name = path.replace("/storage/", "")
            self.client.delete(object_name)
            return True
        except:
            return False
    
    def list_files(self):
        """List all files in the bucket"""
        return self.client.list()
