import boto3
from django.conf import settings
from botocore.config import Config
import logging
from django.core.files.base import File

logger = logging.getLogger(__name__)

class R2Storage:
    def __init__(self):
        self.client = boto3.client('s3',
            endpoint_url=settings.R2_ENDPOINT_URL,
            aws_access_key_id=settings.R2_ACCESS_KEY_ID,
            aws_secret_access_key=settings.R2_SECRET_ACCESS_KEY,
            config=Config(signature_version='s3v4'),
            region_name='auto'
        )
        self.bucket = settings.R2_BUCKET_NAME

    def upload_file(self, file_obj, key, content_type=None):
        """Upload a file to R2"""
        try:

            # Reset file pointer and read content
            file_obj.seek(0)
            file_content = file_obj.read()

            if not file_content:
                raise ValueError("File content is empty")

            from io import BytesIO
            file_data = BytesIO(file_content)

            extra_args = {
                'ContentType': content_type or 'application/octet-stream',
            }

            self.client.upload_fileobj(
                file_data,
                self.bucket,
                key,
                ExtraArgs=extra_args
            )

            return key

        except Exception as e:
            logger.error(f"Upload failed: {str(e)}", exc_info=True)
            raise

    def get_url(self, key, expires_in=3600, width=None, height=None, fit=None):
        """Generate a signed URL that expires after the specified time"""
        if not key:
            return None
        try:
            # Get the signed URL to extract auth parameters
            url = self.client.generate_presigned_url(
                'get_object',
                Params={
                    'Bucket': self.bucket,
                    'Key': key
                },
                ExpiresIn=expires_in
            )

            if not hasattr(settings, 'R2_CUSTOM_DOMAIN'):
                return url

            # Extract authentication parameters
            from urllib.parse import urlparse, parse_qs
            parsed = urlparse(url)
            query_params = parse_qs(parsed.query)
            
            # Build the authentication query string
            auth_params = []
            for param_key in sorted(query_params.keys()):  # Sort to maintain consistent order
                auth_params.append(f"{param_key}={query_params[param_key][0]}")
            auth_string = "&".join(auth_params)

            # If width is specified, create a thumbnail URL
            if width:
                options = []
                if width:
                    options.append(f"width={width}")
                if height:
                    options.append(f"height={height}")
                if fit:
                    options.append(f"fit={fit}")
                
                # Format: https://custom.domain/cdn-cgi/image/options/key?auth-params
                return f"https://{settings.R2_CUSTOM_DOMAIN}/cdn-cgi/image/{','.join(options)}/{key}?{auth_string}"
            
            # Format: https://custom.domain/key?auth-params
            return f"https://{settings.R2_CUSTOM_DOMAIN}/{key}?{auth_string}"

        except Exception as e:
            logger.error(f"Failed to generate signed URL: {str(e)}")
            return None
