import requests
import json
import time
import os ,sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
from aidso_geo.utils import bh_utils


def task_commit_api(task_data):
    url = "http://172.16.1.223:8086/api/geo/task_commit"
    keep_fields = ["prompt", "taskId", "reqId", "platform", "type", "thinkingEnabled"]

    data = {k: i.get(k) for k in keep_fields}
    fields = ["prompt", "taskId", "reqId", "platform", "type", "thinkingEnabled"]
    payload = {k: data.get(k) for k in fields}
    headers = {
       'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, json=payload)
    try:
        response_data = response.json()
        print(response.text)
        if response_data.get("code") == 200:
            task_data["status"] = 'PROCESSING'
            bh_utils.insert_data("geo_third_task_data",[task_data])
    except Exception as e:
        print(e)

def get_result_api(task_data):
    req_id = task_data.get('reqId')
    url = f"http://172.16.1.223:8086/api/geo/task_check?reqId={req_id}"

    payload={}

    response = requests.request("GET", url, data=payload)
    try:
        response_data = response.json()
        if response_data.get("code") == 200 and response_data.get('data').get('status') == 'success':
            task_data["status"] = 'SUCCESS'
            bh_utils.insert_data("geo_third_task_data",[task_data])
    except Exception as e:
        print(e)

def task_commit():
    data_list = bh_utils.query_data("select * from geo_third_task_data where status = 'ING' ")
    return data_list


def get_task():
    data_list = bh_utils.query_data(
        "select * from geo_third_task_data where status = 'PROCESSING' ")
    return  data_list

if __name__ == '__main__':
    try:
        while 1:
            commit_data_list = task_commit()

            if commit_data_list:
                for i in commit_data_list:
                    task_commit_api(i)
            task_data_list = get_task()
            if task_data_list:
                for i in task_data_list:
                    get_result_api(i)
            # print('sleep')
            time.sleep(10)
    except Exception as e:
        print(e)


    # {"prompt": "羽绒服品牌推荐?",
    #  "taskId": "21fd537f-131b-469a-9d5c-6eaccc00da2c11011d61",
    #  "reqId": "5f4d87b5-7c9e-4095-81d2-7fb9ccccc44cff111111e1",
    #  "platform": "TYQWA",
    #  "type": "stream",
    #  "thinkingEnabled": "1"}