# management/commands/clean_temp_images.py
from django.core.management.base import BaseCommand
from django.utils import timezone
from referencias.models import ReferenciaImagen
import os

class Command(BaseCommand):
    help = 'Elimina imágenes temporales no asignadas después de 24 horas'

    def handle(self, *args, **options):
        # Eliminar imágenes sin referencia y con clave temporal antigua
        limite = timezone.now() - timezone.timedelta(hours=24)
        imagenes = ReferenciaImagen.objects.filter(
            referencia__isnull=True,
            temporary_key__isnull=False,
            created_at__lt=limite
        )

        total = imagenes.count()
        for imagen in imagenes:
            try:
                if os.path.exists(imagen.imagen.path):
                    os.remove(imagen.imagen.path)
                imagen.delete()
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'Error eliminando imagen {imagen.id}: {str(e)}'))

        self.stdout.write(self.style.SUCCESS(f'Eliminadas {total} imágenes temporales'))