import json
import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from aidso_geo.clients.tos_client import tos_client
import tos
import requests
from io import BytesIO
from PIL import Image


def put_string_to_tos(object_key: str, content, retry_times: int = 3) -> bool:
    client = tos_client.get_client()
    bucket = tos_client.bucket_name

    for i in range(retry_times):
        try:

            # 如果是字符串，直接使用；否则序列化为JSON字符串
            if isinstance(content, str):
                content_str = content
            else:
                content_str = json.dumps(content, ensure_ascii=False)  # 保留中文等非ASCII字符

            client.put_object(bucket, object_key, content=content_str)
            return True
        except Exception as e:

            continue

    return False


def get_string_from_tos(object_key, retry_times=5):
    client = tos_client.get_client()
    bucket = tos_client.bucket_name
    for _ in range(retry_times):
        try:
            response = client.get_object(bucket, object_key)
            content = response.read().decode('utf-8')
            return content
        except tos.exceptions.TosServerError as e:
            continue
        except Exception:
            continue

    return False


def check_file_in_tos(object_key):
    try:

        client = tos_client.get_client()
        bucket = tos_client.bucket_name
        client.head_object(bucket=bucket, key=object_key)
        return True
    except Exception as e:
        return False
    
def get_tos_file_size(object_key: str, retry_times: int = 3):
    client = tos_client.get_client()
    bucket = tos_client.bucket_name

    for i in range(retry_times):
        try:
            result = client.head_object(bucket, object_key)

            # 兼容不同 SDK 字段命名
            size = getattr(result, "content_length", None)
            if size is None:
                size = getattr(result, "contentLength", None)
            if size is None:
                size = getattr(result, "content-length", None)

            return int(size) if size is not None else None

        except Exception as e:
            return None

    return None






def save_image_to_tos(image_url, tos_path=None):

    client = tos_client.get_client()
    bucket = tos_client.bucket_name

    try:

        # 下载图片
        resp = requests.get(
            image_url,
            timeout=10,
            headers={
                "User-Agent": "Mozilla/5.0"
            }
        )


        if resp.status_code != 200:

            print(
                f"图片下载失败:{image_url}, status={resp.status_code}"
            )

            return None



        # 打开图片
        image = Image.open(
            BytesIO(resp.content)
        )


        # 转RGB，保证可以保存JPEG
        image = image.convert("RGB")



        # 转jpg二进制
        buffer = BytesIO()

        image.save(
            buffer,
            format="JPEG",
            quality=95
        )

        buffer.seek(0)


        tos_path = str(tos_path)

        if not tos_path.endswith(".jpg"):

            tos_path += ".jpg"



        # 上传TOS
        client.put_object(
            bucket,
            tos_path,
            content=buffer.getvalue(),
            content_type="image/jpeg"
        )




        return tos_path



    except Exception as e:

        print(
            f"保存图片到TOS失败:{image_url}, error={e}"
        )

        return None

