"""
Management command: python manage.py publish_scheduled

Publishes insight posts whose scheduled_at time has passed.
Run this on a cron every minute (or every 5 minutes):
  * * * * * /path/to/venv/bin/python /path/to/manage.py publish_scheduled >> /var/log/publish_scheduled.log 2>&1
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from apps.insights.models import Insight


class Command(BaseCommand):
    help = 'Auto-publishes Insight posts whose scheduled_at time has passed.'

    def handle(self, *args, **options):
        from apps.ftlink.models import JobRun
        now = timezone.now()
        self.stdout.write(f'Current time (UTC): {now}')

        all_scheduled = Insight.objects.filter(status=Insight.STATUS_SCHEDULED)
        self.stdout.write(f'Total scheduled posts: {all_scheduled.count()}')
        for p in all_scheduled:
            self.stdout.write(
                f'  - "{p.title}" | scheduled_at={p.scheduled_at} | '
                f'past={p.scheduled_at is not None and p.scheduled_at <= now}'
            )

        qs = all_scheduled.filter(scheduled_at__lte=now)
        count = qs.count()
        for post in qs:
            post.status = Insight.STATUS_PUBLISHED
            if not post.published_at:
                post.published_at = post.scheduled_at
            post.save(update_fields=['status', 'published_at', 'seo_score'])
            self.stdout.write(self.style.SUCCESS(f'  Published: "{post.title}"'))

        if count:
            self.stdout.write(self.style.SUCCESS(f'Done — published {count} post(s).'))
        else:
            self.stdout.write('No posts to publish.')
        JobRun.record('publish_scheduled', note=f'{count} published')
