import json
import traceback
import re
from aidso_geo.models import spider_save_tos
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, put_string_to_tos


def thinking_enabled_fragments(json_data):
    search_word = []
    for i in json_data:
        data = i.get('queries')
        search_word = [item['query'] for item in data]
    return search_word


def deepseek_process_original_data(data):
    file_path = f'geo/{data["taskId"]}/{data["platform"]}/original.text'
    """处理文件内容，提取思考内容、响应内容和URL列表"""
    url_list = ""
    think_content = ""
    response_content = ""
    search_keyword = []
    is_think = False
    think_bool = False
    suggestions = []
    response_bool = False
    url_id_map = {}
    # 按空行分割内容，过滤空字符串
    try:
        original_content = get_string_from_tos(file_path)
        content_list = [item for item in original_content.split("\n\n") if item]


        for item in content_list:
            if item.startswith("event: "):
                # 可根据需要补充event数据处理逻辑
                continue

            # 处理data类型数据
            if item.startswith("data: "):
                try:
                    # 提取并解析JSON数据
                    data_str = item.split("data: ")[1]
                    json_data = json.loads(data_str)

                except (IndexError, json.JSONDecodeError):
                    continue  # 跳过格式错误的数据

                if isinstance(json_data.get('v'),dict):
                    if  json_data.get('v').get('response').get('thinking_enabled') == True:

                        is_think=True
                    fragments = json_data.get('v').get('response').get('fragments')
                    if fragments:
                        if isinstance(fragments, list):
                            if fragments[0].get('type') == 'RESPONSE':
                                response_content += fragments[0].get('content')
                            if fragments[0].get('type') == 'THINK':
                                think_content += fragments[0].get('content')
                                think_bool = True
                            if fragments[0].get('type') == 'SEARCH':
                                if isinstance(fragments[0].get('queries'), list):
                                    for sea in fragments[0].get('queries'):
                                        search_keyword.append(sea.get('query'))
                    # if json_data.get('v').get('response').get('search_enabled') == True:
                    #     if len(json_data.get('v').get('response').get('fragments'))>0:
                    #         query_list = json_data.get('v').get('response').get('fragments')[0].get('queries')
                    #         if query_list:
                    #             result = [item.get('query', '') for item in query_list]
                    #             search_keyword.extend(result)

                if is_think:

                    if json_data.get('p') == 'response/fragments' and json_data.get('v')[0].get('type') == 'SEARCH':
                        search_keyword.append(json_data.get('v')[0].get('queries')[0].get('query'))

                    if json_data.get('p') == 'response/fragments/0/results' or json_data.get(
                            'p') == 'response/fragments/-1/results':
                        url_list = json_data.get('v')

                    if json_data.get('p') =='response/fragments' and json_data.get('v')[0].get('type') == 'THINK':
                        think_bool = True
                        think_content+=json_data.get('v')[0].get('content')
                        continue
                    if json_data.get('p') == 'response' :
                        if isinstance(json_data.get('v')[0].get('v'),list):
                            if json_data.get('v')[0].get('v')[0].get('type') == 'TOOL_SEARCH':
                                for q in json_data.get('v')[0].get('v')[0].get('queries'):
                                    search_keyword.append(q.get('query'))

                        if json_data.get('v')[1].get('p') == 'fragments' or json_data.get('v')[1].get('p') == 'response/fragments':
                            if  json_data.get('v')[1].get('v')[0].get('type') == 'THINK':
                                think_content+=json_data.get('v')[1].get('v')[0].get('content')
                                think_bool = True
                                continue
                        if json_data.get('v')[0].get('p') == 'fragments' or json_data.get('v')[0].get('p') == 'response/fragments':
                            if  json_data.get('v')[0].get('v')[0].get('type') == 'THINK':
                                think_content+=json_data.get('v')[0].get('v')[0].get('content')
                                think_bool = True
                                continue
                        if json_data.get('v')[0].get('v') == 'FINISHED':
                            response_bool = False
                    if json_data.get('p') == 'response/fragments' and json_data.get('v')[0].get('type') == 'RESPONSE':
                        think_bool = False
                        response_bool = True
                        response_content += json_data.get('v')[0].get('content')
                        continue
                    if json_data.get('p') == 'response/fragments/1/elapsed_secs':
                        think_bool = False
                    if isinstance(json_data.get('v'),list):
                        v_json_data = json_data.get('v')
                        has_tool_search = False
                        tool_search_id = None

                        for item in v_json_data:
                            if item.get('p') == 'references':
                                references = item.get('v') or []

                                if isinstance(references, list):
                                    for reference in references:
                                        if (
                                                isinstance(reference, dict)
                                                and reference.get('type') == 'TOOL_OPEN'
                                        ):
                                            has_tool_search = True
                                            tool_search_id = reference.get('id')
                                            break
                        for v in v_json_data:
                            if v.get('p') == 'content' and has_tool_search:
                                p_content = v.get('v') or ''

                                p_content = re.sub(
                                    r'\[reference:\d+\]',
                                    f'[reference:{tool_search_id}]',
                                    p_content
                                )
                                response_content+=p_content

                            if v.get('p') == 'fragments':
                                if v.get('p') == 'fragments':
                                    fragments = v.get('v') or []

                                    if isinstance(fragments, list):
                                        for fragment in fragments:
                                            if (
                                                    isinstance(fragment, dict)
                                                    and fragment.get('type') == 'TOOL_OPEN'
                                                    and fragment.get('result') is not None
                                            ):
                                                url_id_map[fragment.get('result').get('url')] = fragment.get('id')

                    if json_data.get('p') == 'response/fragments/-1/elapsed_secs':
                        think_bool = False
                    if json_data.get('p') == 'response/fragments':
                        response_bool = False
                    if response_bool:
                        if isinstance(json_data.get('v'), str):
                            response_content += json_data.get('v')
                    if think_bool:
                        if isinstance(json_data.get('v'), str):
                            think_content+=json_data.get('v')
                else:
                    if json_data.get('p') == 'response/fragments/-1/content':
                        response_bool = True
                    if json_data.get('p') == 'response/fragments' and json_data.get('v')[0].get('type') == 'SEARCH':
                        search_keyword.append(json_data.get('v')[0].get('queries')[0].get('query'))
                    if json_data.get('p') == 'response/fragments/0/results' or json_data.get('p') == 'response/fragments/-1/results':
                        url_list = json_data.get('v')
                    if json_data.get('p') == 'response/fragments' and json_data.get('v')[0].get('type') == 'RESPONSE':
                        response_content+=json_data.get('v')[0].get('content')
                        response_bool = True
                        continue
                    if json_data.get('p') == 'response':
                        if json_data.get('v')[1].get('p') == 'fragments':
                            if  json_data.get('v')[1].get('v')[0].get('type') == 'RESPONSE':
                                response_content+=json_data.get('v')[1].get('v')[0].get('content')
                                response_bool = True
                                continue
                        if json_data.get('v')[0].get('p') == 'fragments':
                            if  json_data.get('v')[0].get('v')[0].get('type') == 'RESPONSE':
                                response_content+=json_data.get('v')[0].get('v')[0].get('content')
                                response_bool = True
                                continue
                        if json_data.get('v')[0].get('v') == 'FINISHED':
                            response_bool = False
                    if  json_data.get('p') == 'response/fragments' and json_data.get('v')[0].get('type') == 'TIP':
                        response_bool= False
                        continue
                    if json_data.get('v') == 'FINISHED':
                        response_bool = False
                    if response_bool:
                        if isinstance(json_data.get('v'),str):
                            response_content+=json_data.get('v')
        used_ids = set(url_id_map.values())
        next_id = 1

        for item in url_list:
            url = item.get('url')

            if url in url_id_map:
                item['cite_index'] = url_id_map[url]

            elif item.get('cite_index') is None:
                while next_id in used_ids:
                    next_id += 1

                item['cite_index'] = next_id
                used_ids.add(next_id)
                next_id += 1
        think_content = think_content.replace('DEEP_SEARCH','')
        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__':
    data_list = bh_utils.query_data(f"select * from geo_commit_task  where taskId = 'b188155e-7c55-44ed-955b-d369431fe22f' and  platform  = 'DP'")

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


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