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
from aidso_geo.config.base_config import init_redis

def doubao_process_original_data(data):
    thinking_enabled = data.get('thinkingEnabled', '0')
    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)
        try:
            json_assistant = json.loads(original_content)
            search_keyword = json_assistant.get('search_word')
            url_list = json_assistant.get('quto')
            response_content = json_assistant.get('response_content')
            think_content = json_assistant.get('think_content')
            suggestions = json_assistant.get('suggestions')
        except Exception as e:

            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(
                                            "meta_info"):

                                        meta_info = json_content.get('patch_op')[0].get("patch_value").get("content_block")[0].get(
                                            "meta_info")
                                        for meta in  meta_info:
                                            target_title = json.loads(meta.get('info')).get('title')
                                            index = next(
                                                (
                                                    item["text_card"]["index"]
                                                    for item in (url_list or [])
                                                    if item.get("text_card", {}).get("title") == target_title
                                                ),
                                                None
                                            )
                                            if index is not None:
                                                response_content += f"[reference:{index}]"

                                    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:
                                if json_content.get('patch_op')[0].get("patch_value").get("ext").get("sp_v2"):
                                    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))
        if str(thinking_enabled) == '1' and not url_list:
            return (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)
    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__':



    data_list = bh_utils.query_data(f"select * from geo_commit_task  where taskId = '0044cabc-dd1b-493f-a68d-dc7ccdc474b6' and  platform  = 'DB'")

    # # #
    # # #
    # # # # #
    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 doubao_process_original_data(i)


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



