# -*- coding: utf-8 -*-

import time
import tos
from io import StringIO
import json


TOS_AK = "AKLTMmRiMmU3YmY5ZjZjNDZkMTlhMmQxY2JkYTllYTQzNDI"
TOS_SK = "WkdWak4yUTRNakl3WVdOa05HUXdaR0V4TlRBM1l6YzJZMll5WkRnMFlUTQ=="
TOS_ENDPOINT = "tos-cn-beijing.volces.com"
TOS_REGION = "cn-beijing"
TOS_BUCKET_NAME = "douchacha-web"


def check_file_in_tos(object_key, retry_times=50):
    retry_count = 0
    while retry_count <= retry_times:
        try:
            client = tos.TosClientV2(TOS_AK, TOS_SK, TOS_ENDPOINT, TOS_REGION, max_retry_count=3)
            client.head_object(bucket=TOS_BUCKET_NAME, key=object_key)
            return True
        except (tos.exceptions.TosClientError,
                tos.exceptions.TosServerError,
                Exception) as e:
            if isinstance(e, tos.exceptions.TosServerError) and e.status_code == 404:
                retry_count += 1
                time.sleep(5)
                if retry_count > retry_times:
                    return False



def put_string_to_tos( object_key, content, retry_times=3):
    client = tos.TosClientV2(TOS_AK, TOS_SK, TOS_ENDPOINT, TOS_REGION, max_retry_count=3)
    for _ in range(retry_times):
        try:

            client.put_object(TOS_BUCKET_NAME, object_key, content=json.dumps(content))
            return True
        except Exception as e:
            print(e)

            continue
    return False

def get_string_from_tos( object_key, retry_times=3):
    client = tos.TosClientV2(TOS_AK, TOS_SK, TOS_ENDPOINT, TOS_REGION, max_retry_count=3)
    for _ in range(retry_times):
        try:

            response = client.get_object(TOS_BUCKET_NAME,object_key)
            content = response.read()
            return json.loads(content)
        except tos.exceptions.TosServerError as e:
            if e.status_code == 404:
                print(f"文件不存在: {object_key}")
                return None
        except (tos.exceptions.TosClientError, json.JSONDecodeError) as e:
            print(f"JSON解析失败")

    return False




