"""
Management command to set up periodic Celery tasks for quota management.

Run this after deployment:
    python manage.py setup_quota_tasks
"""

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = 'Set up periodic Celery Beat tasks for quota management'

    def handle(self, *args, **options):
        from django_celery_beat.models import PeriodicTask, CrontabSchedule

        self.stdout.write('Setting up quota management periodic tasks...')

        # Create crontab schedules
        # Daily at 2 AM - check all tenants for quota overages
        schedule_2am, _ = CrontabSchedule.objects.get_or_create(
            minute='0',
            hour='2',
            day_of_week='*',
            day_of_month='*',
            month_of_year='*',
        )

        # Daily at 3 AM - process expired grace periods
        schedule_3am, _ = CrontabSchedule.objects.get_or_create(
            minute='0',
            hour='3',
            day_of_week='*',
            day_of_month='*',
            month_of_year='*',
        )

        # Daily at 8 AM - send reminder emails
        schedule_8am, _ = CrontabSchedule.objects.get_or_create(
            minute='0',
            hour='8',
            day_of_week='*',
            day_of_month='*',
            month_of_year='*',
        )

        # Weekly on Sunday at 4 AM - cleanup old overage records
        schedule_sunday_4am, _ = CrontabSchedule.objects.get_or_create(
            minute='0',
            hour='4',
            day_of_week='0',  # Sunday
            day_of_month='*',
            month_of_year='*',
        )

        # Create periodic tasks
        tasks = [
            {
                'name': 'quota-check-all-tenants',
                'task': 'core.tasks.check_all_tenant_quotas',
                'crontab': schedule_2am,
                'description': 'Check all tenants for quota overages (runs daily at 2 AM)',
            },
            {
                'name': 'quota-process-expired',
                'task': 'core.tasks.process_expired_quotas',
                'crontab': schedule_3am,
                'description': 'Auto-archive resources for expired grace periods (runs daily at 3 AM)',
            },
            {
                'name': 'quota-send-reminders',
                'task': 'core.tasks.send_quota_reminder_emails',
                'crontab': schedule_8am,
                'description': 'Send quota overage reminder emails (runs daily at 8 AM)',
            },
            {
                'name': 'quota-cleanup-old',
                'task': 'core.tasks.cleanup_old_resolved_overages',
                'crontab': schedule_sunday_4am,
                'description': 'Clean up old resolved quota overage records (runs weekly on Sunday at 4 AM)',
            },
        ]

        for task_config in tasks:
            task, created = PeriodicTask.objects.update_or_create(
                name=task_config['name'],
                defaults={
                    'task': task_config['task'],
                    'crontab': task_config['crontab'],
                    'description': task_config['description'],
                    'enabled': True,
                }
            )
            status = 'Created' if created else 'Updated'
            self.stdout.write(self.style.SUCCESS(f"  {status}: {task.name}"))

        self.stdout.write(self.style.SUCCESS('\nQuota management tasks set up successfully!'))
        self.stdout.write('\nTasks configured:')
        self.stdout.write('  - quota-check-all-tenants: Daily at 2 AM')
        self.stdout.write('  - quota-process-expired: Daily at 3 AM')
        self.stdout.write('  - quota-send-reminders: Daily at 8 AM')
        self.stdout.write('  - quota-cleanup-old: Weekly on Sunday at 4 AM')
