'''
Clear command

This management command provides utilities to delete (clear) seeded or existing
data from Django models. It supports clearing a specific model or all models
across all installed apps, with optional confirmation prompts for safety.
'''

from django.core.management.base import BaseCommand, CommandError
from django.apps import apps


class Command(BaseCommand):
    help = 'Clear seeded data from Django models'

    def add_arguments(self, parser):
        parser.add_argument(
            '--model',
            type=str,
            help='Specific model to clear (format: ModelName)'
        )
        
        parser.add_argument(
            '--app',
            type=str,
            help='Django app label'
        )
        
        parser.add_argument(
            '--all',
            action='store_true',
            help='Clear all data from all models (dangerous)'
        )
        
        parser.add_argument(
            '--confirm',
            action='store_true',
            help='Skip confirmation prompt'
        )

    def handle(self, *args, **options):
        if options['all']:
            if not options['confirm']:
                confirm = input('Clear ALL data from ALL models? (yes/no): ')
                if confirm.lower() != 'yes':
                    self.stdout.write('Aborted')
                    return
            
            count = 0
            for app_config in apps.get_app_configs():
                for model in app_config.get_models():
                    deleted, _ = model.objects.all().delete()
                    count += deleted
                    self.stdout.write(f'Cleared {model.__name__}')
            
            self.stdout.write(self.style.SUCCESS(f'Total records deleted: {count}'))
        
        elif options['model'] and options['app']:
            try:
                model = apps.get_model(options['app'], options['model'])
                count = model.objects.count()
                
                if not options['confirm']:
                    confirm = input(f'Clear {count} records from {options["model"]}? (yes/no): ')
                    if confirm.lower() != 'yes':
                        self.stdout.write('Aborted')
                        return
                
                model.objects.all().delete()
                self.stdout.write(self.style.SUCCESS(f'Cleared {options["model"]}'))
            except LookupError:
                raise CommandError(f'Model not found: {options["app"]}.{options["model"]}')
        else:
            self.stdout.write(
                self.style.ERROR('Either --all or both --model and --app must be provided')
            )  
