"""
Management command to seed ~3000 blog posts with realistic gym/fitness content.
Each post links to internal pages (/, /features, /pricing).
"""
import random
import uuid
from datetime import timedelta

from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.text import slugify

from apps.content.models import BlogPost, BlogCategory


# ── Categories ──────────────────────────────────────────────────────────────
CATEGORIES = [
    ("Gym Management", "gym-management", "Tips and strategies for running a successful gym business."),
    ("Fitness Tips", "fitness-tips", "Workout routines, exercise guides, and fitness advice."),
    ("Nutrition", "nutrition", "Healthy eating, meal prep, and diet plans for gym-goers."),
    ("Industry News", "industry-news", "Latest trends and news in the fitness industry across Africa."),
    ("Member Retention", "member-retention", "Strategies to keep your gym members engaged and loyal."),
    ("Technology", "technology", "How technology is transforming gym management and fitness."),
    ("Business Growth", "business-growth", "Scaling your gym, marketing strategies, and revenue growth."),
    ("Workout Programs", "workout-programs", "Structured workout plans for different fitness goals."),
    ("M-Pesa & Payments", "mpesa-payments", "Payment solutions and M-Pesa integration for gyms in Kenya."),
    ("Staff Management", "staff-management", "Hiring, training, and managing gym staff and trainers."),
    ("Class Scheduling", "class-scheduling", "Optimizing group fitness classes and scheduling."),
    ("Mental Health", "mental-health", "The connection between fitness and mental wellbeing."),
]

# ── Authors ─────────────────────────────────────────────────────────────────
AUTHORS = [
    "FitMtaani Team", "James Kariuki", "Grace Mwangi", "Tom Otieno",
    "Sarah Njoroge", "Diana Wambui", "Kevin Ouma", "Linda Achieng",
    "Peter Mutua", "Ann Wanjiku", "David Kiprop", "Mercy Chebet",
    "Brian Kimani", "Faith Kamau", "Alex Maina", "Joyce Nyambura",
]

# ── Internal links to weave into content ────────────────────────────────────
INTERNAL_LINKS = [
    '<a href="https://www.fitmtaani.com/">FitMtaani</a>',
    '<a href="https://www.fitmtaani.com/features">our features</a>',
    '<a href="https://www.fitmtaani.com/pricing">view our pricing plans</a>',
    '<a href="https://www.fitmtaani.com/">gym management software</a>',
    '<a href="https://www.fitmtaani.com/features">class scheduling tools</a>',
    '<a href="https://www.fitmtaani.com/features">M-Pesa payment integration</a>',
    '<a href="https://www.fitmtaani.com/pricing">affordable plans for every gym</a>',
    '<a href="https://www.fitmtaani.com/">the all-in-one fitness platform</a>',
]

