#!/usr/bin/env python3
"""
Cin7 → yudao-vue-pro Sync Tool
Usage:
    python main.py                  # sync all
    python main.py --products       # products only
    python main.py --categories     # categories only
    python main.py --brands         # brands only
    python main.py --members        # members only
    python main.py --test           # test Cin7 API connection only
"""
import argparse
import sys

from config import TENANT_ID
from cin7_api import Cin7Api
from sync_category import sync_categories, CATEGORY_ID_MAP
from sync_brand import sync_brands, BRAND_ID_MAP
from sync_spu import sync_spus, SPU_ID_MAP
from sync_member import sync_members, MEMBER_ID_MAP


def test_connection():
    print("Testing Cin7 API connection...")
    api = Cin7Api()
    if api.test_connection():
        print("[OK] Cin7 API connection successful")
        return True
    else:
        print("[FAIL] Cin7 API connection failed — check credentials in config.py")
        return False


def main():
    parser = argparse.ArgumentParser(description="Cin7 → yudao Sync")
    parser.add_argument("--products", action="store_true", help="Sync products (SPU + SKU)")
    parser.add_argument("--categories", action="store_true", help="Sync categories")
    parser.add_argument("--brands", action="store_true", help="Sync brands")
    parser.add_argument("--members", action="store_true", help="Sync members (Customers)")
    parser.add_argument("--test", action="store_true", help="Test Cin7 API connection")
    parser.add_argument("--tenant-id", type=int, default=TENANT_ID, help="yudao tenant_id")
    args = parser.parse_args()

    tenant_id = args.tenant_id

    if args.test:
        sys.exit(0 if test_connection() else 1)

    # Default: sync everything
    sync_all = not any([args.products, args.categories, args.brands, args.members])

    api = Cin7Api()

    if sync_all or args.categories:
        sync_categories(api, tenant_id)

    if sync_all or args.brands:
        sync_brands(api, tenant_id)

    if sync_all or args.products:
        sync_spus(api, tenant_id)

    if sync_all or args.members:
        sync_members(api, tenant_id)

    print("\n=== Sync Complete ===")
    print(f"  Categories: {len(CATEGORY_ID_MAP)}")
    print(f"  Brands:     {len(BRAND_ID_MAP)}")
    print(f"  SPU:        {len(SPU_ID_MAP)}")
    print(f"  Members:    {len(MEMBER_ID_MAP)}")


if __name__ == "__main__":
    main()