import random
import io
from django.core.management.base import BaseCommand
from django.core.files.base import ContentFile
from faker import Faker
from PIL import Image, ImageDraw
from portfolio.models import Portfolio, Category

class Command(BaseCommand):
    help = 'Creates fake portfolio items with images using existing categories'

    def generate_image(self, width, height, format='PNG'):
        """Generates a random image."""
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        image = Image.new('RGB', (width, height), color)
        draw = ImageDraw.Draw(image)
        
        # Draw some random shapes
        for _ in range(10):
            shape_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            x1 = random.randint(0, width)
            y1 = random.randint(0, height)
            x2 = random.randint(0, width)
            y2 = random.randint(0, height)
            # Ensure coordinates are in the correct order (x0, y0, x1, y1)
            draw.rectangle(
                [min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)], 
                fill=shape_color, 
                outline=None
            )

        img_io = io.BytesIO()
        image.save(img_io, format=format)
        return ContentFile(img_io.getvalue(), name=f'fake_image.{format.lower()}')

    def handle(self, *args, **options):
        fake = Faker()
        
        # Fetch existing categories
        categories = list(Category.objects.all())
        
        if not categories:
            self.stdout.write(self.style.WARNING('No categories found. Please create some categories first.'))
            return

        self.stdout.write(f'Found {len(categories)} categories. Creating portfolios...')
        
        for i in range(20):
            portfolio = Portfolio(
                url=fake.url(),
                is_active=True,
            )
            # Portfolio image: 640x481 (saving as PNG, model might convert to avif)
            image_content = self.generate_image(640, 481, 'PNG')
            portfolio.image.save(f'port_{i}.png', image_content, save=False)
            portfolio.save()
            
            # Assign random existing categories
            # Ensure we don't try to sample more categories than exist
            num_categories = min(len(categories), random.randint(1, 3))
            portfolio.categories.set(random.sample(categories, k=num_categories))

        self.stdout.write(self.style.SUCCESS('Successfully created fake portfolio items with images using existing categories.'))
