import json
import re

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 process_price(ori_price):

    price_match = re.search(
        r"\d+(?:\.\d+)?",
        str(ori_price).replace(",", "")
    )

    if price_match:
        price_number = float(price_match.group())
        price = int(price_number) if price_number.is_integer() else price_number
    else:
        price = 0
    return price


def yuanbao_android_process_original_data(task_data):
    file_path = f'geo/{task_data["taskId"]}/{task_data["platform"]}/original.text'
    """处理文件内容，提取思考内容、响应内容和URL列表"""
    url_list = []
    think_content = ""
    response_content = ""
    response_process = ""
    search_keyword = []
    is_think = False
    think_bool = False
    suggestions = []
    rich_media_block = []
    mini_program = []
    jd_goods = []
    tx_goods = []
    response_bool = False
    try:
        original_content = get_string_from_tos(file_path)
        # # 按空行分割内容，过滤空字符串
        content_list = original_content.split("\n\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  # 跳过格式错误的数据
                if json_data.get('type') == 'searchGuid':
                    url_list = json_data.get('docs')
                if json_data.get('type') == 'think':
                    think_content += json_data.get('content')

                if json_data.get('type') == 'text' and json_data.get('msg') is not None:
                    response_content += json_data.get('msg')
                if json_data.get('type') == 'deepSearch':
                    if json_data.get('contents'):
                        if json_data.get('contents')[0].get('msg'):
                            if json_data.get('contents')[0].get('type') == 'text':
                                think_content += json_data.get('contents')[0].get('msg')

                        if json_data.get('contents')[0].get('docs'):
                            url_list.extend(json_data.get('contents')[0].get('docs'))
                if json_data.get('type') == 'image':
                    response_content = "生成了图片"
                if json_data.get('type') == 'replace':
                    replace_data = json_data.get("replace") or {}
                    if json_data.get('replace').get('display') == 'videoBoxV2':
                        rich_media_block.extend(json_data.get('replace').get('multimedias'))
                    if json_data.get('replace').get('display') == 'miniProgramBox':

                        response_content += json_data.get('replace').get('title')

                        response_content += '\n\nrender_ecom_card_widget_miniprogram_start:\n\n'
                        for pro in json_data.get('replace').get('multimedias'):
                            title = pro.get('title', '')
                            icon = pro.get('linkInfo', {}).get('icon', '') or pro.get('linkInfo', {}).get('iconDark',
                                                                                                          '')
                            wx_app_id = pro.get('linkInfo', {}).get('wxAppId', '')
                            response_mini = {
                                "title": title,
                                "icon": icon,
                                "wx_app_id": wx_app_id,
                            }
                            mini_program.append(response_mini)
                        mini_program_str = json.dumps(mini_program, ensure_ascii=False)
                        response_content += mini_program_str
                        response_content += '\n\nrender_ecom_card_widget_miniprogram_end:'
                    if replace_data.get("display") == "goods":
                        replace_media_id = replace_data.get('id')

                        for media in replace_data.get("multimedias") or []:
                            if not isinstance(media, dict):
                                continue

                            goods_content = media.get("goodsContent") or {}
                            goods = goods_content.get("goods") or {}

                            # 没有真实商品数据，说明只是占位/加载事件
                            if not isinstance(goods, dict):
                                continue

                            sku_id = goods.get("skuId")
                            sku_name = goods.get("skuName")

                            # 有商品 ID 和商品名才认为是有效商品
                            if not sku_id or not sku_name:
                                continue
                            raw_content = {}
                            try:
                                raw_content = json.loads(goods.get("rawContent") or "{}")
                            except (TypeError, json.JSONDecodeError):
                                raw_content = {}
                            endpoint_url = goods_content.get("endpointUrl") or {}
                            shop_id = goods.get("shopId") or raw_content.get("shopId", "")

                            goods_data = {
                                "replace_media_id":replace_media_id,
                                "sku": str(sku_id),
                                "sku_name": sku_name,
                                "query": goods.get("query", ""),
                                "image_url": (
                                        goods.get("imagePath")
                                        or raw_content.get("whiteImage")
                                        or raw_content.get("imgPath")
                                        or ""
                                ),
                                "price": process_price(goods.get("purchasePrice", "")),
                                "shop_name": goods.get("shopName", ""),
                                "shop_id": shop_id,
                                "source": goods.get("source", ""),
                                "pc_url": endpoint_url.get("pcUrl", "")
                            }
                            jd_goods.append(goods_data)
                    if json_data.get('replace').get('display') == 'surroundingsV3':
                        for media in replace_data.get("multimedias") or []:
                            if not isinstance(media, dict):
                                continue
                            tx_data = {
                                "title":media.get('title'),
                                "address":media.get('address'),
                                "jumpUrl":media.get('jumpUrl'),
                                "poiId":media.get('poiId'),
                                "distance":media.get('distance'),
                                "avgPrice":media.get('avgPrice'),
                                "starLevel":media.get('starLevel')
                            }
                            tx_goods.append(tx_data)


        if jd_goods:
            response_content += '\n\nrender_ecom_card_widget_jd_start:\n\n'
            jd_goods_str = json.dumps(jd_goods, ensure_ascii=False)
            response_content += jd_goods_str
            response_content += '\n\nrender_ecom_card_widget_jd_end:'
            save_eco_data_to_bh(task_data,'jdeco',jd_goods)
        if tx_goods:
            response_content += '\n\nrender_ecom_card_widget_txmap_start:\n\n'
            tx_goods_str = json.dumps(tx_goods, ensure_ascii=False)
            response_content += tx_goods_str
            response_content += '\n\nrender_ecom_card_widget_txmap_end:'
            save_eco_data_to_bh(task_data,'txmap',tx_goods)
        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)
    return (file_path, search_keyword, url_list, think_content, response_content, suggestions)


if __name__ == '__main__':
    # file_path2 = 'geo/6f49084e-f191-447d-849b-bc6c60fd5d20/TXYBA/original.text'
    # yuanbao_android_process_original_data(file_path2)

    data_list = bh_utils.query_data(
        f"select * from geo_commit_task  where taskId = '0f934ad9-c45e-43eb-93e4-9a0fa5dce5a0' and  platform  = 'TXYBA'")


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


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