from django.core.management.base import BaseCommand
from ml_service.tasks import schedule_daily_notifications, send_notification_at_exact_time
from ml_service.models import UserPattern, ScheduledNotification
from django.utils import timezone
from datetime import datetime
import json


class Command(BaseCommand):
    help = 'Manually trigger notification scheduling or send notifications immediately. Use --schedule to schedule notifications for today, or --send-now to send notifications immediately for a specific user.'

    def add_arguments(self, parser):
        parser.add_argument(
            '--schedule',
            action='store_true',
            help='Schedule all notifications for today (runs schedule_daily_notifications)',
        )
        parser.add_argument(
            '--send-now',
            action='store_true',
            help='Send notifications immediately for all users (bypasses scheduling)',
        )
        parser.add_argument(
            '--user-id',
            type=str,
            help='Specific user ID to send notification for (use with --send-now)',
        )
        parser.add_argument(
            '--question-type',
            type=str,
            help='Specific question_type to send notification for (use with --send-now, e.g., clock_in, lunch_out)',
        )
        parser.add_argument(
            '--verbose',
            action='store_true',
            help='Show detailed output',
        )

    def handle(self, *args, **options):
        schedule = options.get('schedule', False)
        send_now = options.get('send_now', False)
        user_id = options.get('user_id', None)
        question_type = options.get('question_type', None)
        verbose = options.get('verbose', False)

        if schedule:
            self._schedule_notifications(verbose)
        elif send_now:
            self._send_notifications_now(user_id, question_type, verbose)
        else:
            self.stdout.write(self.style.ERROR('Please specify --schedule or --send-now'))
            self.stdout.write('')
            self.stdout.write('Examples:')
            self.stdout.write('  python manage.py trigger_notifications --schedule')
            self.stdout.write('  python manage.py trigger_notifications --send-now')
            self.stdout.write('  python manage.py trigger_notifications --send-now --user-id USER_ID --question-type clock_in')

    def _schedule_notifications(self, verbose):
        """Schedule notifications for today"""
        self.stdout.write(self.style.WARNING('Scheduling notifications for today...'))
        self.stdout.write('This will schedule notifications for all users with patterns.')
        self.stdout.write('')
        
        try:
            result = schedule_daily_notifications()
            
            if verbose:
                self.stdout.write('')
                self.stdout.write(self.style.SUCCESS('Task completed successfully!'))
                self.stdout.write('')
                self.stdout.write('Result:')
                self.stdout.write(json.dumps(result, indent=2, default=str))
            else:
                status = result.get('status', 'unknown')
                if status == 'success':
                    scheduled = result.get('notifications_scheduled', 0)
                    users = result.get('users_processed', 0)
                    
                    self.stdout.write('')
                    self.stdout.write(self.style.SUCCESS('✓ Notifications scheduled successfully!'))
                    self.stdout.write('')
                    self.stdout.write(f'Users processed: {users}')
                    self.stdout.write(f'Notifications scheduled: {scheduled}')
                    self.stdout.write('')
                    self.stdout.write(self.style.WARNING(
                        'Note: Notifications will be sent at their scheduled times.'
                    ))
                    self.stdout.write('Make sure Celery worker is running to send them.')
                else:
                    self.stdout.write('')
                    self.stdout.write(self.style.ERROR(f'Task failed with status: {status}'))
                    if 'error' in result:
                        self.stdout.write(f'Error: {result.get("error")}')
        except Exception as e:
            self.stdout.write('')
            self.stdout.write(self.style.ERROR(f'✗ Failed to schedule notifications: {str(e)}'))
            if verbose:
                import traceback
                self.stdout.write('')
                self.stdout.write('Traceback:')
                self.stdout.write(traceback.format_exc())

    def _send_notifications_now(self, user_id, question_type, verbose):
        """Send notifications immediately"""
        from ml_service.push_service import PushNotificationService
        
        self.stdout.write(self.style.WARNING('Sending notifications immediately...'))
        self.stdout.write('')
        
        try:
            push_service = PushNotificationService()
            sent_count = 0
            skipped_count = 0
            failed_count = 0
            
            if user_id and question_type:
                # Send for specific user and question_type
                self.stdout.write(f'Sending notification for user {user_id}, type {question_type}...')
                try:
                    pattern = UserPattern.objects.get(user_id=user_id, question_type=question_type)
                    
                    # Check if user already did action
                    if push_service.user_already_did_action(user_id, question_type):
                        self.stdout.write(self.style.WARNING('User already completed this action - skipping'))
                        skipped_count += 1
                    else:
                        typical_time_str = pattern.average_time.strftime('%H:%M')
                        success = push_service.send_smart_reminder(user_id, question_type, typical_time_str)
                        
                        if success:
                            self.stdout.write(self.style.SUCCESS('✓ Notification sent successfully!'))
                            sent_count += 1
                        else:
                            self.stdout.write(self.style.ERROR('✗ Failed to send notification'))
                            failed_count += 1
                except UserPattern.DoesNotExist:
                    self.stdout.write(self.style.ERROR(f'Pattern not found for user {user_id}, type {question_type}'))
                    failed_count += 1
            else:
                # Send for all users with patterns
                self.stdout.write('Sending notifications for all users with patterns...')
                self.stdout.write('')
                
                patterns = UserPattern.objects.all()
                total_patterns = patterns.count()
                
                for pattern in patterns:
                    try:
                        # Check if user already did action
                        if push_service.user_already_did_action(str(pattern.user_id), pattern.question_type):
                            skipped_count += 1
                            if verbose:
                                self.stdout.write(f'Skipped: User {pattern.user_id} already completed {pattern.question_type}')
                            continue
                        
                        # Send notification
                        typical_time_str = pattern.average_time.strftime('%H:%M')
                        success = push_service.send_smart_reminder(
                            str(pattern.user_id), 
                            pattern.question_type, 
                            typical_time_str
                        )
                        
                        if success:
                            sent_count += 1
                            if verbose:
                                self.stdout.write(
                                    self.style.SUCCESS(
                                        f'✓ Sent to user {pattern.user_id} for {pattern.question_type}'
                                    )
                                )
                        else:
                            failed_count += 1
                            if verbose:
                                self.stdout.write(
                                    self.style.ERROR(
                                        f'✗ Failed to send to user {pattern.user_id} for {pattern.question_type}'
                                    )
                                )
                    except Exception as e:
                        failed_count += 1
                        if verbose:
                            self.stdout.write(
                                self.style.ERROR(
                                    f'✗ Error sending to user {pattern.user_id}: {str(e)}'
                                )
                            )
                
                self.stdout.write('')
                self.stdout.write(self.style.SUCCESS('✓ Notification sending completed!'))
                self.stdout.write('')
                self.stdout.write(f'Total patterns: {total_patterns}')
                self.stdout.write(f'Notifications sent: {sent_count}')
                self.stdout.write(f'Skipped (already done): {skipped_count}')
                self.stdout.write(f'Failed: {failed_count}')
        
        except Exception as e:
            self.stdout.write('')
            self.stdout.write(self.style.ERROR(f'✗ Failed to send notifications: {str(e)}'))
            if verbose:
                import traceback
                self.stdout.write('')
                self.stdout.write('Traceback:')
                self.stdout.write(traceback.format_exc())

