import json
import os
import time
from datetime import datetime

from alibabacloud_dyvmsapi20170525.client import Client as Dyvmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dyvmsapi20170525 import models as dyvmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
from .._common.logger import logger

class CallUtil:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Dyvmsapi20170525Client:
        """
        使用AK&SK初始化账号Client
        @return: Client
        @throws Exception
        """
        # 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        # 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378659.html。
        config = open_api_models.Config(
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        # Endpoint 请参考 https://api.aliyun.com/product/Dyvmsapi
        config.endpoint = f'dyvmsapi.aliyuncs.com'
        return Dyvmsapi20170525Client(config)

    @staticmethod
    def call(
        called_number: str, message: str, called_show_number : str = '05923396264'
    ) -> None:
        client = CallUtil.create_client()
        ttl_param = {"info": message}
        single_call_by_tts_request = dyvmsapi_20170525_models.SingleCallByTtsRequest(
            called_show_number=called_show_number,
            called_number=called_number,
            tts_code='TTS_305560006',
            tts_param=str(ttl_param)
        )
        runtime = util_models.RuntimeOptions()
        try:
            resp = client.single_call_by_tts_with_options(single_call_by_tts_request, runtime)
            resp_str = UtilClient.to_jsonstring(resp)
            logger.info(f"call response: {resp_str}")
            json_data = json.loads(resp_str)
            if json_data['statusCode'] != 200:
                raise Exception(f"status code is {json_data['statusCode']}")
            if json_data['body']['Code'] != 'OK':
                raise Exception(f"code is {json_data['body']['Code']} message is {json_data['body']['Message']}")
            call_id = json_data['body']['CallId']
            time_str = json_data['headers']['date']
            dt = datetime.strptime(time_str, "%a, %d %b %Y %H:%M:%S %Z")
            timestamp = time.mktime(dt.timetuple())
            return call_id, int(timestamp * 1000)
        except Exception as error:
            raise error

    @staticmethod
    def get_call_status(call_id: str, timestamp: int):
        client = CallUtil.create_client()
        query_call_detail_by_call_id_request = dyvmsapi_20170525_models.QueryCallDetailByCallIdRequest(
            call_id=call_id,
            prod_id=11000000300006,
            query_date=timestamp
        )
        runtime = util_models.RuntimeOptions()
        try:
            resp = client.query_call_detail_by_call_id_with_options(query_call_detail_by_call_id_request, runtime)
            resp_str = UtilClient.to_jsonstring(resp)
            logger.info(f"get call status response: {resp_str}")
            json_data = json.loads(resp_str)
            if json_data['statusCode'] != 200:
                raise Exception(f"status code is {json_data['statusCode']}")
            if json_data['body']['Code'] != 'OK':
                raise Exception(f"code is {json_data['body']['Code']} message is {json_data['body']['Message']}")
            result = json.loads(json_data['body']['Data'])
            return result['state'], result['stateDesc']
        except Exception as error:
            raise error

