from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timedelta
from calls.models import Call, CallLog


class Command(BaseCommand):
    help = 'Clear stuck calls that failed to start properly'

    def add_arguments(self, parser):
        parser.add_argument(
            '--minutes',
            type=int,
            default=5,
            help='Mark calls as failed if they are older than this many minutes (default: 5)',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be cleared without actually clearing',
        )

    def handle(self, *args, **options):
        minutes = options['minutes']
        dry_run = options['dry_run']
        
        # Find stuck calls (initiated status, no Vapi Call ID, older than specified minutes)
        cutoff_time = timezone.now() - timedelta(minutes=minutes)
        stuck_calls = Call.objects.filter(
            twilio_status='initiated',
            vapi_call_id__isnull=True,
            created_at__lt=cutoff_time
        )
        
        if not stuck_calls.exists():
            self.stdout.write(
                self.style.SUCCESS('No stuck calls found to clear.')
            )
            return
        
        self.stdout.write(f'Found {stuck_calls.count()} stuck calls:')
        
        for call in stuck_calls:
            self.stdout.write(
                f'  - Call {call.id}: {call.senior.name} - Created: {call.created_at}'
            )
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING(f'Dry run mode - would mark {stuck_calls.count()} calls as failed')
            )
            return
        
        # Clear the stuck calls
        cleared_count = 0
        for call in stuck_calls:
            call.twilio_status = 'failed'
            call.vapi_status = 'failed'
            call.save()
            cleared_count += 1
            
            # Log the clearing action
            CallLog.objects.create(
                call=call,
                event_type='cleared_by_admin',
                message=f'Call marked as failed (stuck for {minutes}+ minutes)',
                data={'cleared_at': timezone.now().isoformat(), 'reason': 'stuck_call'}
            )
        
        self.stdout.write(
            self.style.SUCCESS(f'Successfully cleared {cleared_count} stuck calls.')
        )

