"""Bulk-attach product photos from a folder.

Name each file after the product's URL slug (from the admin or price-list.csv), optionally with a number for extra
angles:  hp-elitebook-840-g5-core-i5-8gb-ram-256gb-ssd-14-inch.jpg, ...-2.jpg, ...-3.jpg
Every photo is compressed to WebP (400/800/1200 px) and added to the product in number order.

    python manage.py import_photos /path/to/photos [--replace]
"""
import os
import re

from django.core.management.base import BaseCommand, CommandError

from store.db import get_db
from store.images import process
from store.utils import now

EXT = (".jpg", ".jpeg", ".png", ".webp", ".avif")  # convert iPhone HEIC to JPG first


class Command(BaseCommand):
    help = "Compress and attach product photos named <slug>.jpg / <slug>-2.jpg"

    def add_arguments(self, parser):
        parser.add_argument("folder")
        parser.add_argument("--replace", action="store_true", help="Replace existing photos instead of adding")
        parser.add_argument("--manifest", help="manifest.json from fetch_images --commons (adds licence credits)")

    def handle(self, folder, replace=False, manifest=None, **opts):
        if not os.path.isdir(folder):
            raise CommandError(f"Folder not found: {folder}")
        import json
        credits_by_file = json.load(open(manifest)) if manifest else {}
        db = get_db()
        slugs = {p["slug"] for p in db.products.find({}, {"slug": 1})}
        groups, unmatched = {}, []
        for f in sorted(os.listdir(folder)):
            if not f.lower().endswith(EXT):
                continue
            stem = os.path.splitext(f)[0].lower()
            m = re.match(r"^(.*?)(?:-(\d{1,2}))?$", stem)
            slug, order = (stem, 1) if stem in slugs else (m.group(1), int(m.group(2) or 1))
            if slug not in slugs:
                unmatched.append(f)
                continue
            groups.setdefault(slug, []).append((order, f))
        total_in = total_out = 0
        for slug, files in groups.items():
            urls, credits = [], []
            for _, f in sorted(files):
                path = os.path.join(folder, f)
                with open(path, "rb") as fh:
                    try:
                        res = process(fh, f, hint=slug)
                    except ValueError as e:
                        self.stderr.write(f"  skip {f}: {e}")
                        continue
                total_in += os.path.getsize(path)
                total_out += res["sizes"][400]
                urls.append(res["url"])
                if f in credits_by_file:
                    credits.append({**credits_by_file[f]["credit"], "url": res["url"]})
            if urls:
                upd = {"$set": {"images": urls, "image_credits": credits, "updated_at": now()}} if replace else \
                      {"$push": {"images": {"$each": urls}, "image_credits": {"$each": credits}}, "$set": {"updated_at": now()}}
                db.products.update_one({"slug": slug}, upd)
                self.stdout.write(f"  {slug}: {len(urls)} photo(s)")
        if unmatched:
            self.stderr.write("No product matches these files (rename to the product slug):\n  " + "\n  ".join(unmatched))
        if total_in:
            self.stdout.write(self.style.SUCCESS(
                f"Done: {sum(len(v) for v in groups.values())} photos for {len(groups)} products. "
                f"Originals {total_in/1e6:.1f} MB → mobile versions {total_out/1e6:.2f} MB."))
