import time
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


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


if __name__ == '__main__':
    path = f'geo/5ef9bbf4-b356-40af5d44fff30a/TXYB/original.text'
    # put_string_to_tos('geo/1005/DP/aaaa.txt',"['2025年11月5日 天气']")
    # print(check_file_in_tos('geo/1d38cb5e-0b99-49e8-8f68-13688079b719/DP/result.json'))
    print(get_tos_file_size(path))
