from __future__ import annotations

import time

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

from core.models import ConversationEvent


class Command(BaseCommand):
    help = (
        "Prune high-growth behavioral ORM shadow tables after data has been "
        "persisted to Manticore."
    )

    def add_arguments(self, parser):
        parser.add_argument("--user-id", default="")
        parser.add_argument("--dry-run", action="store_true", default=False)
        parser.add_argument("--conversation-days", type=int)
        parser.add_argument(
            "--tables",
            default="conversation_events",
            help="Comma separated subset of: conversation_events",
        )

    def _cutoff_ms(self, days: int) -> int:
        return int(time.time() * 1000) - (max(1, int(days)) * 24 * 60 * 60 * 1000)

    def handle(self, *args, **options):
        user_id = str(options.get("user_id") or "").strip()
        dry_run = bool(options.get("dry_run"))
        conversation_days = int(
            options.get("conversation_days")
            or getattr(settings, "CONVERSATION_EVENT_RETENTION_DAYS", 90)
            or 90
        )
        selected_tables = {
            str(item or "").strip().lower()
            for item in str(options.get("tables") or "").split(",")
            if str(item or "").strip()
        }

        deleted = {
            "conversation_events": 0,
        }

        if "conversation_events" in selected_tables:
            qs = ConversationEvent.objects.filter(
                ts__lt=self._cutoff_ms(conversation_days)
            )
            if user_id:
                qs = qs.filter(user_id=user_id)
            deleted["conversation_events"] = int(qs.count() if dry_run else qs.delete()[0])

        self.stdout.write(
            "prune-behavioral-orm-data "
            f"dry_run={dry_run} "
            f"user_id={user_id or '-'} "
            f"conversation_days={conversation_days} "
            f"deleted={deleted}"
        )
