import boto3
from botocore.exceptions import BotoCoreError, ClientError
from app.core.config import settings
from app.core.logging import logger
from typing import BinaryIO, Optional


# Initialize S3 client
s3_client = boto3.client(
    "s3",
    aws_access_key_id=settings.CLOUDINARY_API_KEY,
    aws_secret_access_key=settings.CLOUDINARY_API_SECRET,
)

BUCKET_NAME = settings.CLOUDINARY_BUCKET_NAME


def upload_image_to_s3(
    image_bytes: BinaryIO,
    file_name: str,
    content_type: str = "image/png"
) -> Optional[str]:
    """
    Upload an image to S3 and return the public CloudFront URL.

    Args:
        image_bytes (BinaryIO): File-like object (e.g., io.BytesIO).
        file_name (str): Target file name (including path if needed).
        content_type (str): MIME type of the file (default: image/png).

    Returns:
        str | None: Public CloudFront URL of the uploaded image, or None if failed.
    """
    try:
        s3_client.upload_fileobj(
            image_bytes,
            BUCKET_NAME,
            file_name,
            ExtraArgs={"ContentType": content_type},
        )
        image_url = f"https://{settings.CLOUD_FRONT_URL}/{file_name}"
        # logger.info(f"Uploaded processed image to S3: {image_url}")
        return image_url
    except (BotoCoreError, ClientError) as e:
        logger.error(f"Error uploading file to S3: {e}")
        return None
