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 = '96563dfa-af05-497f-a75c-2b2ae348cf5a'
    file_path = f"geo/{task}/KIMI/original.text"
    kimi_process_original_data(file_path)
    # aa = 'https://douchacha-web.tos-cn-beijing.volces.com/geo/2ac65e0ef17642eaa42d440e572f693b/KIMI/original.text'

