import json
import os
from django.core.management.base import BaseCommand
import boto3
from botocore.config import Config

class Command(BaseCommand):
    help = "Configure CORS on OVH S3 bucket"

    def handle(self, *args, **kwargs):
        bucket_name = os.getenv("STORAGE_BUCKET_NAME")
        endpoint_url = os.getenv("OVH_ENDPOINT")
        region = os.getenv("OVH_CLOUD_REGION_NAME", "waw")

        config = Config(
            region_name=region,
            signature_version="s3v4",
            request_checksum_calculation="when_required",
            response_checksum_validation="when_required",
            s3={"addressing_style": "path", "payload_signing_enabled": False},
        )

        client = boto3.client(
            "s3",
            aws_access_key_id=os.getenv("ACCESS_KEY_ID"),
            aws_secret_access_key=os.getenv("SECRET_ACCESS_KEY"),
            endpoint_url=endpoint_url,
            config=config,
        )

        with open("cors.json") as f:
            cors_config = json.load(f)

        try:
            client.put_bucket_cors(Bucket=bucket_name, CORSConfiguration=cors_config)
            self.stdout.write(self.style.SUCCESS("✅ CORS configuration uploaded successfully."))
        except Exception as e:
            self.stderr.write(self.style.ERROR(f"❌ Error setting CORS: {e}"))
