import random
import string
from django.core.management.base import BaseCommand
from django.core.files.base import ContentFile
from PIL import Image, ImageDraw
from product.models import Product, Category, Tags, Images

# Try to import Faker, use fallback if not available
try:
    from faker import Faker
    fake = Faker(['tr_TR'])
    HAS_FAKER = True
except ImportError:
    HAS_FAKER = False

class Command(BaseCommand):
    help = 'Generates fake data for products, categories, and tags.'

    def handle(self, *args, **kwargs):
        self.stdout.write("Generating fake data...")
        
        if not HAS_FAKER:
            self.stdout.write(self.style.WARNING("Faker library not found. Using simple random data generator. Install with 'pip install faker' for better data."))

        # 1. Generate Categories
        categories = []
        for i in range(10):
            title = fake.word().capitalize() if HAS_FAKER else f"Kategori {i+1}"
            keywords = ','.join(fake.words(nb=5)) if HAS_FAKER else "test, kategori, urun"
            description = fake.sentence() if HAS_FAKER else f"Bu kategori {i+1} için açıklamadır."
            
            cat = Category.objects.create(
                title=title,
                keywords=keywords,
                description=description
            )
            categories.append(cat)
        self.stdout.write(self.style.SUCCESS(f"{len(categories)} categories created."))

        # 2. Generate Tags
        tags = []
        for i in range(20):
            tag_name = fake.word() if HAS_FAKER else f"Etiket {i+1}"
            tag = Tags.objects.create(tag=tag_name)
            tags.append(tag)
        self.stdout.write(self.style.SUCCESS(f"{len(tags)} tags created."))

        # 3. Generate Gallery Images
        gallery_images = []
        for i in range(15):
            img_name = f"gallery_{i}.jpg" # Using jpg for better compatibility
            img = self._generate_random_image(img_name)
            title = fake.word() if HAS_FAKER else f"Resim {i+1}"
            
            image_instance = Images.objects.create(title=title)
            image_instance.images.save(img_name, img)
            gallery_images.append(image_instance)
        self.stdout.write(self.style.SUCCESS(f"{len(gallery_images)} gallery images created."))

        # 4. Generate Products
        products = []
        for i in range(50):
            product_title = fake.company() if HAS_FAKER else f"Ürün {i+1} - {self._random_string(5)}"
            content = fake.paragraph(nb_sentences=10) if HAS_FAKER else f"Bu ürün {i+1} için detaylı açıklamadır. " * 5
            keywords = ','.join(fake.words(nb=5)) if HAS_FAKER else "urun, satis, online"
            video_code = fake.password(length=11, special_chars=False, upper_case=True, lower_case=True, digits=True) if HAS_FAKER else self._random_string(11)
            
            product = Product.objects.create(
                title=product_title,
                content=content,
                keywords=keywords,
                brim=random.choice(['Adet', 'Kg', 'Porsiyon', 'Dilim']),
                price=round(random.uniform(10.0, 500.0), 2),
                video=f"https://www.youtube.com/watch?v={video_code}"
            )

            # Assign categories, tags, and gallery
            product.categories.set(random.sample(categories, k=random.randint(1, 3)))
            product.tags.set(random.sample(tags, k=random.randint(1, 5)))
            product.gallery.set(random.sample(gallery_images, k=random.randint(1, 4)))

            # Generate and assign main product image
            img_name = f"product_{i}.jpg"
            main_image = self._generate_random_image(img_name)
            product.images.save(img_name, main_image)
            
            products.append(product)
        
        self.stdout.write(self.style.SUCCESS(f"{len(products)} products created."))
        self.stdout.write(self.style.SUCCESS("Fake data generation complete!"))

    def _generate_random_image(self, name):
        """Generates a random image file in memory."""
        width, height = 400, 400
        img = Image.new('RGB', (width, height))
        draw = ImageDraw.Draw(img)
        
        # Random background color
        bg_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        draw.rectangle([0, 0, width, height], fill=bg_color)
        
        # Draw some random shapes
        for _ in range(random.randint(3, 7)):
            shape_type = random.choice(['ellipse', 'rectangle'])
            
            # Generate coordinates and sort them to ensure x0 <= x1 and y0 <= y1
            x1 = random.randint(0, width)
            x2 = random.randint(0, width)
            y1 = random.randint(0, height)
            y2 = random.randint(0, height)
            
            xy = [
                (min(x1, x2), min(y1, y2)),
                (max(x1, x2), max(y1, y2))
            ]

            fill_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            
            if shape_type == 'ellipse':
                draw.ellipse(xy, fill=fill_color)
            else:
                draw.rectangle(xy, fill=fill_color)

        # Save image to a byte buffer
        from io import BytesIO
        buffer = BytesIO()
        img.save(buffer, format='JPEG') # Using JPEG as it is standard in PIL
        return ContentFile(buffer.getvalue(), name=name)

    def _random_string(self, length):
        return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
