from django.core.management.base import BaseCommand
from django.utils import timezone
from calls.models import Call


class Command(BaseCommand):
    help = 'Clear all active calls by updating their status to completed'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be cleared without actually clearing',
        )

    def handle(self, *args, **options):
        # Find all active calls
        active_calls = Call.objects.filter(
            twilio_status__in=['initiated', 'ringing', 'in-progress']
        )
        
        if not active_calls.exists():
            self.stdout.write(
                self.style.SUCCESS('No active calls found to clear.')
            )
            return
        
        self.stdout.write(f'Found {active_calls.count()} active calls:')
        
        for call in active_calls:
            self.stdout.write(
                f'  - Call {call.id}: {call.senior.name} - Status: {call.twilio_status}'
            )
        
        if options['dry_run']:
            self.stdout.write(
                self.style.WARNING('Dry run mode - no calls were actually cleared.')
            )
            return
        
        # Clear the calls
        cleared_count = 0
        for call in active_calls:
            call.twilio_status = 'completed'
            call.vapi_status = 'ended'
            call.save()
            cleared_count += 1
            
            # Log the clearing action
            from calls.models import CallLog
            CallLog.objects.create(
                call=call,
                event_type='cleared_by_admin',
                message=f'Call cleared by admin command',
                data={'cleared_at': timezone.now().isoformat()}
            )
        
        self.stdout.write(
            self.style.SUCCESS(f'Successfully cleared {cleared_count} active calls.')
        )

