import os
import time
from django.conf import settings
from celery import shared_task


@shared_task(
        bind=True,
        max_retries=3,
        name='apps.calls.tasks.cleanup_old_recordings_task'
    )
def cleanup_old_recordings_task(self):
    """
    Delete call recordings older than 30 days.
    """
    try:
        folder = os.path.join(settings.MEDIA_ROOT, "call_recordings")
        cutoff = time.time() - (30 * 86400)
        
        if os.path.exists(folder):
            for filename in os.listdir(folder):
                filepath = os.path.join(folder, filename)
                if os.path.isfile(filepath) and os.path.getmtime(filepath) < cutoff:
                    os.remove(filepath)
    except Exception as exc:
        raise