"""
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_all, insert_many, update_many


BRAND_ID_MAP = {}           # cin7_id -> yudao_id
BRAND_NAME_TO_ID_MAP = {}   # name -> yudao_id


def sync_brands(cin7_api, tenant_id=0):
    """
    Fetch all Cin7 brands and sync to yudao in two bulk operations:
      1. One query_all to load existing rows into memory
      2. One insert_many for new brands
      3. One update_many for changed brands
    No per-row DB round-trips, no threading overhead.
    """
    global BRAND_ID_MAP, BRAND_NAME_TO_ID_MAP
    BRAND_ID_MAP = {}
    BRAND_NAME_TO_ID_MAP = {}

    print("\n=== Sync Brands ===")
    raw = cin7_api.get_brands()
    brands = raw.get("d", []) if isinstance(raw, dict) else raw
    print(f"[brand] Fetched {len(brands)} brands from Cin7")

    # Load all existing brands in one shot
    existing_rows = query_all("SELECT id FROM product_brand WHERE deleted=0")
    existing_ids = {r["id"] for r in existing_rows}

    to_insert = []
    to_update = []

    for b in brands:
        cin7_id = b.get("id")
        name = (b.get("company") or "").strip()
        if not name or not cin7_id:
            continue

        status   = 0 if b.get("isActive", True) else 1
        pic_url  = b.get("logoUrl") or ""
        sort_ord = b.get("sortOrder") or 0
        desc     = b.get("description") or ""

        # Populate in-memory maps (yudao id == cin7 id for brands)
        BRAND_ID_MAP[cin7_id] = cin7_id
        BRAND_NAME_TO_ID_MAP[name] = cin7_id

        if cin7_id in existing_ids:
            to_update.append((name, pic_url, sort_ord, desc, status, cin7_id))
        else:
            to_insert.append((cin7_id, name, pic_url, sort_ord, desc, status, tenant_id))

    if to_insert:
        insert_many(
            "INSERT INTO product_brand "
            "(id, name, pic_url, sort, description, status, tenant_id, "
            "creator, create_time, updater) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s, 'cin7_sync', NOW(), 'cin7_sync')",
            to_insert,
        )
        print(f"[brand] Inserted {len(to_insert)} new brands")

    if to_update:
        update_many(
            "UPDATE product_brand SET name=%s, pic_url=%s, sort=%s, description=%s, "
            "status=%s, update_time=NOW(), updater='cin7_sync' WHERE id=%s",
            to_update,
        )
        print(f"[brand] Updated {len(to_update)} existing brands")

    print(f"[brand] Done. {len(to_insert)} created, {len(to_update)} updated.")
    return BRAND_ID_MAP


def ensure_brand(cin7_brand, tenant_id=0):
    """
    Lightweight helper used by sync_spu when a brand is encountered mid-sync.
    Falls back to a single upsert if the brand wasn't pre-loaded by sync_brands.
    """
    from db import query_one, execute_one, insert_and_get_id

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

    if cin7_id in BRAND_ID_MAP:
        return BRAND_ID_MAP[cin7_id], False

    status  = 0 if cin7_brand.get("isActive", True) else 1
    pic_url = cin7_brand.get("logoUrl") or ""
    sort_ord = cin7_brand.get("sortOrder") or 0
    desc    = cin7_brand.get("description") or ""

    existing = query_one(
        "SELECT id FROM product_brand WHERE id=%s AND deleted=0 LIMIT 1",
        (cin7_id,),
    )
    if existing:
        execute_one(
            "UPDATE product_brand SET name=%s, pic_url=%s, sort=%s, description=%s, "
            "status=%s, update_time=NOW(), updater='cin7_sync' WHERE id=%s",
            (name, pic_url, sort_ord, desc, status, cin7_id),
        )
        yudao_id = existing["id"]
    else:
        yudao_id = insert_and_get_id(
            "INSERT INTO product_brand "
            "(id, name, pic_url, sort, description, status, tenant_id, "
            "creator, create_time, updater) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s, 'cin7_sync', NOW(), 'cin7_sync')",
            (cin7_id, name, pic_url, sort_ord, desc, status, tenant_id),
        )

    BRAND_ID_MAP[cin7_id] = yudao_id
    BRAND_NAME_TO_ID_MAP[name] = yudao_id
    return yudao_id, not existing
