import os
import random
import string
import requests
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.core.files.base import ContentFile
from blog.models import Post, Category, Tags

try:
    from faker import Faker
    fake = Faker()
    HAS_FAKER = True
except ImportError:
    HAS_FAKER = False

class Command(BaseCommand):
    help = 'Creates 300 fake posts with random images'

    def handle(self, *args, **kwargs):
        User = get_user_model()
        # Prefer an existing staff user, otherwise any existing user, otherwise create a fallback user
        user = User.objects.filter(is_staff=True).first() or User.objects.first()
        if not user:
            self.stdout.write('Hiç kullanıcı bulunamadı, `fakeuser` oluşturuluyor...')
            user = User.objects.create(username='fakeuser', email='fake@example.com')
            user.set_unusable_password()
            user.save()
        categories = list(Category.objects.all())
        if not categories:
            self.stdout.write(self.style.ERROR('Lütfen önce en az bir kategori oluşturun!'))
            return

        tags = list(Tags.objects.all())
        if not tags:
            self.stdout.write('Tag bulunamadı, oluşturuluyor...')
            for i in range(5):
                tag_name = self.get_random_string(8) if not HAS_FAKER else fake.word()
                Tags.objects.create(tag=tag_name)
            tags = list(Tags.objects.all())

        self.stdout.write('300 adet fake post oluşturuluyor...')

        for i in range(300):
            if HAS_FAKER:
                title = fake.sentence(nb_words=6).replace('.', '')
                content = '\n\n'.join(fake.paragraphs(nb=5))
                keywords = ", ".join(fake.words(nb=5))
            else:
                title = self.get_random_string(30)
                content = self.get_random_string(500)
                keywords = self.get_random_string(20)

            post = Post(
                user=user,
                title=title,
                content=content,
                keywords=keywords,
                video='none',
                is_active=True,
                is_front=True
            )
            post.save()
            
            # ManyToMany ilişkileri
            post.categories.add(random.choice(categories))
            post.tags.add(random.choice(tags))

            # Resim ekle
            try:
                # Picsum'dan rastgele resim (800x600)
                img_url = f"https://picsum.photos/seed/{random.randint(1, 10000)}/800/600"
                response = requests.get(img_url, timeout=10)
                if response.status_code == 200:
                    file_name = f"fake_post_{i}_{random.randint(1000,9999)}.jpg"
                    post.image.save(file_name, ContentFile(response.content), save=True)
                    self.stdout.write(f'Post {i+1}/300 oluşturuldu: {title} (Resimli)')
                else:
                    self.stdout.write(f'Post {i+1}/300 oluşturuldu: {title} (Resimsiz - İndirme hatası)')
            except Exception as e:
                self.stdout.write(f'Post {i+1}/300 oluşturuldu: {title} (Resimsiz - Hata: {str(e)})')

    def get_random_string(self, length):
        letters = string.ascii_letters + string.digits + ' '
        return ''.join(random.choice(letters) for i in range(length))