# ── Title templates per category ────────────────────────────────────────────
TITLE_TEMPLATES = {
    "Gym Management": [
        "{n} Essential Tips for Running a Successful Gym in {city}",
        "How to Manage Your Gym Like a Pro in {year}",
        "The Complete Guide to Gym Operations in {country}",
        "Why Your Gym Needs a Management System in {year}",
        "{n} Common Gym Management Mistakes and How to Avoid Them",
        "How to Streamline Gym Administration with Software",
        "Building a Profitable Gym: Lessons from {city}",
        "The Ultimate Gym Owner's Checklist for {year}",
        "How to Reduce Operating Costs at Your Gym",
        "Modern Gym Management: What Every Owner Should Know",
        "{n} Ways to Improve Your Gym's Daily Operations",
        "How to Handle Gym Memberships Efficiently",
        "Digital Tools Every Gym Manager Needs in {year}",
        "Setting Up Your Gym for Success: A Step-by-Step Guide",
        "How to Automate Gym Billing and Save Hours Weekly",
    ],
    "Fitness Tips": [
        "{n} Best Exercises for Building Strength",
        "How to Create a Workout Routine That Works",
        "The Beginner's Guide to Weight Training",
        "{n} HIIT Workouts You Can Do Anywhere",
        "How to Improve Your Cardio Fitness in {n} Weeks",
        "The Science Behind Effective Warm-Up Routines",
        "Full-Body Workouts vs Split Routines: Which Is Better?",
        "How to Prevent Common Gym Injuries",
        "{n} Stretching Exercises for After Your Workout",
        "How to Track Your Fitness Progress Effectively",
        "The Best Exercises for Core Strength",
        "Training Tips for Runners Who Also Lift",
        "How to Break Through a Fitness Plateau",
        "{n} Compound Exercises for Maximum Results",
        "Recovery: Why Rest Days Are Essential",
    ],
    "Nutrition": [
        "{n} High-Protein Meals for Muscle Building",
        "Meal Prep Sunday: {n} Easy Recipes for the Week",
        "Understanding Macros: A Beginner's Guide",
        "The Best Pre-Workout Foods for Energy",
        "Post-Workout Nutrition: What to Eat After the Gym",
        "Hydration and Performance: How Much Water Do You Need?",
        "{n} Healthy Snacks for Gym-Goers",
        "The Truth About Protein Supplements",
        "How to Eat Clean on a Budget in {city}",
        "Intermittent Fasting and Exercise: What You Need to Know",
        "Meal Planning for Weight Loss: A Complete Guide",
        "{n} Smoothie Recipes for Recovery",
        "Carbs Are Not the Enemy: Smart Carb Choices for Athletes",
        "Eating for Endurance: Nutrition Tips for Long Workouts",
        "The Role of Vitamins and Minerals in Fitness",
    ],
    "Industry News": [
        "Kenya's Fitness Industry Grows {n}% in {year}",
        "New Trends Shaping Gyms Across {country}",
        "How COVID Changed the Fitness Landscape in Africa",
        "The Rise of Boutique Fitness Studios in {city}",
        "Corporate Wellness Programs on the Rise in {country}",
        "Gym Membership Trends in {city} for {year}",
        "The Future of Fitness Technology in Africa",
        "How African Gyms Are Embracing Digital Transformation",
        "{n} Fitness Trends to Watch in {year}",
        "The Growing Demand for Personal Trainers in {city}",
        "Fitness Industry Report: {country} {year}",
        "How Mobile Payments Are Changing Gym Businesses",
        "The Impact of Social Media on Gym Marketing",
        "Women in Fitness: Breaking Barriers in {country}",
        "Outdoor Fitness Movement Gains Momentum in {city}",
    ],
    "Member Retention": [
        "{n} Proven Strategies to Reduce Member Churn",
        "Why Members Leave and How to Stop It",
        "Building a Gym Community That Keeps Members Coming Back",
        "The Power of Personalization in Member Retention",
        "How to Use Data to Predict Member Churn",
        "Creating a Welcoming Gym Environment for New Members",
        "{n} Loyalty Program Ideas for Your Gym",
        "The Onboarding Process: Setting New Members Up for Success",
        "How to Re-Engage Inactive Gym Members",
        "Member Feedback: How to Collect and Act on It",
        "The Role of Group Classes in Member Retention",
        "How Gym Apps Improve Member Engagement",
        "{n} Ways to Show Members You Value Them",
        "Birthday Perks and Other Small Touches That Matter",
        "How to Handle Member Complaints Effectively",
    ],
    "Technology": [
        "How Gym Management Software Is Revolutionizing Fitness",
        "The Benefits of Cloud-Based Gym Systems",
        "Why Your Gym Needs a Mobile App",
        "Access Control Systems: QR Codes vs Biometrics",
        "How AI Is Being Used in Personal Training",
        "Wearable Tech and Gym Integration: What's Possible",
        "Automating Gym Processes: From Billing to Scheduling",
        "Digital Check-In Systems for Modern Gyms",
        "How to Choose the Right Gym Management Software",
        "The Role of Analytics in Running a Better Gym",
        "Virtual Fitness: Online Classes and Hybrid Models",
        "CRM Systems for Gyms: Why They Matter",
        "{n} Tech Tools Every Modern Gym Should Have",
        "How SMS and WhatsApp Reminders Reduce No-Shows",
        "Integration Guide: Connecting Your Gym's Tech Stack",
    ],
    "Business Growth": [
        "How to Market Your Gym on a Small Budget",
        "{n} Social Media Strategies for Gym Owners",
        "Growing Your Gym from {n} to {n2} Members",
        "How to Set the Right Pricing for Your Gym",
        "Partnerships That Can Grow Your Gym Business",
        "The Power of Referral Programs for Gyms",
        "How to Open a Second Gym Location",
        "Revenue Streams Beyond Memberships",
        "Creating a Strong Brand Identity for Your Gym",
        "How to Attract Corporate Clients to Your Gym",
        "Seasonal Marketing Campaigns for Gyms",
        "The January Rush: How to Convert Trial Members",
        "How to Increase Revenue Per Member",
        "Building an Online Presence for Your Gym",
        "Event Marketing: Hosting Fitness Events That Drive Growth",
    ],
    "Workout Programs": [
        "The {n}-Week Transformation Program",
        "Strength Training Program for Beginners",
        "Advanced Hypertrophy Training: A {n}-Day Split",
        "Running Program: From Couch to 5K",
        "Functional Fitness: A {n}-Week Plan",
        "Boxing Fitness: A {n}-Week Conditioning Program",
        "Yoga and Strength: A Balanced {n}-Week Program",
        "Circuit Training: {n} Routines for All Levels",
        "Powerlifting Program for Intermediate Lifters",
        "Bodyweight Training: No Equipment Needed",
        "CrossFit-Style WODs for Your Gym",
        "Senior Fitness: Safe and Effective Programs",
        "Athletic Performance: Speed and Agility Training",
        "Prenatal Fitness: Safe Exercises During Pregnancy",
        "Rehabilitation Exercises After Common Injuries",
    ],
    "M-Pesa & Payments": [
        "How to Accept M-Pesa Payments at Your Gym",
        "M-Pesa Integration: A Complete Guide for Gym Owners",
        "Why Mobile Payments Are the Future of Gym Billing",
        "Reducing Payment Delays with Automated M-Pesa Collection",
        "How to Set Up Recurring Payments via M-Pesa",
        "M-Pesa vs Card Payments: What Works Best for {city} Gyms",
        "Payment Analytics: Understanding Your Gym's Revenue Flow",
        "How to Handle Failed Payments Gracefully",
        "The Business Case for Going Cashless at Your Gym",
        "Integrating Multiple Payment Methods in Your Gym Software",
        "How Automated Billing Saves Gym Owners {n} Hours Monthly",
        "Payment Reminders: Reducing Late Payments by {n}%",
        "Financial Reporting Made Easy with Integrated Payments",
        "How to Offer Flexible Payment Plans to Members",
        "Secure Payment Processing: Protecting Member Data",
    ],
    "Staff Management": [
        "How to Hire the Right Personal Trainers",
        "Creating Effective Staff Schedules for Your Gym",
        "Training Your Gym Staff for Excellence",
        "{n} Qualities to Look for in Gym Employees",
        "How to Reduce Staff Turnover at Your Gym",
        "Performance Reviews for Gym Staff: A Guide",
        "Building a Positive Workplace Culture at Your Gym",
        "How to Manage Freelance Trainers and Instructors",
        "Staff Certification Requirements in {country}",
        "Communication Tools for Gym Teams",
        "How to Delegate Effectively as a Gym Owner",
        "The Role of Front Desk Staff in Member Experience",
        "Incentive Programs for High-Performing Trainers",
        "Managing Part-Time vs Full-Time Gym Staff",
        "How to Handle Staff Conflicts Professionally",
    ],
    "Class Scheduling": [
        "How to Build an Effective Class Schedule",
        "Optimizing Class Times for Maximum Attendance",
        "The Most Popular Group Fitness Classes in {year}",
        "How to Launch a New Class at Your Gym",
        "Managing Class Capacity and Waitlists",
        "How Online Booking Increases Class Attendance",
        "Hybrid Classes: In-Person and Virtual Combined",
        "How to Set the Right Duration for Group Classes",
        "Seasonal Class Schedule Adjustments",
        "Instructor Scheduling: Balancing Availability and Demand",
        "How to Handle Class Cancellations Smoothly",
        "The Benefits of a Consistent Weekly Schedule",
        "Special Events and Workshop Scheduling",
        "How to Price Drop-In Classes vs Memberships",
        "Class Feedback: Improving Based on Member Input",
    ],
    "Mental Health": [
        "The Connection Between Exercise and Mental Health",
        "How Gym Communities Support Mental Wellbeing",
        "Exercise as Therapy: What the Research Says",
        "Mindfulness and Movement: Combining Meditation with Fitness",
        "How to Create a Stress-Free Gym Environment",
        "The Role of Personal Trainers in Mental Health Support",
        "Exercise for Anxiety: The Best Workouts for Calm",
        "How Regular Fitness Reduces Depression Symptoms",
        "Building Confidence Through Fitness",
        "The Psychological Benefits of Group Exercise",
        "How to Motivate Members Who Struggle with Consistency",
        "Sleep and Exercise: The Recovery Connection",
        "Burnout Prevention for Gym Owners and Staff",
        "Creating Inclusive Spaces for All Body Types",
        "How Fitness Goals Improve Overall Life Satisfaction",
    ],
}

