"""Flip scheduled posts to published when their scheduled_at has passed.

Run on a cron (every minute):
    * * * * * cd /path/to/backend && /path/to/.venv/bin/python manage.py publish_due_posts >> /var/log/disseminations.log 2>&1
"""
from django.core.management.base import BaseCommand
from django.utils import timezone

from apps.disseminations.models import Post
from apps.disseminations.services import ensure_tracking_link


class Command(BaseCommand):
    help = "Publish scheduled posts whose scheduled_at <= now."

    def add_arguments(self, parser):
        parser.add_argument("--dry-run", action="store_true", help="Show what would be published without saving.")

    def handle(self, *args, **options):
        now = timezone.now()
        due = Post.objects.filter(status="scheduled", scheduled_at__lte=now).order_by("scheduled_at")
        count = due.count()
        if count == 0:
            self.stdout.write("No posts due.")
            return

        for post in due:
            self.stdout.write(f"Publishing [{post.id}] {post.title or post.body[:60]} → {post.scheduled_at:%Y-%m-%d %H:%M}")
            if not options["dry_run"]:
                # NOTE: actual platform delivery would go here (Channel-specific clients).
                # For now we just flip status; integrate adapters later.
                post.mark_published()
                ensure_tracking_link(post)

        verb = "Would publish" if options["dry_run"] else "Published"
        self.stdout.write(self.style.SUCCESS(f"{verb} {count} post(s)."))
