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.tos_utils import get_string_from_tos
from aidso_geo.models import spider_save_tos


def qianwen_process_original_data(data):
    file_path = f'geo/{data["taskId"]}/{data["platform"]}/original.text'
    url_list = []
    url_list_batch = []
    think_content = ""
    response_content = ""
    search_keyword = []
    suggestions = []
    rich_media_block =[]
    is_think = False
    think_bool = False
    response_bool = False
    result = []
    try:
        original_content = get_string_from_tos(file_path)

        content_list = original_content.split("\n")

        for i in content_list:

            if i.startswith("data:"):
                try:
                    # 提取并解析JSON数据
                    data_str = i.split("data:")[1]

                    json_data = json.loads(data_str)

                except (IndexError, json.JSONDecodeError):

                    continue
                #
                if isinstance(json_data, dict):
                    if json_data.get('msgStatus'):
                        if json_data.get("incremental") == False:
                            if json_data.get('msgStatus') == 'finished':

                                if json_data.get('contents'):
                                    for cn in json_data.get('contents'):
                                        if cn.get('contentType') == 'plugin':
                                            pluginResult = json.loads(cn.get('content')).get('pluginResult')

                                            if pluginResult:
                                                try:
                                                    if isinstance(json.loads(pluginResult), list):
                                                        if len(json.loads(pluginResult))>=2:
                                                            url_list = json.loads(pluginResult)[1].get(
                                                                'search_results')
                                                    if isinstance(json.loads(pluginResult), dict):
                                                        url_list = json.loads(pluginResult).get(
                                                            'links')
                                                except Exception as e:
                                                    ...
                                        if cn.get('contentType') == 'think':
                                            think_content = json.loads(cn.get('content')).get('content')
                                        if cn.get('contentType') == 'text':
                                            response_content = cn.get('content')
                    if json_data.get("data"):
                        if json_data.get("data").get('status'):

                            if json_data.get("data").get('status') == 'complete':

                                messages = json_data.get('data').get('messages')

                                for cn in messages:
                                    if cn.get('mime_type') == 'bar/iframe' and cn.get('status') == 'complete':
                                        url_list_batch  =cn.get('meta_data').get('sources')[0].get('content').get('list')
                                    if cn.get('mime_type') == 'multi_load/iframe' and cn.get('status') == 'complete':
                                        response_content = cn.get('content')
                                        response_content = response_content.replace("[(deep_think)]", "")
                                        response_content = response_content.replace("[(multimodal_chat_think_1)]", "")
                                        multi_load = cn.get('meta_data').get('multi_load')
                                        if multi_load:
                                            for mu in multi_load:
                                                if mu.get('type') == 'deep_think' or mu.get('type') == 'multimodal_chat_think':
                                                    if mu.get('content').get('status') =='complete':
                                                        think_content = mu.get('content').get('think_content')

                        if json_data.get("data").get('messages'):
                            messages = json_data.get("data").get('messages')
                            for ms in messages:

                                if ms.get('mime_type') =='multi_load/iframe' and ms.get('status') == 'complete':

                                    response_content = ms.get('content')

                                    response_content = response_content.replace("[(deep_think)]", "")
                                    response_content = response_content.replace("[(multimodal_chat_think_1)]", "")
                                    multi_load = ms.get('meta_data').get('multi_load')
                                    if multi_load:
                                        for mu in multi_load:
                                            if mu.get('type') == 'deep_think' or mu.get('type') == 'multimodal_chat_think':
                                                if mu.get('content').get('status') == 'complete':
                                                    think_content = mu.get('content').get('think_content')
                                            if mu.get('type') == 'ref_source_inline':

                                                mu_content = mu.get('content')
                                                if mu_content:
                                                    if mu_content.get('query_list'):
                                                        search_keyword.extend(mu_content.get('query_list'))
                                                    if mu_content.get('list'):
                                                        url_list_batch.extend(mu_content.get('list'))
                                            if mu.get('type') == 'video_note_list':
                                                rich_media_block.append(
                                                    {
                                                        "url": mu.get('content').get('list'),
                                                        "source_seq": mu.get('source_seq')
                                                    }
                                                )

                                if ms.get('mime_type') =='bar/iframe' and ms.get('status') == 'complete':
                                    if  ms.get('meta_data').get('sources'):
                                        url_list_batch = ms.get('meta_data').get('sources')[0].get('content').get('list')
                                if ms.get('mime_type') =='paa/iframe' and ms.get('status') == 'complete':
                                    paas = ms.get('meta_data').get('paas')
                                    if paas:
                                        for pa in ms.get('meta_data').get('paas'):
                                            suggestions.append(pa.get('show_text'))

        if url_list_batch:
            for url in url_list_batch:
                url_list.append(
                    {
                        "url": url.get('url', ''),
                        "title": url.get('title', ''),
                        "snippet": url.get('summary', ''),
                        "host_name": url.get('name', ''),
                        "host_logo": url.get('icon', ''),
                        "time": url.get('publish_time', ''),
                    }
                )

        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)
    return (file_path, search_keyword, url_list, think_content, response_content, suggestions)
#

if __name__ == '__main__':

    # file_path2 = 'geo/21fd5xxx37f-131b-469axxxxx-9d5c-6ea00da2c0d6/TYQW/original.text'
    # # file_path2 = 'geo/jqk/TYQW/2.txt'
    # # /geo/900f0ea6e9a34c95b6b57aa7519a4820/
    # # file_path3 = 'geo/51a7ee04-711c-4cf0-9d4c-4b523fba7037/TYQW/original.text'
    # qianwen_process_original_data(file_path2)
    # for i in task_id:
    data_list = bh_utils.query_data(f"select * from geo_commit_task  where taskId = '3e317dd8-2512-476c-a31a-104c0bcaca75' and  platform  = 'TYQW'")

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


    if data_list:
        for i in data_list:
            try:
                handle_item(i)
            except Exception as e:
                ...
    # plan_cot/post  and status =='complete' 思考过程前
    # bar/progress and type = cot 搜索关键词
    # bar/progress and type = sources 引用来源
    # multi_load/iframe 相关视频

    #     qianwen_process_original_data(f"geo/{i}/TYQW/original.text")
