from cloud_storage_clients.connector import Connector
from cloud_storage_clients.responses import GetUploadUrlResponse
from cloud_storage_clients.s3.client import S3Client


class OvhClient(S3Client):
    """OVHcloud Object Storage client using the S3-compatible API.

    OVHcloud exposes an S3-compatible endpoint per region at:
        https://s3.<region>.io.cloud.ovh.net

    OVHcloud does **not** support S3 POST-based presigned uploads
    (generate_presigned_post), so we override the upload method to use
    a presigned PUT URL instead.

    Ref: https://help.ovhcloud.com/csm/en-public-cloud-storage-s3-getting-started-with-object-storage
    """

    def __init__(self, connector: Connector, credentials: dict | None):
        if not credentials:
            raise ValueError("OVH credentials are required")

        region_name = credentials.get("region_name")
        if not region_name:
            raise ValueError("region_name is required for OVH")

        credentials = {
            **credentials,
            "endpoint_url": f"https://s3.{region_name}.io.cloud.ovh.net",
        }

        super().__init__(connector, credentials, default_region_name=None)

    def get_upload_url(
        self, object_name: str, file_type: str, expiration: int
    ) -> GetUploadUrlResponse:
        """Generate a presigned PUT URL for OVHcloud (POST is not supported)."""
        url = self._client.generate_presigned_url(
            ClientMethod="put_object",
            Params={
                "Bucket": self.bucket,
                "Key": object_name,
                "ContentType": file_type,
            },
            ExpiresIn=expiration,
        )
        return GetUploadUrlResponse(url=url, fields={})