# ── Content paragraph templates ─────────────────────────────────────────────
PARAGRAPHS = {
    "intro": [
        "Running a gym in {country} comes with unique challenges and opportunities. Whether you're managing a small studio in {city} or a multi-location fitness chain, having the right approach is crucial for success.",
        "The fitness industry in {country} is booming, and gym owners need to stay ahead of the curve. In this article, we explore practical strategies that can make a real difference in your business.",
        "As more people in {city} and across {country} embrace healthier lifestyles, the demand for quality fitness facilities continues to grow. Here's what you need to know to capitalize on this trend.",
        "Fitness isn't just about workouts — it's about building a sustainable business that serves your community. Let's dive into the strategies that successful gym owners use.",
        "The modern gym landscape is evolving rapidly. From digital check-ins to mobile payments, technology is reshaping how fitness businesses operate in {country}.",
        "Whether you're a seasoned gym owner or just starting out, there are always new things to learn. This guide covers the essentials you need to know in {year}.",
    ],
    "body": [
        "One of the most important aspects of gym management is understanding your members. By tracking attendance patterns and preferences, you can tailor your offerings to match demand. Tools like {link} make this process seamless, giving you real-time insights into how your gym is performing.",
        "Payment processing has traditionally been a pain point for gyms in {country}. With M-Pesa integration, you can automate collections, reduce cash handling, and give members a convenient way to pay. {link} offers built-in payment processing that saves you time and reduces errors.",
        "Class scheduling can make or break member satisfaction. When classes are well-organized and easy to book, members are more likely to attend regularly. Consider using {link} to streamline your scheduling and allow online bookings.",
        "Member retention is arguably more important than acquisition. It costs significantly more to attract a new member than to keep an existing one. Focus on creating a welcoming environment, offering variety in your programming, and maintaining regular communication with your members.",
        "Staff management is critical for delivering a great member experience. Your trainers and front desk staff are the face of your business. Invest in their development and provide them with the tools they need. {link} includes staff management features that simplify scheduling and performance tracking.",
        "Financial management goes beyond just collecting dues. Understanding your revenue streams, tracking expenses, and monitoring profitability are essential. With {link}, you get comprehensive financial reporting that helps you make informed decisions.",
        "Marketing doesn't have to be expensive. Social media, referral programs, and local partnerships can be highly effective for gyms. The key is consistency and authenticity — share real stories from your gym community.",
        "Data-driven decision making is no longer optional for gym businesses. Track your key metrics — member count, revenue per member, attendance rates, and churn percentage. Use these numbers to guide your strategy. {link} provides analytics dashboards that make this easy.",
        "The gym experience begins before a member even walks through the door. From your website to your check-in process, every touchpoint matters. Streamline these with modern software to create a professional impression.",
        "Group fitness continues to be one of the strongest drivers of member engagement. Whether it's spinning, yoga, or HIIT, offering a diverse class schedule keeps members interested and committed to their fitness journey.",
    ],
    "conclusion": [
        "The fitness industry in {country} is full of potential. By adopting modern tools and strategies, gym owners can build thriving businesses that make a real impact on their communities. Ready to get started? Check out {link} to see how we can help.",
        "Success in the gym business isn't just about having great equipment — it's about creating an experience that keeps members coming back. With the right tools and mindset, you can build something truly special. Explore {link} today.",
        "As we look ahead, the gyms that embrace technology and focus on member experience will be the ones that thrive. Don't get left behind — {link} and start transforming your gym business today.",
        "Every gym is different, but the fundamentals of good management are universal. Stay focused on your members, invest in your team, and leverage technology to work smarter. Learn more about how {link} can support your growth.",
        "The journey of building a successful gym is ongoing. Stay curious, keep learning, and don't be afraid to try new approaches. For affordable tools that grow with your business, {link}.",
    ],
    "tips": [
        "Always respond to member feedback within 24 hours — it shows you care about their experience.",
        "Track your busiest hours and schedule your best staff during peak times.",
        "Offer a free trial week for potential members — it's one of the most effective conversion tools.",
        "Keep your equipment well-maintained. Nothing drives members away faster than broken machines.",
        "Create a clean, welcoming environment. Cleanliness is one of the top factors in gym selection.",
        "Use social proof — display testimonials and success stories prominently in your gym.",
        "Set up automated payment reminders to reduce late payments and awkward conversations.",
        "Host monthly community events to build a sense of belonging among your members.",
        "Invest in good lighting and music — the atmosphere matters more than most owners realize.",
        "Train your staff to greet every member by name. Personal connection drives retention.",
        "Offer flexible membership options — not everyone wants a 12-month commitment.",
        "Partner with local businesses for cross-promotions that benefit both parties.",
        "Use check-in data to identify at-risk members and reach out before they cancel.",
        "Keep your class schedule consistent — members plan their weeks around your timetable.",
        "Document your processes so any staff member can handle any situation.",
    ],
}

