import json
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


def deepseek_android_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 is_think:

                    if json_data.get('p') == 'response/fragments' and json_data.get('v')[0].get('type') == 'SEARCH':
                        for i  in  json_data.get('v')[0].get('queries'):
                            search_keyword.append(i.get('query'))
                    if json_data.get('p') == 'response' and  json_data.get('v')[0].get('p') =='fragments' :
                        if isinstance(json_data.get('v')[0].get('v'),list):
                            for q in json_data.get('v')[0].get('v'):
                                if q.get('type') =='TOOL_SEARCH':
                                    if isinstance(q.get('queries'),list):
                                        for que in q.get('queries'):
                                            search_keyword.append(que.get('query'))
                            # if json_data.get('v')[0].get('v')[0].get('queries'):
                            #     for q in json_data.get('v')[0].get('v')[0].get('queries'):
                            #         search_keyword.append(q.get('query'))
                    if json_data.get('p') == 'response/search_results' or json_data.get('p') == 'response/fragments/-1/results':
                        url_list = json_data.get('v')
                    if json_data.get('p') == 'response' :
                        if json_data.get('v')[0].get('v') == 'FINISHED':
                            continue
                        if isinstance(json_data.get('v')[0].get('v'),list):

                            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('p') == 'response/fragments' and json_data.get('v')[0].get('type') == 'THINK':
                        think_content += json_data.get('v')[0].get('content')
                        think_bool = True
                        continue
                    if json_data.get('p') == 'response/fragments/-1/elapsed_secs':
                        think_bool = False
                        continue
                    if think_bool:
                        if isinstance(json_data.get('v'), str):
                            think_content+=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/fragments' and json_data.get('v')[0].get('type') == 'TIP':
                        response_bool = False
                        continue


                    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':
                        response_bool = False
                        continue
                    if response_bool:
                        if isinstance(json_data.get('v'), str):
                            response_content += json_data.get('v')
                else:
                    if json_data.get('p') == 'response/fragments/-1/content':
                        if isinstance(json_data.get('v'), str):
                            response_content+=json_data.get('v')
                            response_bool=True
                            continue
                    if 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') =='SEARCH':
                        for i in json_data.get('v')[0].get('queries'):
                            search_keyword.append(i.get('query'))
                    if json_data.get('p') =='response':
                        for i in json_data.get('v'):
                            if i.get('p') == 'fragments':
                                if i.get('v'):
                                    for k in i.get('v'):
                                        if k.get('queries'):
                                            for q in k.get('queries'):
                                                search_keyword.append(q.get('query'))

                    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/fragments':
                        if json_data.get('v')[0].get('v'):
                            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('p') == 'response' :
                        if json_data.get('v')[0].get('v') == 'FINISHED':
                            response_bool = False
                            continue
                        if isinstance(json_data.get('v')[0].get('v'),list):
                            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('p') == 'response/fragments' and json_data.get('v')[0].get('type') == 'TIP':
                        response_bool = False
                        continue
                    if json_data.get('p') == 'response/status' and json_data.get('v')== 'FINISHED':
                        response_bool = False
                        continue
                    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_android_process_original_data(i)


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