import re
from aidso_geo.utils import bh_utils,ai_utils



def process_eco_product_relation(
    eco_result,
    keyword,
    batch_size=500,
):
    """
    每100条商品调用一次AI，并将识别结果合并到原商品数据中。
    produce_name只用于匹配，不写入最终结果。
    """

    def normalize_title(value):
        return " ".join(
            str(value or "").strip().split()
        )

    final_result = []

    for start_index in range(
        0,
        len(eco_result),
        batch_size,
    ):
        batch = eco_result[
            start_index:start_index + batch_size
        ]

        product_list = [
            str(item.get("eco_title") or "").strip()
            for item in batch
        ]
        try:
            ai_result = (
                ai_utils.ai_get_product_relation_spu(
                    product_list,
                    keyword,
                )
            )
        except Exception as exc:
            print(
                f"AI商品识别失败: "
                f"batch={start_index // batch_size + 1}, "
                f"error={exc}"
            )
            ai_result = []

        if not isinstance(ai_result, list):
            ai_result = []

        # produce_name只用于建立匹配关系。
        ai_result_map = {}

        for ai_item in ai_result:
            if not isinstance(ai_item, dict):
                continue

            produce_name = str(
                ai_item.get("produce_name") or ""
            ).strip()

            normalized_name = normalize_title(
                produce_name
            )
            if not normalized_name:
                continue

            if normalized_name not in ai_result_map:
                ai_result_map[normalized_name] = ai_item

        for original_item in batch:
            eco_title = str(
                original_item.get("eco_title") or ""
            ).strip()

            matched_item = ai_result_map.get(
                normalize_title(eco_title)
            )

            # 未匹配时的默认值。
            relation_data = {
                "brand": eco_title,
                "spu_name": "",
                "current": 0,
            }

            if isinstance(matched_item, dict):
                brand = str(
                    matched_item.get("brand")
                    or eco_title
                ).strip()

                spu_name = str(
                    matched_item.get("spu_name")
                    or ""
                ).strip()

                try:
                    current = int(
                        matched_item.get("current", 0)
                    )
                except (TypeError, ValueError):
                    current = 0
                if brand == spu_name:
                    spu_name = brand
                else:
                    spu_name = brand+" "+spu_name

                relation_data = {
                    "brand": brand,
                    "search_goods_word":keyword,
                    "spu_name": spu_name,
                    "current": (
                        1 if current == 1 else 0
                    ),
                }

            final_result.append(
                {
                    **original_item,
                    **relation_data,
                }
            )
    for item in final_result:
        item["isCalculateSearchWord"] = 1
    bh_utils.insert_data('geo_eco_data', final_result)
    return final_result


def extract_price(price):
    if not price:
        return ''

    price = str(price).strip()

    # 提取“元”前面的整数或小数
    match = re.search(r'(\d+(?:\.\d+)?)\s*元', price)

    return match.group(1) if match else ''
def qianwen_android_process_taobao_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        if item.get('card_type') =='single_product':
            raw_data = {
                "eco_id": item.get('item_id', ''),
                "eco_url": item.get('auctionURL', '') or item.get('jump_url',''),
                "eco_title": item.get('title', ''),
                "eco_index": index+1,
                "eco_pic": item.get('pic_path', ''),
                "eco_price": item.get('price', ''),
                "eco_source": 'taobao',
                "platform": platform,
                "task_id": task_id,
                "req_id": req_id,
                "prompt": prompt
            }
            eco_result.append(raw_data)

    return eco_result

def qianwen_android_process_damai_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('id', ''),
            "eco_url": item.get('webURL', '') ,
            "eco_title": item.get('name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('verticalPic', ''),
            "eco_price": item.get('priceShowText', ''),
            "eco_source": 'damai',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result


def qianwen_android_process_gaode_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('poi_id', ''),
            "eco_url": item.get('url', '') ,
            "eco_title": item.get('name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('photos', ''),
            "eco_price": item.get('cost', ''),
            "eco_source": 'gaode',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def doubao_android_process_douyin_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('pid', ''),
            "eco_url": item.get('jump_url', '') ,
            "eco_title": item.get('text', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', ''),
            "eco_price": item.get('priceShowText', ''),
            "eco_source": 'dyeco',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def doubao_android_process_douyin_poi_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('poi_id', ''),
            "eco_url": item.get('poi_url', '') ,
            "eco_title": item.get('poi_name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_list', [])[0].get('large_url','') or item.get('image_list', [])[0].get('small_url',''),
            "eco_price": extract_price(item.get('price', '')),
            "eco_source": 'dypoi',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result



def yuanbao_android_process_jd_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('sku', ''),
            "eco_url": item.get('pc_url', '') ,
            "eco_title": item.get('sku_name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', ''),
            "eco_price": item.get('price', ''),
            "eco_source": 'jdeco',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def yuanbao_process_jd_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('sku', ''),
            "eco_url": item.get('pc_url', '') ,
            "eco_title": item.get('sku_name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', ''),
            "eco_price": item.get('price', ''),
            "eco_source": 'jdeco',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def yuanbao_process_txmap_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('poiId', ''),
            "eco_url": item.get('jumpUrl', '') ,
            "eco_title": item.get('title', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', 'https://tcdn.aidso.com/dso/pc/aiDialoguePng/112_112.jpg?v=2'),
            "eco_price": item.get('avgPrice', ''),
            "eco_source": 'txmap',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def yuanbao_android_process_txmap_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('poiId', ''),
            "eco_url": item.get('jumpUrl', '') ,
            "eco_title": item.get('title', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', 'https://tcdn.aidso.com/dso/pc/aiDialoguePng/112_112.jpg?v=2'),
            "eco_price": item.get('avgPrice', ''),
            "eco_source": 'txmap',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def save_eco_data_to_bh(data,eco_type,eco_list):

    platform = data.get('platform')
    search_goods_word = data.get('searchGoodsWord')

    eco_result = []
    if platform == 'TYQWA':
        if eco_type == 'taobao':
            eco_result = qianwen_android_process_taobao_eco(data,eco_list)
        if eco_type == 'damai':
            eco_result = qianwen_android_process_damai_eco(data, eco_list)
        if eco_type == 'gaode':
            eco_result = qianwen_android_process_gaode_eco(data, eco_list)
    if platform == 'DOUBA':
        if eco_type == 'dypoi':
            eco_result = doubao_android_process_douyin_poi_eco(data, eco_list)
        if eco_type == 'dyeco':
            eco_result =doubao_android_process_douyin_eco(data,eco_list)
    if platform == 'TXYBA':
        if eco_type == 'jdeco':
            eco_result =yuanbao_android_process_jd_eco(data,eco_list)
        if eco_type == 'txmap':
            eco_result = yuanbao_android_process_txmap_eco(data,eco_list)
    if platform == 'TXYB':
        if eco_type == 'jdeco':
            eco_result =yuanbao_process_jd_eco(data,eco_list)
        if eco_type == 'txmap':
            eco_result = yuanbao_process_txmap_eco(data,eco_list)

    if search_goods_word:
        eco_result = process_eco_product_relation(eco_result, search_goods_word)
        for item in eco_result:
            item["isCalculateSearchWord"] = None
    bh_utils.insert_data('geo_eco_data',eco_result)
if __name__ == '__main__':
    result = bh_utils.query_data("select * from geo_eco_data where req_id in ('3a9edb7d-c98b-4ad2-8ae5-f53c4803ba99')")
    eco_result = process_eco_product_relation(result, "忠芝")
    for item in result:
        item["isCalculateSearchWord"] = None
    bh_utils.insert_data('geo_eco_data', result)