CITIES = [
    "Nairobi", "Mombasa", "Kisumu", "Nakuru", "Eldoret", "Thika",
    "Malindi", "Kitale", "Garissa", "Nyeri", "Machakos", "Nanyuki",
    "Lamu", "Naivasha", "Kericho", "Embu", "Meru", "Ruiru",
    "Kampala", "Dar es Salaam", "Kigali", "Addis Ababa", "Lagos",
    "Accra", "Johannesburg", "Cape Town", "Lusaka", "Harare",
]

COUNTRIES = [
    "Kenya", "East Africa", "Africa", "Uganda", "Tanzania",
    "Rwanda", "Nigeria", "South Africa", "Ghana",
]

TAGS_POOL = [
    "gym-management", "fitness", "health", "wellness", "workout",
    "nutrition", "weight-loss", "muscle-building", "cardio", "strength",
    "mpesa", "payments", "billing", "scheduling", "classes",
    "retention", "marketing", "growth", "technology", "software",
    "personal-training", "group-fitness", "yoga", "hiit", "crossfit",
    "staff", "hiring", "trainers", "kenya", "africa",
    "analytics", "reports", "members", "engagement", "community",
    "weight-training", "bodybuilding", "running", "stretching", "recovery",
    "meal-prep", "protein", "supplements", "hydration", "diet",
    "mental-health", "motivation", "consistency", "goals", "transformation",
]


