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') == 'source_group_web':
                                                mu_content = mu.get('content')
                                                mu_source_seq = mu.get('source_seq')
                                                if mu_content.get('list'):
                                                    mu_content_list = mu_content.get('list')
                                                    for mu_list in mu_content_list:
                                                        if mu_list.get('type') == 'source':
                                                            mu_list_list = (mu_list.get('content').get('list'))
                                                            for mu_list_l in mu_list_list:
                                                                ...
                                                                # 处理引用文章
                                                                # print(mu_list_l)
                                                                # print(mu_source_seq)
                                                                # print(mu_source_seq)
                                                                # print('----')
                                                                # print('----')

                                            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')
                                        # print(ms)
                                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 ms.get('mime_type') == 'bar/workflow' and ms.get('status') == 'complete':
                                    ms_meta_data_multi_load = ms.get('meta_data').get('multi_load')
                                    if isinstance(ms_meta_data_multi_load,list):
                                        for i in ms_meta_data_multi_load:
                                            ms_meta_data_multi_load_type  =i.get('type')
                                            if ms_meta_data_multi_load_type == 'bar_thinking':
                                                think_content+=i.get('content').get('body')
                                            if ms_meta_data_multi_load_type == 'bar_ref_source_inline':
                                                if i.get('content'):
                                                    if i.get('content').get('query_list'):
                                                        search_keyword.extend(i.get('content').get('query_list'))
                                                    if i.get('content').get('docs'):
                                                        url_list_batch.extend(i.get('content').get('docs'))

        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 = '9fd93209-01db-4dd2-84e3-02eeccbedb16' 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")
