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 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 baiduai_process_original_data(data):
    file_path = f'geo/{data["taskId"]}/{data["platform"]}/original.text'
    """处理文件内容，提取思考内容、响应内容和URL列表"""
    url_list = []
    rich_media_block = []
    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") if item]
        for item in content_list:
            if item.startswith("event:"):
                continue

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

                except (IndexError, json.JSONDecodeError):
                    continue  # 跳过格式错误的数据
                data = json_data.get("data")
                if data :
                    stage_data = data.get('message').get('metaData').get('speedInfo').get('stage')
                    if stage_data == 'SPEED_THINKING_STAGE':

                        if data.get('message').get('content').get('generator').get('data'):
                            if isinstance(data.get('message').get('content').get('generator').get('data').get('reasoningContent'),str):
                                think_content += data.get('message').get('content').get('generator').get('data').get('reasoningContent')
                    if stage_data == 'SPEED_CONTENT_STAGE':
                        if data.get('message').get('content').get('generator').get('data'):

                            value = data.get('message').get('content').get('generator').get('data').get('value')
                            items = data.get('message').get('content').get('generator').get('data').get('items')
                            if value:
                                if isinstance(value, str):
                                    response_content+=value
                            if items:
                                if isinstance(items, list):
                                    for ite in items:
                                        rich_media_block.append(ite)
                            if  data.get('message').get('content').get('generator').get('data').get("items") and response_content == "":
                                response_content += "生成了图片"
                    if stage_data == 'SPEED_THINKING_STAGE':
                        if data.get('message').get('content').get('generator').get('data'):
                            if data.get('message').get('content').get('generator').get('data').get('referenceList'):
                                url_list+=data.get('message').get('content').get('generator').get('data').get('referenceList')
                    if stage_data == 'SPEED_GUIDE_STAGE':
                        if data.get('message').get('content').get('generator').get('data'):
                            if  data.get('message').get('content').get('generator').get('data').get('recommendWord'):
                                for i in  data.get('message').get('content').get('generator').get('data').get('recommendWord'):
                                    if i.get('modelType') == 0:
                                        suggestions.append(i.get('text'))
                    if  data.get('message').get('content'):
                        if data.get('message').get('content').get('generator'):
                            if data.get('message').get('content').get('generator').get('antiFlag') and data.get('message').get('content').get('generator').get('isFinished') == True:
                                response_content+='我们换个话题聊聊吧'

        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, rich_media_block)
    return (file_path, search_keyword, url_list, think_content, response_content, suggestions)




if __name__ == '__main__':
    file_path = "geo/21430906-2656-4ba4-b884-5f937745734c/BDAI/original.text"
    baiduai_process_original_data(file_path)
    # 男子驾车撞4辆电动车致3伤
