"""Write a CSV for filling in manufacturer part numbers (MPN) or barcodes (GTIN/EAN) so official photos can be
fetched from Open Icecat.

    python manage.py export_image_sources image-sources.csv          # products without photos
    python manage.py export_image_sources image-sources.csv --all    # every product

Where to find the codes: the sticker under a laptop ("Product No." / "P/N" on HP, "MTM" or "Type" on Lenovo,
part number on ASUS), the box barcode for new stock, or your distributor's invoice/price list.
"""
import csv

from django.core.management.base import BaseCommand

from store.db import get_db


class Command(BaseCommand):
    help = "Export a CSV template (slug, name, brand, mpn, gtin) for the image fetcher"

    def add_arguments(self, parser):
        parser.add_argument("path")
        parser.add_argument("--all", action="store_true")

    def handle(self, path, **opts):
        q = {} if opts["all"] else {"$or": [{"images": {"$size": 0}}, {"images": {"$exists": False}}]}
        rows = list(get_db().products.find(q, {"slug": 1, "name": 1, "brand": 1, "category": 1, "mpn": 1, "gtin": 1})
                    .sort([("category", 1), ("name", 1)]))
        with open(path, "w", newline="", encoding="utf-8-sig") as f:
            w = csv.writer(f)
            w.writerow(["slug", "name", "brand", "category", "mpn", "gtin"])
            for p in rows:
                w.writerow([p["slug"], p["name"], p.get("brand", ""), p.get("category", ""), p.get("mpn", ""), p.get("gtin", "")])
        self.stdout.write(self.style.SUCCESS(f"Wrote {len(rows)} products to {path}. Fill the mpn or gtin column, then run "
                                             f"fetch_images --icecat-user YOUR_USERNAME --csv {path}"))
