import random
import requests
from django.core.management.base import BaseCommand
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
from django.contrib.auth import get_user_model
from faker import Faker
from blog.models import Category, Tags, Post

User = get_user_model()

class Command(BaseCommand):
    help = 'Seeds the database with fake data for blog app'

    def handle(self, *args, **kwargs):
        self.stdout.write('Seeding data...')
        fake = Faker()

        # Ensure a user exists
        user, created = User.objects.get_or_create(
            email='admin@example.com',
            defaults={'first_name': 'Admin', 'is_staff': True, 'is_superuser': True}
        )
        if created:
            user.set_password('admin')
            user.save()
            self.stdout.write(self.style.SUCCESS(f'Created user: {user.email}'))
        else:
             self.stdout.write(self.style.SUCCESS(f'Using existing user: {user.email}'))

        # Create Categories
        categories_data = {
            'Teknoloji': ['Yazılım', 'Donanım', 'Yapay Zeka'],
            'Yaşam': ['Seyahat', 'Sağlık', 'Yemek'],
            'Spor': ['Futbol', 'Basketbol', 'Voleybol'],
            'Eğlence': ['Sinema', 'Müzik', 'Oyun'],
        }

        created_categories = []
        for parent_name, children in categories_data.items():
            parent, _ = Category.objects.get_or_create(
                title=parent_name,
                defaults={
                    'keywords': f'{parent_name}, blog, kategori',
                    'description': f'{parent_name} kategorisi açıklaması',
                    'is_active': True
                }
            )
            created_categories.append(parent)
            self.stdout.write(f'Created/Found Category: {parent.title}')

            for child_name in children:
                child, _ = Category.objects.get_or_create(
                    title=child_name,
                    parent=parent,
                    defaults={
                        'keywords': f'{child_name}, {parent_name}, blog',
                        'description': f'{child_name} alt kategorisi açıklaması',
                        'is_active': True
                    }
                )
                created_categories.append(child)
                self.stdout.write(f'  - Created/Found Subcategory: {child.title}')

        # Create Tags
        tags_list = ['Python', 'Django', 'Web Development', 'Coding', 'Tech', 'News', 'Tutorial', 'Tips', 'Health', 'Travel']
        created_tags = []
        for tag_name in tags_list:
            tag, _ = Tags.objects.get_or_create(
                tag=tag_name,
                 defaults={'is_active': True}
            )
            created_tags.append(tag)
            self.stdout.write(f'Created/Found Tag: {tag.tag}')

        # Create Posts
        self.stdout.write('Creating posts...')
        for i in range(30): # Create 30 posts
            title = fake.sentence(nb_words=6).replace('.', '')
            content = f"<p>{fake.paragraph(nb_sentences=10)}</p><p>{fake.paragraph(nb_sentences=5)}</p>"
            
            post, created = Post.objects.get_or_create(
                title=title,
                defaults={
                    'user': user,
                    'content': content,
                    'keywords': ', '.join(fake.words(nb=5)),
                    'is_active': True,
                    'is_front': True,
                    'video': 'none'
                }
            )
            
            if created:
                # Add Categories
                post_cats = random.sample(created_categories, k=random.randint(1, 3))
                post.categories.set(post_cats)
                
                # Add Tags
                post_tags = random.sample(created_tags, k=random.randint(1, 4))
                post.tags.set(post_tags)

                # Fetch and save image
                image_url = f"https://picsum.photos/800/600?random={i}"
                try:
                    response = requests.get(image_url, timeout=10)
                    if response.status_code == 200:
                        img_temp = NamedTemporaryFile(delete=True)
                        img_temp.write(response.content)
                        img_temp.flush()
                        post.image.save(f"post_{i}.jpg", File(img_temp), save=True)
                        self.stdout.write(f'  - Downloaded image for post: {title}')
                except Exception as e:
                    self.stdout.write(self.style.WARNING(f'  - Could not download image for post {title}: {e}'))
                
                post.save()
                self.stdout.write(self.style.SUCCESS(f'Created Post: {post.title}'))
            else:
                self.stdout.write(f'Post already exists: {post.title}')

        self.stdout.write(self.style.SUCCESS('Data seeding completed successfully!'))
