import json
import traceback

from aidso_geo.models import spider_save_tos
from aidso_geo.models.eco_data_process import save_eco_data_to_bh
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 doubao_mobile_process_original_data(task_data):
    file_path = f'geo/{task_data["taskId"]}/{task_data["platform"]}/original.text'
    url_list = []
    think_content = ""
    response_content = ""
    search_keyword = []
    suggestions = set()
    rich_media_block = []
    seen_pos = set()
    is_think = False
    think_bool = False
    response_bool = False
    dy_poi_list =[]
    dy_eco_list =[]

    try:
        original_content = get_string_from_tos(file_path)
        content_list = original_content.split("\n")

        for i in content_list:
            if not i.startswith("data:"):
                continue

            payload = i[len("data:"):].lstrip()
            if not payload:
                continue

            try:
                json_content = json.loads(payload)
            except (IndexError, json.JSONDecodeError):
                continue

            if json_content.get('content'):
                if json_content.get('content').get('content_block'):
                    if json_content.get('content').get('content_block')[0].get('block_type') == 10040:
                        is_think = True
                        think_bool = True
                        continue
                if json_content.get("content").get("content_type") == 9999 and \
                        json_content.get("content").get("content_block")[0].get('block_type') == 10050:
                    for i in json_content.get("content").get("content_block")[0].get('content').get(
                            'rich_media_block').get('creations'):
                        rich_media_block.append(i.get('video') or i.get('ugc_item'))
                if json_content.get("content").get("content_type") == 9999 and \
                        json_content.get("content").get("content_block")[0].get('block_type') == 10000:
                    response_content += json_content.get("content").get("content_block")[0].get("content").get(
                        "text_block").get("text")
            if is_think:

                patch_op = json_content.get('patch_op')

                if patch_op:
                    if patch_op[0]:
                        patch_value = patch_op[0].get('patch_value')
                        if patch_value:
                            if patch_value.get('ext'):
                                if patch_value.get('ext').get('sp_v2'):
                                    for i in json.loads(patch_value.get('ext').get('sp_v2')):
                                        suggestions.add(i.get('content'))
                            content_block = patch_value.get('content_block')
                            if content_block:
                                if content_block[0].get('block_type') == 10000:
                                    text_block = content_block[0].get('content').get('text_block').get('text', '')

                                    if think_bool:
                                        think_content += text_block
                                    if response_bool:
                                        response_content += text_block

                                if content_block[0].get('block_type') == 10025:

                                    if think_bool:
                                        if content_block[0].get('content').get('search_query_result_block').get(
                                                'results') is not None:
                                            search_keyword.extend(
                                                content_block[0].get('content').get('search_query_result_block').get(
                                                    'queries'))
                                            think_content += "\n\n**"
                                            think_content += content_block[0].get('content').get(
                                                'search_query_result_block').get('summary', '')
                                            think_content += "**\n\n"
                                            for i in content_block[0].get('content').get(
                                                    'search_query_result_block').get(
                                                    'results'):
                                                url_list.append(i.get('text_card'))
                                            think_bool = False
                                            response_bool = True
                                            continue
                                if content_block[0].get('block_type') == 10040:
                                    think_bool = False
                                    response_bool = True
                                    continue
                                if content_block[0].get('block_type') == 10050:
                                    for i in content_block[0].get('content').get('rich_media_block').get('creations'):
                                        rich_media_block.append(i.get('video'))

                if think_bool:
                    if isinstance(json_content.get('text'), str):
                        think_content += json_content.get('text')

                if response_bool:
                    if isinstance(json_content.get('text'), str):
                        response_content += json_content.get('text')
            else:

                patch_op = json_content.get('patch_op')

                if response_content:
                    if isinstance(json_content.get('text'), str):
                        response_content += json_content.get('text')

                if patch_op:

                    target_item = next((item for item in patch_op if item.get('patch_object') == 102), None)

                    if target_item:

                        content_str = target_item.get('patch_value').get('content')
                        if content_str:

                            content_json = json.loads(content_str)

                            response_content += content_json.get('text')
                            if content_json.get('search_references'):
                                for i in content_json.get('search_references'):
                                    url_list.append(i.get('text_card'))

                    content_item = next((item for item in patch_op if item.get('patch_type') == 1), None)
                    if content_item:
                        patch_value = content_item.get('patch_value')

                        if patch_value:
                            content_block = patch_value.get('content_block')

                            if content_block:
                                if content_block[0].get('block_type') == 10101 and content_block[0].get('is_finish'):
                                    response_content = ""
                                if content_block[0].get('block_type') == 10000 and content_block[0].get('is_finish'):
                                    response_bool = True
                                if content_block[0].get('block_type') == 10000 and content_block[0].get('is_finish'):
                                    response_bool = False
                                if content_block[0].get('block_type') == 10000 and content_block[0].get('meta_info'):

                                    media_list = []
                                    poi_list = []
                                    meta_info = content_block[0].get('meta_info')

                                    for meta in meta_info:

                                        if meta.get('type') == 202:

                                            if meta.get('info'):

                                                if json.loads(meta.get('info')):
                                                    media = json.loads(meta.get('info')).get('media')

                                                    pos = json.loads(meta.get('info')).get('pos')

                                                    if pos in seen_pos:
                                                        continue
                                                    seen_pos.add(pos)

                                                    if media:

                                                        for m in media:
                                                            if m.get('type') == 4:

                                                                if m.get('applet'):

                                                                    if m.get('applet').get('render_data'):

                                                                        render_data = json.loads(m.get('applet').get('render_data'))
                                                                        if render_data.get('widget_data'):
                                                                            widget_data = json.loads(render_data.get('widget_data'))

                                                                            if widget_data:

                                                                                try:
                                                                                    widget_data_data = json.loads(
                                                                                        widget_data.get('data'))
                                                                                except Exception as e:
                                                                                    continue

                                                                                if widget_data_data:
                                                                                    pro_data = widget_data_data.get('data')

                                                                                    if pro_data:
                                                                                        for pr in pro_data:
                                                                                            if isinstance(pr,dict):

                                                                                                pid = pr.get('pid', '')
                                                                                                url = f'https://haohuo.jinritemai.com/ecommerce/trade/detail/index.html?id={pid}&origin_type=604'
                                                                                                product = {
                                                                                                    'text': pr.get('text', ''),
                                                                                                    'seller_name': pr.get(
                                                                                                        'seller_name', ''),
                                                                                                    'image_url': pr.get(
                                                                                                        'image_url', ''),
                                                                                                    'pid': pid,
                                                                                                    'jump_url': url,
                                                                                                }
                                                                                                media_list.append(product)
                                                                                                dy_eco_list.extend(media_list)
                                                                                    poi_data = widget_data_data.get(
                                                                                        'poi_list')

                                                                                    if poi_data:
                                                                                        for po in poi_data:
                                                                                            image_list = po.get(
                                                                                                "image_list") or []

                                                                                            poi = {
                                                                                                "poi_name": po.get(
                                                                                                    'poi_name'),
                                                                                                "image_list": image_list,
                                                                                                "poi_url": f"https://life-share.scsjsd.com/falcon/poi_mwa/poi_detail?poi_id={po.get('poi_id')}",
                                                                                                "price": po.get('price',
                                                                                                                ''),
                                                                                                "score": po.get('score',
                                                                                                                ''),
                                                                                                "rank": po.get('rank', '')
                                                                                            }
                                                                                            poi_list.append(poi)


                                    if media_list:
                                        response_content += 'render_ecom_card_widget_product_start:'
                                        media_str = json.dumps(media_list, ensure_ascii=False)
                                        response_content += media_str
                                        response_content += 'render_ecom_card_widget_product_end:'
                                    if poi_list:
                                        response_content += 'render_ecom_card_widget_poi_start:'
                                        poi_str = json.dumps(poi_list, ensure_ascii=False)
                                        response_content += poi_str
                                        response_content += 'render_ecom_card_widget_poi_end:'

                                if content_block[0].get('block_type') == 10000 and content_block[0].get(
                                        'patch_type') == 1:
                                    text_block = content_block[0].get('content').get('text_block').get('text', '')
                                    response_content += text_block

                                if content_block[0].get('block_type') == 10025:
                                    if content_block[0].get('content'):
                                        if content_block[0].get('content').get('search_query_result_block').get(
                                                'results') is not None:
                                            search_keyword.extend(
                                                content_block[0].get('content').get('search_query_result_block').get(
                                                    'queries'))
                                            for i in content_block[0].get('content').get('search_query_result_block').get(
                                                    'results'):
                                                if i.get('text_card'):
                                                    url_list.append(i.get('text_card'))
                                                if i.get('video_card'):
                                                    rich_media_block.append(i.get('video_card'))
                                if content_block[0].get('block_type') == 10050:
                                    creations = content_block[0].get('content',{}).get('rich_media_block',{}).get('creations')
                                    if creations:
                                        for cre in creations:
                                            rich_media_block.append(cre.get('video'))

                    suggest_item = next((item for item in patch_op if item.get('patch_object') == 50), None)
                    if suggest_item:
                        if suggest_item.get('patch_value'):
                            if suggest_item.get('patch_value').get('ext'):
                                if suggest_item.get('patch_value').get('ext').get('has_suggest') == '1':
                                    for i in json.loads(suggest_item.get('patch_value').get('ext').get('sp_v2')):
                                        suggestions.add(i.get('content'))

                else:
                    data_value = json_content.get('data')
                    if isinstance(data_value, list):
                        if data_value[0].get('cmd') == 'Append':
                            gen = data_value[0].get('display').get('display').get('generation_spans')
                            if gen:
                                if gen[0].get('type') == 2:
                                    response_content += gen[0].get('text').get('content')
        suggestions = list(suggestions)
        search_keyword = list(set(search_keyword))

        url_list_seen = set()
        new_url_list = []

        for item in url_list:
            key = json.dumps(item, ensure_ascii=False, sort_keys=True)

            if key in url_list_seen:
                continue

            url_list_seen.add(key)
            new_url_list.append(item)
        if dy_eco_list:
            save_eco_data_to_bh(task_data,'dyeco',dy_eco_list)
        url_list = new_url_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__':
    # 电商 21fd5xxx37f-131b-469axxxxx-9d5c-6ea00da2c0d6
    # poi 21fd5xxx37f-131b-4ss69axxxxx-9d5c-6ea00da2c0d6 0提及
    # 电商+poi 21fd5xxx37f-131b-4ss69axxxxx-9d5c-6ea00da2c0d6 0提及

    # aa = ['667b7528-5ff4-4ccb-bb98-7d0b5972014d']
    # https://tcdn.aidso.com/geo/6a5a03b63da04b9d809ea9fd27e266f6/DOUBA/rich_media_block.txt?secret=1104ee98dd68e955a5b45452010a5c54060b570e000d5849524855
    # file_path = 'geo/c7eb465e-f385-4aa2-89c4-a7cf11897f45/KIMI/1(1).txt'

    data_list = bh_utils.query_data(
        f"select * from geo_commit_task  where taskId = '369df725-ef53-4050-8b94-233a007950c3' and  platform  = 'DOUBA'")



    # # #
    # # # # #
    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 doubao_mobile_process_original_data(i)


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