"""
品牌检测与排他协议辅助判断
"""
import re
from typing import List, Dict, Any

# 中国品牌
CHINESE_BRANDS = [
    "byd", "chery", "dfsk", "dongfeng", "foton", "gac", "geely",
    "great wall", "haval", "jac", "jetour", "li auto", "mg", "nio",
    "omoda", "ora", "wuling", "xpeng", "zeekr", "changan", "baic",
    " brilliance", "maxus", "saic"
]

# 常见非中国品牌（用于判断“无排他”）
NON_CHINESE_BRANDS = [
    "audi", "bmw", "citroen", "dacia", "fiat", "ford", "honda",
    "hyundai", "kia", "mercedes", "nissan", "opel", "peugeot",
    "renault", "seat", "skoda", "toyota", "volkswagen", "volvo",
    "jeep", "chevrolet", "mazda", "mitsubishi", "suzuki"
]


def detect_brands(text: str) -> Dict[str, List[str]]:
    """从文本中检测品牌词"""
    if not text:
        return {"chinese": [], "non_chinese": [], "all": []}

    text_lower = text.lower()
    found_chinese = []
    found_non_chinese = []

    for brand in CHINESE_BRANDS:
        if re.search(r'\b' + re.escape(brand) + r'\b', text_lower):
            found_chinese.append(brand)

    for brand in NON_CHINESE_BRANDS:
        if re.search(r'\b' + re.escape(brand) + r'\b', text_lower):
            found_non_chinese.append(brand)

    return {
        "chinese": found_chinese,
        "non_chinese": found_non_chinese,
        "all": found_chinese + found_non_chinese
    }


def assess_exclusivity(text: str) -> str:
    """
    辅助判断排他协议状态
    返回: 疑似无排他，可合作 / 已代理中国品牌，需评估 / 信息不足，待判断
    """
    brands = detect_brands(text)

    if brands["chinese"]:
        return "已代理中国品牌，需评估"

    if brands["non_chinese"] and len(brands["non_chinese"]) >= 1:
        return "疑似无排他，可合作"

    return "信息不足，待判断"


def enrich_record_with_brands(record: Dict[str, Any]) -> Dict[str, Any]:
    """给记录添加品牌检测字段"""
    combined_text = " ".join([
        str(record.get("主营业务", "")),
        str(record.get("备注", "")),
        str(record.get("客户类型", ""))
    ])
    brands = detect_brands(combined_text)
    record["detected_brands"] = brands["all"]
    record["exclusivity_assessment"] = assess_exclusivity(combined_text)
    return record
