"""
Manual cleanup command for expired status
Place in: status/management/commands/cleanup_expired_status.py

Usage:
python manage.py cleanup_expired_status
"""

from django.core.management.base import BaseCommand
from django.utils import timezone
from status.models import Status
import logging

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Delete all expired status'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be deleted without actually deleting',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        
        # Get all expired status
        expired_status = Status.objects.filter(
            expires_at__lte=timezone.now()
        )
        
        count = expired_status.count()
        
        if count == 0:
            self.stdout.write(
                self.style.SUCCESS('No expired status found')
            )
            return
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING(
                    f'DRY RUN: Would delete {count} expired status'
                )
            )
            for status in expired_status[:10]:  # Show first 10
                self.stdout.write(
                    f'  - Status {status.id} by {status.user.username} '
                    f'(expired {status.expires_at})'
                )
            if count > 10:
                self.stdout.write(f'  ... and {count - 10} more')
            return
        
        # Delete media files first
        media_count = 0
        for status_obj in expired_status:
            if status_obj.media:
                try:
                    status_obj.media.delete(save=False)
                    media_count += 1
                except Exception as e:
                    logger.error(f"Error deleting media: {e}")
        
        # Delete status records
        expired_status.delete()
        
        self.stdout.write(
            self.style.SUCCESS(
                f'Successfully deleted {count} expired status '
                f'({media_count} with media files)'
            )
        )