import re
from aidso_geo.utils import bh_utils,ai_utils



def process_eco_product_relation(
    eco_result,
    keyword,
    batch_size=100,
):
    """
    每batch_size条商品调用一次AI，并将识别结果合并到原商品数据中。

    row_id只用于关联AI结果，不写入最终数据库。
    produce_name只用于传给AI和调试，不再用于匹配。
    """

    final_result = []

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

        # 给每条商品增加临时row_id。
        # 使用全局位置，保证整个任务内不重复。
        product_list = [
            {
                "row_id": start_index + batch_index,
                "produce_name": str(
                    item.get("eco_title") or ""
                ).strip(),
            }
            for batch_index, item in enumerate(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 = []

        expected_row_ids = {
            product["row_id"]
            for product in product_list
        }

        # 使用row_id建立AI结果映射。
        ai_result_map = {}

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

            raw_row_id = ai_item.get("row_id")

            # 兼容AI返回数字字符串的情况。
            if isinstance(raw_row_id, bool):
                continue

            try:
                row_id = int(raw_row_id)
            except (TypeError, ValueError):
                continue

            # 忽略本批次不存在的row_id。
            if row_id not in expected_row_ids:
                continue

            # 如果AI重复返回同一个row_id，保留第一条。
            if row_id not in ai_result_map:
                ai_result_map[row_id] = ai_item

        returned_row_ids = set(ai_result_map.keys())

        missing_row_ids = (
            expected_row_ids - returned_row_ids
        )

        for batch_index, original_item in enumerate(batch):
            row_id = start_index + batch_index

            eco_title = str(
                original_item.get("eco_title") or ""
            ).strip()

            matched_item = ai_result_map.get(row_id)

            # 没有匹配到row_id时使用默认值。
            relation_data = {
                "brand": eco_title,
                "search_goods_word": keyword,
                "spu_name": "",
                "current": 0,
            }

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

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

                try:
                    current = int(
                        matched_item.get(
                            "current",
                            0,
                        )
                    )
                except (TypeError, ValueError):
                    current = 0

                # 生成“品牌 + SPU名称”，同时避免重复品牌。
                if not ai_spu_name:
                    spu_name = brand
                elif ai_spu_name.startswith(brand):
                    spu_name = ai_spu_name
                else:
                    spu_name = (
                        f"{brand} {ai_spu_name}"
                    ).strip()

                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

    insert_success = bh_utils.insert_data(
        "geo_eco_data",
        final_result,
    )

    if not insert_success:
        print(
            "商品关系结果写入失败: "
            f"rows={len(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
    # eco_result = process_eco_product_relation(eco_result, search_goods_word)
    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 ='c23acb75eb114cb085f01fb744b1337f'")
    eco_result = process_eco_product_relation(result, "小米洗地机")
    # for item in eco_result:
    #     item["isCalculateSearchWord"] = None

    print(eco_result)
    bh_utils.insert_data('geo_eco_data', eco_result)

