from qcloud_cos import CosConfig, CosS3Client
import os
from urllib.parse import quote

def upload_to_tencent_cos(
    local_file_path: str,
    cos_secret_id: str,
    cos_secret_key: str,
    cos_region: str,
    cos_bucket_name: str,
    cos_key_path: str
) -> str:
    """
    上传文件到腾讯云COS，覆盖同名文件。
    成功返回COS URL，失败返回空字符串。

    Args:
        local_file_path (str): 本地文件路径
        cos_secret_id (str): 腾讯云SecretId
        cos_secret_key (str): 腾讯云SecretKey
        cos_region (str): 地域，如 'ap-guangzhou'
        cos_bucket_name (str): 存储桶名称
        cos_key_path (str): COS上的路径前缀，如 'uploads/pva/12345'

    Returns:
        str: 成功返回URL，失败返回空字符串 ""
    """
    # 检查本地文件是否存在
    if not os.path.exists(local_file_path):
        print(f"❌ 本地文件不存在: {local_file_path}")
        return ""

    try:
        # 初始化配置
        config = CosConfig(
            Region=cos_region,
            SecretId=cos_secret_id,
            SecretKey=cos_secret_key,
            Scheme='https'
        )
        client = CosS3Client(config)

        # 生成COS对象键：cos_key_path/文件名
        filename = os.path.basename(local_file_path)
        cos_object_key = f"{cos_key_path.rstrip('/')}/{filename}"

        # 构建最终URL
        encoded_key = quote(cos_object_key, safe='/ ')
        file_url = f'https://{cos_bucket_name}.cos.{cos_region}.myqcloud.com/{encoded_key}'

        # 执行上传（自动覆盖同名文件）
        print(f"🔄 开始上传: {local_file_path} → {cos_object_key}")
        response = client.upload_file(
            Bucket=cos_bucket_name,
            LocalFilePath=local_file_path,
            Key=cos_object_key,
            PartSize=1,
            MAXThread=5,
            EnableMD5=False
        )

        if response is not None:
            print(f"✅ 上传成功: {file_url}")
            return file_url  # ✅ 成功：返回URL
        else:
            print("❌ 上传失败：响应为空")
            return ""  # ❌ 失败：返回空字符串

    except Exception as e:
        print(f"❌ 上传异常: {str(e)}")
        return ""  # ❌ 任何错误都返回空字符串

