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 qianwen_android_process_original_data(task_data):

    file_path = f'geo/{task_data["taskId"]}/{task_data["platform"]}/original.text'
    url_list = []
    url_list_batch = []
    think_content = ""
    response_content = ""
    search_keyword = []
    rich_media_block = []
    suggestions = []
    is_think = False
    think_bool = False
    response_bool = False
    result = []
    damai_data_list = []
    try:
        json_original = ""
        original_content = get_string_from_tos(file_path)
        try:
            sse_json_data = json.loads(original_content)

            # sse_json_data = json.loads(json_original.get('sse'))
            response_content = sse_json_data.get('reply_text','')
            think_content = sse_json_data.get('deepthink_text','')
            paa_answer = sse_json_data.get('paa_answer','')
            bar_sources = sse_json_data.get('bar_sources')
            source_content = {}
            if bar_sources:
                source_content =next(
                    (item.get('content') for item in bar_sources if item.get('type') == 'source'),
                    {}
                )
            source_list = source_content.get('list', [])

            video_note_data = sse_json_data.get('video_note_list') or {}

            if isinstance(video_note_data, str):
                try:
                    video_note_data = json.loads(video_note_data)
                except json.JSONDecodeError:
                    video_note_data = {}
            video_note_list = video_note_data.get('list', [])
            video_list = []
            if video_note_list:
                for i in video_note_list:
                    rich_media = {
                        'zhidaye_id':i.get('zhidaye_id'),
                        'title':i.get('title'),
                        'cover':i.get('cover'),
                        'url':i.get('url'),
                        'author':i.get('author'),
                        'publishTime':i.get('publishTime'),
                        'duration':i.get('duration'),
                    }
                    video_list.append(rich_media)

                rich_media_block.append({
                    "url":video_list,
                    "source_seq":''
                })
            source_count_list = []
            if source_list:
                for s in source_list:
                    source_url = {
                        'url':s.get('url'),
                        'title':s.get('title'),
                        'summary':s.get('summary'),
                        'publish_time':s.get('publish_time'),
                        'name':s.get('name'),
                        'icon':s.get('icon'),
                        'source_seq':s.get('source_seq',''),
                    }
                    source_count_list.append(source_url)
                url_list.append({
                    "url":[
                        {
                            "type":"source",
                            "content":{
                                "list":source_count_list
                            },
                        }
                    ],
                    "source_seq":''
                })

            if paa_answer:
                paa_json = json.loads(paa_answer)
                for paa in paa_json:
                    suggestions.append(paa.get('paa_query'))
        except Exception as e:
            content_list = original_content.split("\n")

            for i in content_list:

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

                        json_data = json.loads(data_str)

                    except (IndexError, json.JSONDecodeError):

                        continue
                    data = json_data.get('data')

                    if data:
                        messages = data.get('messages')
                        if isinstance(messages, list):
                            if len(messages) > 0:
                                mime_type = messages[0].get('mime_type')
                                status = messages[0].get('status')
                                type = messages[0].get('type')
                                content = messages[0].get('content')
                                meta_data = messages[0].get('meta_data')
                                meta_data_type = ""
                                multi_load = ""
                                multi_load_type = ""
                                multi_load_content = ""
                                multi_load_status = ""
                                if meta_data:
                                    meta_data_type = messages[0].get('meta_data').get('type')
                                    multi_load = messages[0].get('meta_data').get('multi_load')
                                    if multi_load:
                                        if isinstance(multi_load, list):
                                            multi_load_type = multi_load[0].get('type')
                                            multi_load_content = multi_load[0].get('content')
                                            if multi_load_content:
                                                multi_load_status = multi_load[0].get('content').get('status')
                                # 搜索前
                                if mime_type == 'plan_cot/post' and status == 'complete':
                                    think_content += content
                                # 搜索词
                                if mime_type == 'bar/progress' and meta_data_type == 'cot':
                                    if messages[0].get('meta_data').get('content'):
                                        search_list = messages[0].get('meta_data').get('content').get('list')
                                        if isinstance(search_list, list):
                                            for search in search_list:
                                                search_keyword.append(search.get('query'))
                                if mime_type == 'bar/progress' and meta_data_type == 'bar_update':
                                    if messages[0].get('meta_data'):
                                        if messages[0].get('meta_data').get('elements'):
                                            response_content+=messages[0].get('meta_data').get('elements')[0].get('content')
                                # 引用来源-无下标
                                if mime_type == 'multi_load/iframe' :
                                    for i in multi_load:
                                        if i.get('type') =='ref_source_inline' and i.get('content').get('status') =='complete':
                                            multi_load_content = i.get('content')
                                            multi_load_source_seq = i.get('source_seq')
                                            multi_load_content_query_list = multi_load_content.get('query_list')
                                            multi_load_content_url_list = multi_load_content.get('list')
                                            if multi_load_content_query_list:
                                                search_keyword.extend(multi_load_content_query_list)
                                            if multi_load_content_url_list:
                                                url_reslt = {"content": {"list": multi_load_content_url_list}}
                                                url_list_batch.append({
                                                    "url": [url_reslt],
                                                    "source_seq": multi_load_source_seq
                                                })

                                if mime_type == 'bar/iframe' and status == 'complete':

                                    if meta_data:
                                        sources = meta_data.get('sources')
                                        for sou in sources:
                                            url_list.append({
                                                "url": [sou],
                                                "source_seq": '',
                                            })
                                taobao_list = []
                                if mime_type == 'multi_load/iframe' and (multi_load_type == 'taoassistant_fold_product_feeds' or multi_load_type == 'taoassistant_single_product' or multi_load_type == 'taoassistant_single_product_v2') and status == 'complete':

                                    for mu in multi_load:

                                        if mu.get('type') == 'taoassistant_fold_product_feeds' :

                                            source_seq = mu.get('source_seq')
                                            jump_url = next(
                                                (
                                                    item.get('params', {}).get('popupLink', '')
                                                    for item in
                                                mu.get('content', {}).get('cardData', {}).get('clientActions', [])
                                                    if item.get('type') == 'popupLink'
                                                ),
                                                ''
                                            )

                                            query = next(
                                                (
                                                    item.get('params', {}).get('params',  {}).get('queryList',[])
                                                    for item in
                                                mu.get('content', {}).get('cardData', {}).get('clientActions', [])
                                                    if item.get('type') == 'loadmore'
                                                ),
                                                ''
                                            )
                                            if isinstance(query,str):
                                                if query:
                                                    query = json.loads(query)
                                            if isinstance(query,list):
                                                search_keyword.extend(query)
                                            if isinstance(mu.get('content').get('cardData').get('data').get('items'), list) and not taobao_list  :

                                                cateTitle = mu.get('content').get('cardData').get('data').get('cateTitle')
                                                for pro in mu.get('content').get('cardData').get('data').get('items'):
                                                    price = (pro.get('priceShowWithIcon') or {}).get('price') or pro.get('itemPrice') or ''
                                                    taobao_list.append({
                                                        "title": cateTitle or pro.get('title', ''),
                                                        "shop_name": next(
                                                            (
                                                                item.get('text', '')
                                                                for item in
                                                                pro.get('structuredShopInfo', {}).get('infoList', [])
                                                                if item.get('sourceType') == 'shop_name'
                                                            ),
                                                            ''
                                                        ),
                                                        "pic_path": pro.get('pic_path', ''),
                                                        "price": price,
                                                        "jump_url": jump_url,
                                                        "source_seq": source_seq,
                                                        "auctionURL": pro.get('auctionURL'),
                                                        "item_id": pro.get('item_id'),
                                                        'card_type':'fold_product'
                                                    })

                                        if mu.get('type') in ('taoassistant_single_product','taoassistant_single_product_v2'):
                                            mu_content = mu.get('content',{})
                                            mu_content_cardData = mu_content.get('cardData',{})
                                            mu_content_cardData_data = mu_content_cardData.get('data',{})

                                            if mu_content_cardData_data:
                                                source_seq = mu_content.get('cardId') or mu_content.get('businessId')
                                                price = (mu_content_cardData_data.get('priceShowWithIcon') or {}).get('price') or mu_content_cardData_data.get(
                                                    'itemPrice') or ''
                                                taobao_list.append({
                                                    "title": mu_content_cardData_data.get('title'),
                                                    "shop_name": next(
                                                        (
                                                            item.get('text', '')
                                                            for item in
                                                            mu_content_cardData_data.get('structuredShopInfo', {}).get('infoList', [])
                                                            if item.get('sourceType') == 'shop_name'
                                                        ),
                                                        ''
                                                    ),
                                                    "pic_path": mu_content_cardData_data.get('pic_path', ''),
                                                    "price": price,
                                                    "jump_url": mu_content_cardData_data.get('auctionURL'),
                                                    "source_seq": source_seq,
                                                    "auctionURL": mu_content_cardData_data.get('auctionURL'),
                                                    "item_id": mu_content_cardData_data.get('item_id'),
                                                    'card_type': 'single_product'
                                                })


                                if taobao_list:
                                    response_content += 'render_ecom_card_widget_taobao_start:'
                                    damai_str = json.dumps(taobao_list, ensure_ascii=False)
                                    response_content += damai_str
                                    response_content += 'render_ecom_card_widget_taobao_end:\n'
                                    save_eco_data_to_bh(task_data,'taobao',taobao_list)
                                damai_list = []
                                if mime_type == 'multi_load/iframe' and multi_load_type == 'damai_shows_list' and multi_load_status == 'complete':

                                    for mu in multi_load:
                                        if mu.get('type') == 'damai_shows_list':
                                            source_seq = mu.get('source_seq')
                                            if isinstance(mu.get('content').get('list'), list):
                                                for damai in mu.get('content').get('list'):
                                                    venueName = damai.get('data').get('venueName', '')
                                                    cityName = damai.get('data').get('cityName', '')
                                                    damai_list.append({
                                                        'name': damai.get('data').get('name', ''),
                                                        'venueName': venueName,
                                                        'showTime': damai.get('data').get('showTime', ''),
                                                        "cityName": cityName,
                                                        'verticalPic': damai.get('data').get('verticalPic', ''),
                                                        'priceShowText': damai.get('data').get('priceShowText', ''),
                                                        'webURL': damai.get('jumpConfig').get('detailUrl').get('webURL',
                                                                                                               '') or '',
                                                        'priceLow': damai.get('data').get('priceLow', ''),
                                                        'minPrice': damai.get('data').get('minPrice', ''),
                                                        'maxPrice': damai.get('data').get('maxPrice', ''),
                                                        'priceStr': damai.get('data').get('priceStr', ''),
                                                        'showVenueName': cityName + venueName,
                                                        'source_seq_id': source_seq,
                                                        'id': damai.get('data').get('id')
                                                    })
                                                    damai_data_list.extend(damai_list)
                                gaode_list = []
                                if mime_type == 'multi_load/iframe' and multi_load_type == 'new_amap_poi_list' and multi_load_status == 'complete':
                                    for mu in multi_load:
                                        mu_content = mu.get('content')
                                        mu_source_seq = mu.get('source_seq')

                                        mu_content_model_input  = mu_content.get('modelInput')
                                        mu_content_pois  = mu_content.get('pois')

                                        for poi in mu_content_pois:
                                            poi_summary = poi.get('summary1')
                                            distance_formatted = poi.get('distance_formatted')
                                            photos = poi.get('photos')
                                            distance_address = poi.get('address')

                                            gaode_result = {
                                                "source_seq":mu_source_seq,
                                                "name":mu_content_model_input.get("name"),
                                                "poi_id":mu_content_model_input.get("poi_id"),
                                                "poi_summary":poi_summary,
                                                "distance_formatted":distance_formatted,
                                                "photos":photos[0].get("url", "") if isinstance(photos, list) and photos and isinstance(photos[0], dict) else "",
                                                "address":distance_address,
                                            }
                                            gaode_list.append(gaode_result)

                                if damai_list:
                                    response_content += 'render_ecom_card_widget_damai_start:'
                                    damai_str = json.dumps(damai_list, ensure_ascii=False)
                                    response_content += damai_str
                                    response_content += 'render_ecom_card_widget_damai_end:\n'
                                if gaode_list:
                                    response_content += 'render_ecom_card_widget_gaode_start:'
                                    gaode_str = json.dumps(gaode_list, ensure_ascii=False)
                                    response_content += gaode_str
                                    response_content += 'render_ecom_card_widget_gaode_end:\n'
                                if mime_type == 'multi_load/iframe' and multi_load_type == 'deep_think' and multi_load_status == 'complete':
                                    think_content += multi_load_content.get('think_content')
                                # 引用来源 回答 视频列表
                                if mime_type == 'multi_load/iframe' and status == 'complete':
                                    response_content += content
                                    for mu in multi_load:
                                        if mu.get('type') == 'video_note_list':
                                            rich_media_block.append(
                                                {
                                                    "url": mu.get('content').get('list'),
                                                    "source_seq": mu.get('source_seq')
                                                }
                                            )

                                        if mu.get('type') == 'source_group_web':
                                            url_list_batch.append(
                                                {
                                                    "url": mu.get('content').get('list'),
                                                    "source_seq": mu.get('source_seq')
                                                }
                                            )

                                if mime_type == 'paa/iframe' and status == 'complete':
                                    paas = meta_data.get('paas')
                                    if isinstance(paas, list):
                                        for pa in paas:
                                            suggestions.append(pa.get('show_text'))
            if url_list_batch:
                url_list = url_list_batch
            if damai_data_list:
                save_eco_data_to_bh(task_data, 'damai', damai_data_list)


        response_content = response_content.replace("[(deep_think)]", "")
        response_content = response_content.replace("[(multimodal_chat_think_1)]", "")

        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__':

    #https://tcdn.aidso.com/geo/6fede9d0-ce6c-4c97-bcb8-43c499fc24e5/TYQWA/think.txt?secret=1104ed37df6abefbb2b454530b06515f0f59505d5751504e524855
    # 6fede9d0-ce6c-4c97-bcb8-43c499fc24e5

    # file_path2 = 'geo/alskdjhfasldjkfh/TYQWA/original.text'
    # file_path2 = 'geo/ef66d5f9-cadb-43f3-b8cf-824d75a81e7c/TYQWA/original.text'
    # qianwen_android_process_original_data(file_path2)


    # data_list = bh_utils.query_data(f"select * from geo_commit_task  where taskId = '0001e01d-a8ea-405e-acef-93e4f55abbff' and  platform  = 'TYQWA'")
    data_list = bh_utils.query_data(f"select * from geo_commit_task where taskId = 'b347cfe7-0f74-47c4-8328-3c92b9cad1ea' and platform = 'TYQWA'")

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


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