from django.core.management.base import BaseCommand
from catalog.models import Product, Category, ProductImage
from django.core.files import File
from django.conf import settings
import random
import os
from decimal import Decimal
import string

def random_title():
    words = ['Fresh', 'Organic', 'Premium', 'Natural', 'Tasty', 'Crispy', 'Sweet', 'Juicy', 'Classic', 'Healthy']
    return ' '.join(random.choice(words) for _ in range(3))

SAMPLE_IMAGES_DIR = os.path.join(settings.BASE_DIR, 'media', 'images', 'products')

class Command(BaseCommand):
    help = 'Generate sample products with images'

    def add_arguments(self, parser):
        parser.add_argument('--count', type=int, default=100, help='Number of products to create')

    def handle(self, *args, **options):
        count = options['count']
        images = []
        if os.path.isdir(SAMPLE_IMAGES_DIR):
            for f in os.listdir(SAMPLE_IMAGES_DIR):
                if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif')):
                    images.append(os.path.join(SAMPLE_IMAGES_DIR, f))

        if not images:
            self.stdout.write(self.style.ERROR(f'No sample images found in {SAMPLE_IMAGES_DIR}.'))
            return

        # Ensure at least one category
        categories = list(Category.objects.all())
        if not categories:
            cat = Category.objects.create(name='Sample')
            categories = [cat]

        for i in range(count):
            title = random_title()
            price = Decimal(random.randint(100, 5000)) / Decimal(100)
            category = random.choice(categories)
            product = Product.objects.create(
                title=title,
                description=' '.join(random.choice(string.ascii_letters) for _ in range(120)),
                price=price,
                unit=random.choice(['عدد', 'کیلوگرم', 'بسته']),
                weight_grams=random.choice([0, 100, 250, 500, 1000]),
                category=category,
                in_stock=True,
                stock_qty=random.randint(1, 500),
                tags=','.join(random.choice(['grocery','organic','sale','fresh','popular','imported','local']) for _ in range(3)),
            )

            # attach thumbnail
            thumb_path = random.choice(images)
            with open(thumb_path, 'rb') as fh:
                product.thumbnail.save(os.path.basename(thumb_path), File(fh), save=True)

            # attach 1-3 extra images
            for _ in range(random.randint(1,3)):
                img_path = random.choice(images)
                with open(img_path, 'rb') as fh:
                    pi = ProductImage(product=product)
                    pi.image.save(f'{product.slug or product.id}_{os.path.basename(img_path)}', File(fh), save=True)

            if (i+1) % 10 == 0:
                self.stdout.write(self.style.SUCCESS(f'Created {i+1}/{count} products'))

        self.stdout.write(self.style.SUCCESS(f'Finished creating {count} products'))
