import time

from qcloud_cos import CosConfig, CosS3Client


class CosBucket:
    def __init__(self, secret_id, secret_key, region, bucket_name, token=None):
        self.bucket_name = bucket_name
        self.config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token)
        self.client = CosS3Client(self.config)

    def bucket_upload(self, file_path, key):
        """

        :param file_path:上传的文件本地路径
        :param key: 文件名，不能重复，现在开放的路径：picture/,report/
        :return:
        """
        try:
            # 检查 Key 是否已存在
            existing_keys = self.list_all_keys().get('keys', [])
            if key in existing_keys:
                return {"msg": "error", "code": 1, "error": "Key already exists"}

            # 上传文件
            response = self.client.upload_file(
                Bucket=self.bucket_name,
                LocalFilePath=file_path,
                Key=key,
                PartSize=10,
                MAXThread=10,
                EnableMD5=False
            )
            return {"msg": "success", "code": 0, "ETag": response['ETag']}
        except Exception as e:
            raise e

    def generate_download_url(self, key):
        try:
            url = self.client.get_presigned_url(
                Bucket=self.bucket_name,
                Key=key,
                Method='GET',
                Expired=int(time.time()) + 3600
            )
            return {"msg": "success", "code": 0, "url": url}
        except Exception as e:
            raise e

    def list_all_keys(self):
        try:
            keys = []
            response = self.client.list_objects(
                Bucket=self.bucket_name,
                MaxKeys=100
            )
            for content in response.get('Contents', []):
                keys.append(content['Key'])

            while 'NextMarker' in response:
                response = self.client.list_objects(
                    Bucket=self.bucket_name,
                    Marker=response['NextMarker'],
                    MaxKeys=100
                )
                for content in response.get('Contents', []):
                    keys.append(content['Key'])

            return {"msg": "success", "code": 0, "keys": keys}
        except Exception as e:
            raise e


