import requests
import json
import config
from logger_config import logger

APPID = config.config["SCKJ_APPID"]
API_KEY = config.config["SCKJ_APIKey"]
NLP_URL = config.config["SCKJ_NLP_URL"]


def create_dialog():
    # 定义要发送的数据
    data = {"code": APPID, "appKey": API_KEY}

    # 将数据转换为 JSON 格式
    json_data = json.dumps(data)

    # 设置请求头部
    headers = {
        "Content-Type": "application/json"
    }

    # 发送 POST 请求
    response = requests.post(NLP_URL + "/create", data=json_data, headers=headers)

    # 检查响应状态码
    if response.status_code == 200:
        # 打印响应内容
        logger.info(f"创建对话成功：{response.json()}")
        return {"did": response.json()['data']['id'], "hotwords": response.json()['data']['hotwords']}
    else:
        logger.info(f"创建对话失败，Error http code: {response.status_code}")
        return {}


def get_nlp_result(did, text):
    # 定义要发送的数据
    data = {"id": did, "input": text, "timeout": False}

    # 将数据转换为 JSON 格式
    json_data = json.dumps(data)

    # 设置请求头部
    headers = {
        "Content-Type": "application/json"
    }

    # 发送 POST 请求
    response = requests.post(NLP_URL + "/input", data=json_data, headers=headers)

    # 检查响应状态码
    if response.status_code == 200:
        # 打印响应内容
        logger.info(f"语义理解结果：{response.text}")
        return response.text
    else:
        logger.info(f"语义理解失败，Error http code: {response.status_code}")
        return ''


def end_dialog(did):
    # 定义要发送的数据
    data = {"id": did}

    # 将数据转换为 JSON 格式
    json_data = json.dumps(data)

    # 设置请求头部
    headers = {
        "Content-Type": "application/json"
    }

    # 发送 POST 请求
    response = requests.post(NLP_URL + "/end", data=json_data, headers=headers)

    # 检查响应状态码
    if response.status_code == 200:
        # 打印响应内容
        print("结束对话结果：", response.json())
        return response.text
    else:
        print("结束对话失败，Error http code:", response.status_code)
        return ''
