from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.conf import settings
from catalog.models import Category, Product, ProductImage
from pathlib import Path
import json, os, shutil

class Command(BaseCommand):
    help = "Create admin user (admin/admin) and import products from data/products.json into SQLite."

    def handle(self, *args, **kwargs):
        # Admin user
        if not User.objects.filter(username="admin").exists():
            User.objects.create_superuser("admin", "admin@example.com", "admin")
            self.stdout.write(self.style.SUCCESS("Created admin user admin/admin"))
        else:
            self.stdout.write("Admin user already exists")

        data_path = Path(settings.BASE_DIR) / "data" / "products.json"
        if not data_path.exists():
            self.stdout.write(self.style.WARNING(f"{data_path} not found; skipping import."))
            return

        with open(data_path, "r", encoding="utf-8") as f:
            products = json.load(f)

        # Create categories
        cat_map = {}
        for p in products:
            cname = p.get("category") or "متفرقه"
            if cname not in cat_map:
                cat, _ = Category.objects.get_or_create(name=cname)
                cat_map[cname] = cat

        # Create products
        created = 0
        for p in products:
            cat = cat_map.get(p.get("category"))

            obj, created_flag = Product.objects.get_or_create(
                slug=p.get("slug"),
                defaults={
                    "title": p.get("title"),
                    "description": p.get("description",""),
                    "price": p.get("price",0),
                    "unit": p.get("unit","عدد"),
                    "weight_grams": p.get("weightGrams",0),
                    "category": cat,
                    "in_stock": p.get("inStock", True),
                    "stock_qty": 100,
                    "rating": p.get("rating", 0),
                    "reviews_count": p.get("reviewsCount", 0),
                    "tags": ",".join(p.get("tags", [])),
                }
            )
            # set thumbnail if exists
            img_rel = p.get("image")
            if img_rel:
                # convert '/images/... to media path
                src = Path(settings.BASE_DIR) / "media" / img_rel.strip("/")
                if src.exists():
                    # copy to products/ dir with slug filename
                    dst_dir = Path(settings.MEDIA_ROOT) / "products"
                    dst_dir.mkdir(parents=True, exist_ok=True)
                    dst = dst_dir / (p.get("slug") + src.suffix)
                    if not dst.exists():
                        shutil.copy2(src, dst)
                    obj.thumbnail.name = "products/" + dst.name
                    obj.save()

            if created_flag:
                created += 1

        self.stdout.write(self.style.SUCCESS(f"Imported/updated {len(products)} products; created {created} new."))