def _rand_link():
    return random.choice(INTERNAL_LINKS)


def _build_content(category_name):
    """Build a realistic HTML blog post body."""
    city = random.choice(CITIES)
    country = random.choice(COUNTRIES)
    year = random.choice([2024, 2025, 2026])
    ctx = {"city": city, "country": country, "year": str(year), "link": _rand_link()}

    sections = []

    # Intro
    intro = random.choice(PARAGRAPHS["intro"]).format(**ctx)
    sections.append(f"<p>{intro}</p>")

    # 2-4 body paragraphs with subheadings
    subheadings = [
        "Key Strategies", "Understanding the Landscape", "Best Practices",
        "What the Data Shows", "Practical Steps", "Getting Started",
        "Building Momentum", "Long-Term Success", "The Bottom Line",
        "Expert Insights", "Real-World Examples", "Making It Work",
    ]
    random.shuffle(subheadings)
    body_count = random.randint(2, 4)
    body_paragraphs = random.sample(PARAGRAPHS["body"], min(body_count, len(PARAGRAPHS["body"])))

    for i, para in enumerate(body_paragraphs):
        ctx["link"] = _rand_link()
        sections.append(f"<h2>{subheadings[i]}</h2>")
        sections.append(f"<p>{para.format(**ctx)}</p>")

    # Optional tips list
    if random.random() > 0.4:
        tips = random.sample(PARAGRAPHS["tips"], random.randint(3, 6))
        sections.append("<h2>Quick Tips</h2>")
        sections.append("<ul>")
        for tip in tips:
            sections.append(f"<li>{tip}</li>")
        sections.append("</ul>")

    # Optional blockquote
    if random.random() > 0.5:
        quotes = [
            "The best time to start was yesterday. The second best time is now.",
            "Fitness is not about being better than someone else. It's about being better than you used to be.",
            "Success in the gym business is built one member at a time.",
            "Technology doesn't replace the human touch — it enhances it.",
            "Your gym is only as good as the experience you deliver.",
        ]
        sections.append(f"<blockquote><p>{random.choice(quotes)}</p></blockquote>")

    # Conclusion
    ctx["link"] = _rand_link()
    conclusion = random.choice(PARAGRAPHS["conclusion"]).format(**ctx)
    sections.append(f"<h2>Wrapping Up</h2>")
    sections.append(f"<p>{conclusion}</p>")

    return "\n\n".join(sections)


