import time
import json
import requests
import traceback
from config import set_config
from log import Log
from moon_shoot_api import MoonShotHandle

config_ = set_config()
log_ = Log()
moonShotHandle_ = MoonShotHandle()


def get_tag(prompt):
    retry = 1
    result_content = None
    while retry < 3:
        try:
            log_.info(f"retry = {retry}")
            headers = {
                'Content-Type': 'application/json',
                # 'Authorization': f'Bearer {os.environ["OPENAI_API_KEY"]}',
                'Authorization': f'Bearer {config_.GPT_OPENAI_API_KEY}',
            }
            proxies = config_.PROXIES
            json_data = {
                'model': 'gpt-3.5-turbo',
                'messages': [
                    {
                        'role': 'user',
                        'content': f'{prompt}',
                    },
                ],
            }
            response = requests.post(
                url=config_.GPT_HOST, headers=headers, json=json_data, proxies=proxies)
            print(response.json())
            print(response.json()['choices'][0]['message']['content'])
            print('\n')
            result_content = response.json(
            )['choices'][0]['message']['content']
            return result_content
        except Exception as e:
            print(e)
            log_.error(traceback.format_exc())
            retry += 1
            time.sleep(30)
            continue
    return result_content


def request_gpt(prompt):
    retry_count = 0
    result_content = None
    while retry_count < config_.RETRY_MAX_COUNT:
        retry_count += 1
        try:
            result_content = moonShotHandle_.chat(prompt)
            # response = requests.post(url=config_.GPT_URL, json={'content': prompt, 'auth': config_.GPT_OPENAI_API_KEY})
            # response = requests.post(url=config_.GPT_URL, json={'content': prompt})
            # print(response.json())
            # print(response.json()['choices'][0]['message']['content'])
            # print('\n')
            # result_content = response.json()['choices'][0]['message']['content']
            # log_.info(f"response.text: {response.text}")
            # res_data = json.loads(response.text)
            # if res_data['code'] != 0:
            #     time.sleep(10)
            #     continue
            # result_content = res_data['data']['choices'][0]['message']['content']
            if "```json" in result_content:
                result_content = result_content.split(
                    "```json")[1].split("```")[0]
            return result_content
        except Exception:
            log_.error(traceback.format_exc())
            time.sleep(10)
            continue
    return result_content


# res = MoonShotHandle().chat("'\n请对如下文本进行：\n1. 用20个字以内对文本内容进行概况。\n2. 列举三个关键词。\n仅以json格式返回，key为summary, keywords。分别代表概要，关键词。\n-----------------------------\n养肺离不开吃最润肺的食物推荐给大家第一个是山药山药是润肺的最佳食品之一大家在平时的时候可以吃最好的吃法是做成山药粥或者是直接的清炒山药就可以了不适合与其他的食物相配第二个是梨这个大家都很清楚梨水是用来清肺的润肺的所以梨对于肺来讲是个好东西因为它的水多又好消化最好的吃法是做成梨汤或者是梨水加入冰糖吃这种梨肉喝汤就可以了第三个是百合百合是白色的食物两肺就适合吃这种白色的食物它是能够清肺润肺的最好的吃法依然是清炒不用加太多的调料清淡的口味就行了第四个是银耳银耳也是咱们中医推荐的用于润肺养肺的食物之一最好的吃法就是直接打成汤或者再加上枸杞还有红枣这样会让银耳的效果更出众另外也可以加点白糖增加一下能量第五是白萝卜萝卜有通气之处而肺是需要过气的所以吃萝卜可以让我们的通气但对于肺的功能它是有很好的通畅效果所以吃萝卜也是可以清肺的'")
# res = res.split("```json")[1].split("```")[0]
# print(res)
