import json
import traceback
from asyncio import as_completed
from concurrent.futures import ThreadPoolExecutor

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 qianwen_android_process_original_data(data):
# def qianwen_android_process_original_data(file_path):
    file_path = f'geo/{data["taskId"]}/{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 = []
    try:
        json_original = ""
        original_content = get_string_from_tos(file_path)
        try:
            json_original = 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 =next(
                (item.get('content') for item in bar_sources if item.get('type') == 'source'),
                {}
            )
            source_list = source_content.get('list', [])

            video_note_list = sse_json_data.get('video_note_list',{}).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({
                    "utl":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 == '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' 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):
                                                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": 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'),
                                                    })

                                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'

                                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
                                                    })
                                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 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

        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 = 'd652c3d0-484b-46b6-aefc-1ccd58c46a51' 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:
                ...
