import boto3
import os
import uuid

from app.core.config import settings

class S3Service:
    def __init__(self):
        self.s3 = boto3.client(
            "s3",
            region_name=settings.AWS_REGION,
            aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
            aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
        )
        self.bucket = os.getenv("AWS_S3_BUCKET") or settings.AWS_S3_BUCKET

    def upload_fileobj(self, file_obj, filename=None, content_type=None):
        if filename is None:
            filename = str(uuid.uuid4())
        extra_args = {}
        if content_type:
            extra_args["ContentType"] = content_type
        self.s3.upload_fileobj(
            file_obj,
            self.bucket,
            filename,
            ExtraArgs=extra_args
        )
        url = f"https://{self.bucket}.s3.{settings.AWS_REGION}.amazonaws.com/{filename}"
        return url