"""APScheduler periodic tasks for routermon."""
import logging

logger = logging.getLogger(__name__)

_BATCH = 500  # rows per delete batch to avoid long locks


def cleanup_old_queries():
    """Delete DnsQuery and WanEvent rows older than retention_days. Run periodically."""
    try:
        from datetime import timedelta
        from django.utils import timezone
        from .models import RouterMonSettings, DnsQuery, WanEvent

        settings = RouterMonSettings.get()
        if settings.retention_days <= 0:
            return

        cutoff = timezone.now() - timedelta(days=settings.retention_days)

        # Batch-delete DnsQuery rows
        total_dns = 0
        while True:
            ids = list(DnsQuery.objects.filter(timestamp__lt=cutoff).values_list('pk', flat=True)[:_BATCH])
            if not ids:
                break
            deleted, _ = DnsQuery.objects.filter(pk__in=ids).delete()
            total_dns += deleted

        # WAN events accumulate fast under port scans — use shorter retention (3 days max)
        wan_retention = min(settings.retention_days, 3)
        wan_cutoff = timezone.now() - timedelta(days=wan_retention)
        total_wan = 0
        while True:
            ids = list(WanEvent.objects.filter(timestamp__lt=wan_cutoff).values_list('pk', flat=True)[:_BATCH])
            if not ids:
                break
            deleted, _ = WanEvent.objects.filter(pk__in=ids).delete()
            total_wan += deleted

        if total_dns:
            logger.info('routermon: pruned %d old DNS query records (>%d days)', total_dns, settings.retention_days)
        if total_wan:
            logger.info('routermon: pruned %d old WAN event records (>%d days)', total_wan, wan_retention)
    except Exception as exc:
        logger.error('routermon: cleanup_old_queries error: %s', exc, exc_info=True)
