import json

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


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


    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 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')
        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_path1 = 'geo/b1480658-f379-4ca7-8897-51ffef64b2d0/DPA/original.text'
    file_path2 = 'geo/799bfc72-60dc-4333-b551-3e1d284c7570/DPA/original.text'
    # file_path1 = "geo/0f59c196-aff1-46a5-aa50-5c792ebf481e/DPA/original.text"
    # file_path = "geo/0c0abba3-9122244-wwwsss4e2dddd1ssssaaass-96aaaa2wwww1-10086/DPA/original.text"
    # file_path2 = "geo/0a715fc6-ecc8-4e48-baf1-abc0c9477c1e/DPA/original.text"
    deepseek_android_process_original_data(file_path2)
