"""
Generate and publish blog posts due today (scheduled_date <= today).

Usage:
  python manage.py publish_due_blog_articles
  python manage.py publish_due_blog_articles --sync
"""

import json

from django.core.management.base import BaseCommand

from blogs.services.automation_service import BlogAutomationService


class Command(BaseCommand):
    help = "Generate and publish articles whose scheduled publish date has arrived."

    def add_arguments(self, parser):
        parser.add_argument(
            "--sync",
            action="store_true",
            help="Block until each due article is generated and published.",
        )

    def handle(self, *args, **options):
        try:
            result = BlogAutomationService.publish_due_articles(
                sync=options.get("sync")
            )
        except Exception as exc:
            self.stderr.write(self.style.ERROR(str(exc)))
            raise SystemExit(1) from exc

        self.stdout.write(json.dumps(result, indent=2, default=str))
