"""
migrate_products.py

Run once to fix existing product records:

  FBA & FBT products:
    - Clear shipping from every variant (set to "")
    - Set top-level shippings: []

  All other products:
    - If shippings array is missing or empty, extract unique shipping values
      from variants and write them as the top-level shippings field.
    - Variant shipping values are left unchanged.

Usage:
    python migrate_products.py [--dry-run]
"""

import sys
from MongoDBConnection import MONGO_URI, DB_NAME
from pymongo import MongoClient

FBA_FBT_CATEGORY = "FBA & FBT"
DRY_RUN = "--dry-run" in sys.argv


def migrate():
    client = MongoClient(MONGO_URI)
    collection = client[DB_NAME]["products"]

    products = list(collection.find({}))
    print(f"Total products found: {len(products)}")

    updated_fba = 0
    updated_other = 0
    skipped = 0

    for p in products:
        product_id = p.get("productId", str(p["_id"]))
        category = p.get("categoryName", "")
        variants = p.get("variants", []) or []

        if category == FBA_FBT_CATEGORY:
            cleaned_variants = [
                {**v, "shipping": ""} for v in variants
            ]
            update = {
                "$set": {
                    "shippings": [],
                    "variants": cleaned_variants,
                }
            }
            print(f"[FBA&FBT] {product_id}: clear shipping from {len(variants)} variants")
            if not DRY_RUN:
                collection.update_one({"_id": p["_id"]}, update)
            updated_fba += 1
        else:
            existing_shippings = p.get("shippings", []) or []
            if existing_shippings:
                skipped += 1
                print(f"[SKIP]    {product_id}: already has shippings={existing_shippings}")
                continue

            derived = list(dict.fromkeys(
                str(v.get("shipping", "")).strip()
                for v in variants
                if str(v.get("shipping", "")).strip()
            ))
            update = {"$set": {"shippings": derived}}
            print(f"[OTHER]   {product_id}: set shippings={derived}")
            if not DRY_RUN:
                collection.update_one({"_id": p["_id"]}, update)
            updated_other += 1

    print()
    print(f"FBA&FBT updated : {updated_fba}")
    print(f"Others  updated : {updated_other}")
    print(f"Skipped         : {skipped}")
    if DRY_RUN:
        print("DRY RUN — no changes written.")
    client.close()


if __name__ == "__main__":
    migrate()
