import json
import traceback

from aidso_geo.utils import robot_utils, bh_utils
from aidso_geo.utils.ai_interface import get_parse_sse_result
from aidso_geo.utils.bh_utils import query_data
from aidso_geo.utils.tos_utils import get_string_from_tos
from aidso_geo.models import spider_save_tos


def kimi_process_original_data(data):
    file_path = f'geo/{data["taskId"]}/{data["platform"]}/original.text'
    url_list = []
    think_content = ""
    response_content = ""
    search_keyword = []
    suggestions = []
    is_think = False
    think_bool = False
    response_bool = False


    try:
        original_content = get_string_from_tos(file_path)

        original_content_list = json.loads(original_content)

        if isinstance(original_content_list, list):
            for item in original_content_list:
                block_data = item.get('block', {})
                think_data = block_data.get('think', {})
                text_data = block_data.get('text', {})

                if item.get('mask') == 'block.search' or item.get('mask') == 'block.search.keywords':
                    search_keyword.append(block_data.get('search').get('keywords')[0])

                # if item.get('mask') == 'block.search.webPages':
                #     url_list.extend(block_data.get('search').get('webPages'))
                if item.get('mask') =='message.refs.usedSearchChunks':

                    searchChunks = item.get('message').get("refs").get('usedSearchChunks')
                    if searchChunks:
                        for i in searchChunks:

                            new_item = i['base'].copy()
                            new_item['id'] = i['id']
                            new_item['refIndex'] = i.get('refIndex')
                            url_list.append(new_item)
                if item.get('mask') =='message.refs.searchChunks' and len(url_list) ==0:
                    searchChunks = item.get('message').get("refs").get('searchChunks')
                    if searchChunks:
                        for i in searchChunks:
                            new_item = i['base'].copy()
                            new_item['id'] = i['id']
                            new_item['refIndex'] = i.get('refIndex')
                            url_list.append(new_item)
                if item.get('mask') == 'block.think.content' or item.get('mask') == 'block.think':
                    if think_data.get('content'):
                        think_content += think_data.get('content')
                if item.get('mask') == 'block.text.content' or item.get('mask') == 'block.text':
                    if text_data.get('content'):
                        response_content += text_data.get('content')
                if item.get('mask') == 'block.error' and response_content == "":
                    response_content+=item.get('block').get('error').get("localizedMessage").get("message")
            spider_save_tos.process_and_save_files(file_path, search_keyword, url_list, think_content, response_content,
                                                   suggestions)
            return (file_path, search_keyword, url_list, think_content, response_content, suggestions)
    except Exception as e:
        parts = file_path.split('/')
        platform = parts[2]
        task_id = parts[1]
        context, quote, suggestion, think, search_word = get_parse_sse_result(platform, task_id)
        if context:
            response_content = context
            url_list = quote
            suggestions = suggestion
            think_content = think
            search_keyword = search_word
            spider_save_tos.process_and_save_files_ai(file_path, search_keyword, url_list, think_content,
                                                      response_content, suggestions)

            return (file_path, search_keyword, url_list, think_content, response_content, suggestions)
        else:
            response_content = "对话信息获取失败:-200"
            robot_utils.feishu_tobot(file_path)

    spider_save_tos.process_and_save_files(file_path, search_keyword, url_list, think_content, response_content,
                                           suggestions)
    return (file_path, search_keyword, url_list, think_content, response_content, suggestions)


if __name__ == '__main__':
    # result = bh_utils.query_data("select * from geo_commit_task where platform = 'KIMI' and insertime >1778428800 order by insertime asc ")
    # # # result = []
    # for i in result:
    #     file_path = f"geo/{i.get('taskId')}/KIMI/original.text"
    #     kimi_process_original_data(file_path)
    # task = 'a652a0f1-781a-4171-8764-ab30d96031ab'
    data_list = bh_utils.query_data(f"select * from geo_commit_task  where taskId = '45817021-a93b-434a-bba1-958dd0d69a1b' and  platform  = 'KIMI'")

    # # #
    # # #
    # # # # #
    def handle_item(i):
        if i.get('comWordsMap'):
            i['comWordsMap'] = json.loads(i.get('comWordsMap'))
        if i.get('brandWords'):
            i['brandWords'] = json.loads(i.get('brandWords'))
        if i.get('comWords'):
            i['comWords'] = json.loads(i.get('comWords'))
        if i.get('keywords'):
            i['keywords'] = json.loads(i.get('keywords'))
        if i.get('productWordsMap'):
            i['productWordsMap'] = json.loads(i.get('productWordsMap'))

        return kimi_process_original_data(i)


    if data_list:
        for i in data_list:
            try:
                handle_item(i)
            except Exception as e:
                ...


