import sys
import os
import json


def get_home_env():
    if sys.platform == "win32":
        return 'APPDATA'
    return 'HOME'


def gen_home_doc_path():
    if sys.platform == "win32":
        import ctypes.wintypes
        path_id = 5  # 5:文档 0:桌面
        buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
        ctypes.windll.shell32.SHGetFolderPathW(None, path_id, None, 0, buf)
        path = buf.value
    elif sys.platform == "darwin":
        path = "%s/.iflytek" % (os.environ[get_home_env()])
    elif sys.platform == "linux":
        path = "%s/.iflytek" % (os.environ[get_home_env()])
    else:
        path = "%s/.iflytek" % (os.environ[get_home_env()])
    return path


def gen_output_path(_input):
    _output = f"{_input}/output"
    if not os.path.exists(_output):
        os.makedirs(_output)
    return _output


# 生成json数据模版
def gen_q_data(code, data):
    return {"code": code, "data": data}


# 判断字符串是否包含标点
def symbol_in_word(word):
    if "," in word:
        return 1
    if "." in word:
        return 1
    if "，" in word:
        return 1
    if "。" in word:
        return 1
    if ";" in word:
        return 1
    if "；" in word:
        return 1
    if "?" in word:
        return 1
    if "？" in word:
        return 1
    if "!" in word:
        return 1
    if "！" in word:
        return 1
    return 0


def parse_aiui_v2_result(result_json):
    if result_json and result_json.get("code") == "0" and result_json.get("action") == "result":
        data = result_json.get("data")
        if data and data.get("sub"):
            sub = data.get("sub")
            result = {"code": "0", "sub": sub, "is_last": data.get("is_last"), "is_finish": data.get("is_finish")}
            if sub == "iat":
                text = data.get("text")
                result["pgs"] = text.get("pgs")
                ws_list = text.get("ws")
                words = list(map(lambda ws: ws.get("cw")[0].get("w"), ws_list))
                word = "".join(words)
                result["service"] = "raw"
                result["rawText"] = word
                return result
            elif sub == "nlp":
                intent = data.get("intent")
                if intent:
                    service = intent.get("service")
                    text = intent.get("text")
                    # answer_text = intent.get("answer").get("text")
                    result["service"] = service
                    result["rawText"] = text
                    return result
            elif sub == "tpp":
                content = data.get("content")
                if content:
                    js = json.loads(content)
                    result.update(js)
                    return result
    return result_json
