from django_q.tasks import schedule
import os
import time
import shutil
import re

# Change this to your folder path
FOLDER_PATH = "/var/www/html/Data/schicatt/jobs"
TIMESTAMP_PATTERN = r".*_(\d+)$"  # Regex to extract timestamp


def cleanup_old_folders():
    now = time.time()
    if not os.path.exists(FOLDER_PATH):
        return

    for folder in os.listdir(FOLDER_PATH):
        folder_path = os.path.join(FOLDER_PATH, folder)
        match = re.match(TIMESTAMP_PATTERN, folder)

        if match and os.path.isdir(folder_path):
            folder_timestamp = int(match.group(1))  # Extract timestamp
            if now - folder_timestamp > 86400:  # 24 hours
                shutil.rmtree(folder_path)
                print(f"Deleted old folder: {folder}")


# Schedule cleanup to run every night at midnight
schedule('your_app.tasks.cleanup_old_folders',
         schedule_type='D', next_run='00:00')
