import random
import requests
from django.utils import timezone
from django.core.files.base import ContentFile
from faker import Faker
from .models import Blog
from accounts.models import CustomUser

fake = Faker()

def create_dummy_blogs(n=20):
    users = list(CustomUser.objects.filter(is_active=True))
    if not users:
        print("No active users found. Please create users first.")
        return

    for i in range(n):
        title = fake.sentence(nb_words=6)
        content = fake.paragraph(nb_sentences=10)
        meta_title = title
        meta_description = fake.text(max_nb_chars=180)
        meta_keywords = ', '.join(fake.words(nb=5))

        # Download a random image
        image_url = "https://source.unsplash.com/600x400/?realestate,home,apartment"
        response = requests.get(image_url)

        blog = Blog(
            title=title,
            content=content,
            meta_title=meta_title,
            meta_description=meta_description,
            meta_keywords=meta_keywords,
            published_on=timezone.now(),
            published_by=random.choice(users),
            is_draft=False,
            is_active=True,
        )

        if response.status_code == 200:
            image_name = f"blog_image_{i}.jpg"
            blog.cover_image.save(image_name, ContentFile(response.content), save=False)

        blog.save()
        print(f"Created blog: {title}")
