import json
import traceback

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


def doubao_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
    rich_media_block = []
    think_bool = False
    response_bool = False

    try:
        original_content = get_string_from_tos(file_path)
        content_list = original_content.split("\n")

        for i in content_list:

            if i != "":

                if not i.startswith("data:"):
                    continue

                payload = i[len("data:"):].lstrip()
                if not payload:
                    continue

                try:
                    json_content = json.loads(payload)

                except (IndexError, json.JSONDecodeError):
                    continue

                if json_content.get('event_type') == 2001:

                    even_data = json.loads(json_content.get('event_data'))

                    message_data = even_data.get('message')
                    if even_data.get('tts_content') is not None:
                        response_content = even_data.get('tts_content')
                    if message_data.get('content_type') == 2007 :
                        for i in json.loads(message_data.get('content')).get("search_result").get("video_card").get("card_list"):
                            rich_media_block.append(i)
                    if message_data.get('content_type') == 10040 and message_data.get('is_finish') is None:
                        think_bool = True

                        continue
                    if message_data.get('content_type') == 10040 and message_data.get('is_finish') == True:
                        think_bool = False
                        continue
                    if think_bool:
                        if json.loads(message_data.get('content')).get('text') is not None:
                            think_content += json.loads(message_data.get('content')).get('text')
                        content_json = json.loads(message_data.get('content'))

                        if message_data.get('content_type') == 10025 and content_json.get('results') is not None:
                            think_content += "\n\n"
                            think_content += "**搜索"
                            think_content += str(len(content_json.get('queries')))
                            think_content += "个关键词，参考"
                            think_content += str(len(content_json.get('results')))
                            think_content += "篇文章**"
                            think_content += "\n\n"

                    if message_data.get('content_type') == 10025:

                        content_json = json.loads(message_data.get('content'))
                        if content_json.get('queries') is not None and content_json.get('results') is not None:
                            search_keyword = search_keyword + json.loads(message_data.get('content')).get('queries')

                        if content_json.get('scene') == 2:
                            url_list = content_json.get('results')

                    if message_data.get('content_type') == 2002:
                        suggestions = suggestions + json.loads(message_data.get('content')).get('suggestions')
                else:

                    if json_content.get("patch_op"):
                        if json_content.get('patch_op')[0].get("patch_object") == 111:
                            if json_content.get('patch_op')[0].get("patch_value").get("tts_content"):
                                response_content += json_content.get('patch_op')[0].get("patch_value").get("tts_content")
                        if json_content.get('patch_op')[0].get("patch_object") == 1:
                            if json_content.get('patch_op')[0].get("patch_value",{}).get("content_block"):
                                if json_content.get('patch_op')[0].get("patch_value",{}).get("content_block")[0].get(
                                        "content",{}).get("search_query_result_block",{}):
                                    search_keyword = json_content.get('patch_op')[0].get("patch_value").get("content_block")[
                                        0].get("content").get("search_query_result_block").get("queries")
                                    url_list = json_content.get('patch_op')[0].get("patch_value").get("content_block")[0].get(
                                        "content").get("search_query_result_block").get("results")
                                    if is_think == True and json_content.get('patch_op')[0].get("patch_value").get("content_block")[0].get(
                                        "content").get("search_query_result_block").get("results") is not None:
                                        think_content += "\n\n"
                                        think_content += "**"
                                        think_content+=json_content.get('patch_op')[0].get("patch_value").get("content_block")[0].get(
                                        "content").get("search_query_result_block").get("summary")
                                        think_content += "**"
                                        think_content += "\n\n"
                                if json_content.get('patch_op')[0].get("patch_value").get("content_block")[0].get(
                                        "block_type") ==10000 and json_content.get('patch_op')[0].get("patch_value").get("content_block")[0].get(
                                        "parent_id") and len(json_content.get('patch_op'))>1:

                                    is_think = True
                                    if json_content.get('patch_op')[0].get("patch_value").get("content_block")[0].get("content").get('text_block').get("text"):
                                        think_content+=json_content.get('patch_op')[0].get("patch_value").get("content_block")[0].get("content").get("text_block").get("text")
                                        continue
                                if json_content.get('patch_op')[0].get("patch_value").get("content_block")[0].get(
                                        "block_type") == 10040:
                                    is_think = False
                                    continue
                        if json_content.get('patch_op')[0].get("patch_object") == 50:
                            for sug in json.loads(
                                    json_content.get('patch_op')[0].get("patch_value").get("ext").get("sp_v2")):
                                suggestions.append(sug.get("content"))
                    if is_think:
                        if json_content.get("text"):
                            think_content += json_content.get("text")
                    else:
                        if json_content.get("content"):
                            content_block = json_content.get("content").get('content_block')
                            if content_block:
                                if len(content_block)>0:
                                    if content_block[0].get('block_type') ==10050:
                                        for i in content_block[0].get('content').get('rich_media_block').get('creations'):
                                            rich_media_block.append(i.get('video'))
                                    if content_block[0].get('block_type') ==10000:
                                        if content_block[0].get("content").get("text_block").get("text"):
                                            response_content = content_block[0].get("content").get("text_block").get("text")

        suggestions = list(set(suggestions))
        spider_save_tos.process_and_save_files(file_path, search_keyword, url_list, think_content, response_content,
                                               suggestions,rich_media_block)
        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,rich_media_block)
    return (file_path, search_keyword, url_list, think_content, response_content, suggestions)




if __name__ == '__main__':


    # task_id_list = [
    #     '8629188a-46c9-429f-8aa6-d342110326f0', 'ba138c4d-2bb4-45e3-bda3-ecf80553ac89',
    #     'e178ee36-b9ca-4f1f-802b-83b5e4b820f0', '52efa2d8-616f-48b9-b656-59833fbb91b8',
    #     '769570cf-c385-4ed7-8e28-f57b5f89d34b', 'cac5bbdb-2145-44a0-9b81-eb20b286d278',
    #     '7d8ad6ad-c784-407e-9e5f-127c15de5c9e', '6a839541-e3f3-4cd6-a33d-366b3c3297b9',
    #     '86bd6c56-18d4-41c4-a75a-8d15da5ca589', 'd7e86e4b-521b-4f6f-a34d-ccc7fa629e09',
    #     '5069cfbb-1150-4bf6-a967-698640c2ce8f', '8bc46734-3469-4681-8a0c-f048169e9486',
    #     '0480d9c5-0ca9-4c5f-a5c9-dfc4db3b5511', '34cfbfae-cf25-49e6-80a9-199d31813bf2',
    #     '1d35ff25-760d-43c4-a24f-210d74e82ffe', 'f1d7ca94-7ddf-4548-9b5f-8890d39e7b6c',
    #     '6fb6c767-54bf-4872-ad60-c52223238d41', '785bf969-4645-4ca7-a9c9-6a5f104a7894',
    #     'e52a3c9c-720a-46c5-98f5-efb3e9d8c597', 'ccc66d28-8843-4ea0-a3b0-2700c655260b',
    #     '3aeee8d2-3086-48c6-a9cb-e29f4a244e34', '67660404-bac4-4bb4-80bb-4b78fd713af0',
    #     '4b0c64e1-8393-4638-ab98-6b14c579912c', '9217ad06-413a-4161-9be8-6150ffe7b4eb',
    #     'e9b27490-6ff0-48da-91a5-3dbbb8494c1d', 'b92b318c71d54c399ed033a722c06a35'
    # ]
    # for task in task_id_list:
    task = 'a090ebc2-8f74-4533-915c-f7352658c42e'
    file_path = f'geo/{task}/DB/original.text'
    doubao_process_original_data(file_path)



