from django.core.management.base import BaseCommand
from django.utils import timezone
from calls.models import Call, CallLog
from seniors.models import Senior
import logging

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Monitor live calls and send warnings when time limit is approaching'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--test',
            action='store_true',
            help='Test mode - shows calculations without taking action',
        )
        parser.add_argument(
            '--call-id',
            type=int,
            help='Monitor specific call ID only',
        )
        parser.add_argument(
            '--force-warning',
            action='store_true',
            help='Force warning for testing (even if time not low)',
        )

    def handle(self, *args, **options):
        test_mode = options['test']
        specific_call_id = options['call_id']
        force_warning = options['force_warning']
        
        if test_mode:
            self.stdout.write(self.style.WARNING('🧪 TEST MODE - No actions will be taken'))
        
        if specific_call_id:
            self.stdout.write(f'Monitoring specific call ID: {specific_call_id}')
            calls = Call.objects.filter(id=specific_call_id)
        else:
            # Get all currently active calls
            calls = Call.objects.filter(
                twilio_status='in-progress',
                call_start_time__isnull=False,
                vapi_call_id__isnull=False
            )
        
        self.stdout.write(f'Found {calls.count()} active call(s) to monitor')
        
        for call in calls:
            try:
                self.monitor_single_call(call, test_mode, force_warning)
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'Error monitoring call {call.id}: {str(e)}'))
                logger.error(f'Error monitoring call {call.id}: {str(e)}')
        
        if not test_mode:
            self.stdout.write(self.style.SUCCESS('✅ Live call monitoring completed'))
    
    def monitor_single_call(self, call, test_mode=False, force_warning=False):
        """Monitor a single call for time limits"""
        
        # Calculate actual elapsed time since call started
        elapsed_seconds = (timezone.now() - call.call_start_time).total_seconds()
        elapsed_seconds = int(elapsed_seconds)
        
        # Get senior's remaining time
        senior = call.senior
        remaining_seconds = senior.get_remaining_seconds()
        
        # Calculate remaining after this call
        remaining_after_call = remaining_seconds - elapsed_seconds
        
        self.stdout.write(f'\n📞 Call ID: {call.id} - {call.senior.name}')
        self.stdout.write(f'   ⏱️  Elapsed time: {elapsed_seconds}s')
        self.stdout.write(f'   📊 DB Remaining: {remaining_seconds}s')
        self.stdout.write(f'   🔮 After this call: {remaining_after_call}s')
        
        # Check if we need to take action
        if test_mode:
            if remaining_after_call <= 30 and remaining_after_call > 0:
                self.stdout.write(self.style.WARNING(
                    f'   ⚠️  WOULD send 30s warning ({remaining_after_call}s remaining)'
                ))
            elif remaining_after_call <= 0:
                self.stdout.write(self.style.ERROR(
                    f'   🛑 WOULD end call (time limit reached)'
                ))
            return
        
        # Real monitoring - take action
        if not call.is_limit_enforced:
            if force_warning or (remaining_after_call <= 30 and remaining_after_call > 0):
                # Send 30-second warning
                from calls.tasks import send_time_warning_to_senior
                result = send_time_warning_to_senior.delay(call.id, remaining_after_call)
                
                self.stdout.write(self.style.WARNING(
                    f'   ⚠️  Sent {remaining_after_call}s warning (Task ID: {result.id})'
                ))
                
                call.is_limit_enforced = True
                call.save(update_fields=['is_limit_enforced'])
                
                CallLog.objects.create(
                    call=call,
                    event_type='time_warning_sent',
                    message=f'30-second warning sent. {remaining_after_call} seconds remaining',
                    data={
                        'elapsed_seconds': elapsed_seconds,
                        'remaining_seconds': remaining_after_call,
                        'call_id': call.id,
                        'senior_id': senior.id
                    }
                )
                
            elif remaining_after_call <= 0:
                # Time limit reached - end the call
                from calls.tasks import enforce_call_limit_task
                result = enforce_call_limit_task.delay(call.id)
                
                self.stdout.write(self.style.ERROR(
                    f'   🛑 Ending call - time limit reached (Task ID: {result.id})'
                ))
                
                CallLog.objects.create(
                    call=call,
                    event_type='time_limit_reached',
                    message=f'Time limit reached. Elapsed: {elapsed_seconds}s',
                    data={
                        'elapsed_seconds': elapsed_seconds,
                        'remaining_seconds': remaining_after_call,
                        'call_id': call.id,
                        'senior_id': senior.id
                    }
                )
        else:
            self.stdout.write('   ✅ Already enforced')
