"""
``prune_audit_runs`` management command.

Manual entry point for retention pruning.
"""

from __future__ import annotations

import logging
from datetime import timedelta
from typing import TYPE_CHECKING

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

from ...app_settings import AA_DISCORD_AUDIT_RUN_RETENTION_DAYS
from ...models import AuditRun
from ...persistence import log_pending_purges

if TYPE_CHECKING:
    import argparse

logger = logging.getLogger(f"extensions.{__name__}")


class Command(BaseCommand):
    help = (
        "Delete AuditRun rows older than AA_DISCORD_AUDIT_RUN_RETENTION_DAYS. "
        "AuditFinding rows cascade. InitialAuditAcknowledgement is never "
        "pruned regardless of age."
    )

    def add_arguments(self, parser: argparse.ArgumentParser) -> None:
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Report the count without deleting.",
        )

    def handle(self, *args, **options) -> None:
        # 0 is the indefinite-retention sentinel; opt-out gated by
        # AA_DISCORD_AUDIT_RETENTION_OPT_OUT_ACKNOWLEDGED at startup.
        if AA_DISCORD_AUDIT_RUN_RETENTION_DAYS == 0:
            self.stdout.write(
                self.style.WARNING(
                    "AA_DISCORD_AUDIT_RUN_RETENTION_DAYS=0: retention is "
                    "explicitly opted out "
                    "(RETENTION_OPT_OUT_ACKNOWLEDGED=True). "
                    "Nothing to prune."
                )
            )
            return

        cutoff = timezone.now() - timedelta(
            days=AA_DISCORD_AUDIT_RUN_RETENTION_DAYS
        )
        queryset = AuditRun.objects.filter(started_at__lt=cutoff)
        count = queryset.count()

        if options["dry_run"]:
            self.stdout.write(
                self.style.NOTICE(
                    f"--dry-run: {count} AuditRun rows older than "
                    f"{cutoff.isoformat()} would be deleted."
                )
            )
            return

        # PENDING tombstone preamble — symmetric with the Celery task.
        log_pending_purges(queryset)

        deleted, breakdown = queryset.delete()
        self.stdout.write(
            self.style.SUCCESS(f"Pruned {deleted} rows ({breakdown})")
        )
