import json
import traceback

from aidso_geo.models import spider_save_tos
from aidso_geo.utils import robot_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

    # 按空行分割内容，过滤空字符串
    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
                    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 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')
        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__':
    file_path = "geo/a374ca2e-eb45-4c2d-badd-9219af98ff38/DP/original.text"
    deepseek_process_original_data(file_path)
