"""
Celery tasks for automatic status cleanup
Requires: celery, redis, django-celery-beat

Installation:
pip install celery redis django-celery-beat

Setup in settings.py:
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_BEAT_SCHEDULE = {
    'cleanup-expired-status': {
        'task': 'status.tasks.cleanup_expired_status',
        'schedule': crontab(minute='*/5'),  # Every 5 minutes
    },
}

Run celery worker:
celery -A your_project_name worker -l info

Run celery beat:
celery -A your_project_name beat -l info
"""

from celery import shared_task
from django.utils import timezone
from .models import Status
import logging

logger = logging.getLogger(__name__)


@shared_task
def cleanup_expired_status():
    """
    Delete all expired status
    Runs every 5 minutes via Celery Beat
    """
    try:
        # Get all expired status
        expired_status = Status.objects.filter(
            expires_at__lte=timezone.now()
        )
        
        count = expired_status.count()
        
        if count > 0:
            # Delete media files first
            for status_obj in expired_status:
                if status_obj.media:
                    try:
                        status_obj.media.delete(save=False)
                    except Exception as e:
                        logger.error(f"Error deleting media: {e}")
            
            # Delete status records
            expired_status.delete()
            
            logger.info(f"Deleted {count} expired status")
            return f"Successfully deleted {count} expired status"
        else:
            logger.info("No expired status to delete")
            return "No expired status found"
    
    except Exception as e:
        logger.error(f"Error in cleanup_expired_status: {e}")
        return f"Error: {str(e)}"


@shared_task
def delete_old_status_views():
    """
    Delete status views older than 7 days (optional)
    Keeps database clean
    """
    try:
        from datetime import timedelta
        from .models import StatusView
        
        cutoff_date = timezone.now() - timedelta(days=7)
        old_views = StatusView.objects.filter(viewed_at__lt=cutoff_date)
        
        count = old_views.count()
        old_views.delete()
        
        logger.info(f"Deleted {count} old status views")
        return f"Successfully deleted {count} old status views"
    
    except Exception as e:
        logger.error(f"Error in delete_old_status_views: {e}")
        return f"Error: {str(e)}"