"""
Sync product brands from Cin7 to yudao product_brand table

Cin7 Brands fields: id, company (name), logoUrl, isActive, sortOrder
yudao product_brand: id, name, pic_url, sort, description, status, tenant_id
"""
from db import query_one, insert_and_get_id, execute_one


# Map Cin7 brand_id → yudao brand_id
BRAND_ID_MAP = {}  # cin7_id -> yudao_id


def ensure_brand(cin7_brand, tenant_id=0):
    """
    Ensure brand exists. Returns (yudao_id, created_bool)
    """
    cin7_id = cin7_brand["id"]
    if cin7_id in BRAND_ID_MAP:
        return BRAND_ID_MAP[cin7_id], False

    name = (cin7_brand.get("company") or "").strip()
    if not name:
        return None, False

    is_active = cin7_brand.get("isActive", True)
    status = 0 if is_active else 1  # 0=开启, 1=禁用

    # Check if already exists by name
    existing = query_one(
        "SELECT id FROM product_brand WHERE name=%s AND deleted=0 LIMIT 1",
        (name,)
    )
    if existing:
        yudao_id = existing["id"]
        BRAND_ID_MAP[cin7_id] = yudao_id
        # Update logo/status if changed
        execute_one(
            "UPDATE product_brand SET pic_url=%s, status=%s WHERE id=%s",
            (cin7_brand.get("logoUrl") or "", status, yudao_id)
        )
        print(f"  [brand] updated id={yudao_id} name='{name}'")
        return yudao_id, False

    pic_url = cin7_brand.get("logoUrl") or ""
    sort_order = cin7_brand.get("sortOrder") or 0

    yudao_id = insert_and_get_id(
        "INSERT INTO product_brand (name, pic_url, sort, status, tenant_id, creator, create_time, updater) "
        "VALUES (%s, %s, %s, %s, %s, 'cin7_sync', NOW(), 'cin7_sync')",
        (name, pic_url, sort_order, status, tenant_id)
    )
    BRAND_ID_MAP[cin7_id] = yudao_id
    print(f"  [brand] created id={yudao_id} name='{name}'")
    return yudao_id, True


def sync_brands(cin7_api, tenant_id=0):
    """Fetch all Cin7 brands and sync to yudao"""
    print("\n=== Sync Brands ===")
    raw = cin7_api.get_brands()
    brands = raw.get("d", []) if isinstance(raw, dict) else raw

    for b in brands:
        ensure_brand(b, tenant_id)

    print(f"[brand] Done. {len(BRAND_ID_MAP)} brands mapped.")
    return BRAND_ID_MAP