"""
Delete System Log entries older than the retention period
(settings.SYSTEM_LOG_RETENTION_DAYS, default 183 ≈ 6 months).

Run daily from cron, e.g. on cPanel:
    15 2 * * * cd /home/<user>/<app> && <venv>/bin/python manage.py prune_system_logs
"""

from datetime import timedelta

from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone

from system_logs.models import SystemLog


class Command(BaseCommand):
    help = "Delete System Log entries older than the retention period."

    def add_arguments(self, parser):
        parser.add_argument(
            "--days", type=int, default=getattr(settings, "SYSTEM_LOG_RETENTION_DAYS", 183),
            help="Keep this many days of entries (default: SYSTEM_LOG_RETENTION_DAYS).",
        )

    def handle(self, *args, days, **options):
        cutoff = timezone.now() - timedelta(days=days)
        total = 0
        # Batched so a large backlog doesn't lock the table for long.
        while True:
            ids = list(SystemLog.objects.filter(created_at__lt=cutoff).values_list("pk", flat=True)[:2000])
            if not ids:
                break
            deleted, _ = SystemLog.objects.filter(pk__in=ids).delete()
            total += deleted
        self.stdout.write(self.style.SUCCESS(f"Deleted {total} System Log entr{'y' if total == 1 else 'ies'} older than {days} days."))