def _build_excerpt(title, category_name):
    """Build a short excerpt/summary for the post."""
    templates = [
        f"Discover practical insights on {category_name.lower()} for gym owners. {title.split(':')[0]} — everything you need to know.",
        f"A deep dive into {category_name.lower()} for fitness businesses in Africa. Learn actionable strategies you can implement today.",
        f"Explore key strategies for {category_name.lower()} that can help your gym grow. Practical tips backed by real experience.",
        f"Essential reading for gym owners: {category_name.lower()} insights and strategies for building a thriving fitness business.",
        f"Get ahead with our guide to {category_name.lower()}. Packed with practical advice for gym owners in Kenya and beyond.",
    ]
    return random.choice(templates)


class Command(BaseCommand):
    help = "Seed approximately 3000 blog posts with realistic gym/fitness content."

    def add_arguments(self, parser):
        parser.add_argument(
            "--count", type=int, default=3000,
            help="Number of blog posts to create (default: 3000)",
        )
        parser.add_argument(
            "--clear", action="store_true",
            help="Delete all existing blog posts and categories before seeding.",
        )

    def handle(self, *args, **options):
        count = options["count"]

        if options["clear"]:
            deleted_posts = BlogPost.objects.all().delete()
            deleted_cats = BlogCategory.objects.all().delete()
            self.stdout.write(f"Cleared {deleted_posts[0]} posts, {deleted_cats[0]} categories.")

        # Create categories
        cat_objects = {}
        for name, slug, desc in CATEGORIES:
            cat, _ = BlogCategory.objects.get_or_create(
                slug=slug,
                defaults={"name": name, "description": desc, "is_active": True},
            )
            cat_objects[name] = cat

        self.stdout.write(f"Created/ensured {len(cat_objects)} categories.")

        # Generate posts
        cat_names = list(cat_objects.keys())
        now = timezone.now()
        created = 0
        batch = []

        for i in range(count):
            cat_name = random.choice(cat_names)
            category = cat_objects[cat_name]
            templates = TITLE_TEMPLATES.get(cat_name, TITLE_TEMPLATES["Gym Management"])
            title_tpl = random.choice(templates)

            n = random.randint(3, 15)
            n2 = n * random.randint(5, 20)
            city = random.choice(CITIES)
            country = random.choice(COUNTRIES)
            year = random.choice([2024, 2025, 2026])

            title = title_tpl.format(n=n, n2=n2, city=city, country=country, year=year)

            # Ensure unique slug
            base_slug = slugify(title)[:200]
            slug = f"{base_slug}-{uuid.uuid4().hex[:6]}"

            content = _build_content(cat_name)
            excerpt = _build_excerpt(title, cat_name)
            author_name = random.choice(AUTHORS)

            # Random published date within last 2 years
            days_ago = random.randint(0, 730)
            published_at = now - timedelta(days=days_ago, hours=random.randint(0, 23))

            tags = ",".join(random.sample(TAGS_POOL, random.randint(3, 7)))

            batch.append(BlogPost(
                title=title,
                slug=slug,
                content=content,
                excerpt=excerpt,
                category=category,
                tags=tags,
                status="published",
                published_at=published_at,
                is_featured=random.random() < 0.02,  # ~2% featured
                views_count=random.randint(0, 5000),
                meta_title=title[:255],
                meta_description=excerpt[:300],
            ))

            if len(batch) >= 500:
                BlogPost.objects.bulk_create(batch, ignore_conflicts=True)
                created += len(batch)
                self.stdout.write(f"  ...created {created}/{count}")
                batch = []

        if batch:
            BlogPost.objects.bulk_create(batch, ignore_conflicts=True)
            created += len(batch)

        self.stdout.write(self.style.SUCCESS(
            f"Successfully seeded {created} blog posts across {len(cat_objects)} categories."
        ))
