import json

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 douyin_ai_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
    rich_media_block = []
    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("data:"):
                try:
                    # 提取并解析JSON数据
                    data_str = item.split("data:")[1]
                    json_data = json.loads(data_str)

                except (IndexError, json.JSONDecodeError):
                    continue

                if json_data.get('data'):

                    if json_data.get('data')[0]:
                        for cur in json_data.get('data'):
                            if not cur:
                                continue


                            display_obj = cur.get('display')

                            if display_obj and display_obj.get('display'):
                                display = display_obj.get('display')
                                if display.get('generation_spans'):

                                    if display.get('generation_spans')[0].get('type') ==2:
                                        response_content+=display.get('generation_spans')[0].get('text').get('content')
                                    if display.get('generation_spans')[0].get('type') ==11:
                                        think_content+=display.get('generation_spans')[0].get('cot').get('text')
                                        if display.get('generation_spans')[0].get('cot').get('search_queries'):
                                            think_content += '\n'+'\n'.join(display.get('generation_spans')[0].get('cot').get('search_queries'))+'\n\n'
                                    if display.get('generation_spans')[0].get('type') == 0:
                                        for i in json_data.get("data"):
                                            if i.get("container_info"):
                                                if i.get("container_info").get("business_data"):
                                                        if i.get("container_info").get("business_data")[0].get("type") == 999:
                                                            if json.loads(i.get("container_info").get("business_data")[0].get("data").get("raw_data")).get("display"):
                                                                if json.loads(i.get("container_info").get("business_data")[0].get("data").get("raw_data")).get("display").get("dis_video_info"):
                                                                    for video in json.loads(i.get("container_info").get("business_data")[0].get("data").get("raw_data")).get("display").get("dis_video_info"):
                                                                        rich_media_block.append(video)
                                if display.get('generation_refs'):

                                    if len(url_list) >0:
                                        continue
                                    for i in display.get('generation_refs'):
                                        if i.get('bottom_source_info'):
                                            url_list.append(i)

                            container_info = json_data.get('data')[0].get('container_info')

                            if container_info:
                                business_data = container_info.get('business_data')

                                if business_data:
                                    if business_data[0].get('data').get('bytesync_data') and response_content == "":
                                        if len(business_data[0].get('data').get('bytesync_data'))>0:
                                            if json.loads(business_data[0].get('data').get('bytesync_data')[0]).get('display').get('generation_spans'):
                                                for cn in json.loads(business_data[0].get('data').get('bytesync_data')[0]).get('display').get('generation_spans'):
                                                    if cn.get('type') ==2:
                                                        response_content+=cn.get('text').get('content')
                                    if business_data[0].get('data').get('raw_data'):
                                        video_list= json.loads(business_data[0].get('data').get('raw_data')).get('display').get('dis_video_info')
                                        if video_list:
                                            rich_media_block.extend(video_list)
                                        suggestions_list = json.loads(business_data[0].get('data').get('raw_data')).get('display').get('query_list')
                                        if suggestions_list:
                                            suggestions = [item['content'] for item in suggestions_list]
        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)
    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__':
    data_list = bh_utils.query_data(
        f"select * from geo_commit_task where taskId = '1cfb92e0-b0ae-40e5-b198-342d079dea0a' and platform = 'DYAI'")


    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 douyin_ai_process_original_data(i)


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

