"""
Management command to ensure all users have UserProfile instances.

This command creates UserProfile for any User that doesn't have one,
preventing AttributeError when accessing user.user_profile.

Usage:
    python manage.py ensure_user_profiles
"""

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from appauthentication.models import UserProfile


class Command(BaseCommand):
    help = 'Ensure all users have UserProfile instances'

    def handle(self, *args, **options):
        self.stdout.write(self.style.WARNING('Checking for users without profiles...'))
        
        # Find all users
        all_users = User.objects.all()
        total_users = all_users.count()
        
        self.stdout.write(f'Found {total_users} total users')
        
        # Check for missing profiles
        users_without_profile = []
        for user in all_users:
            if not hasattr(user, 'user_profile'):
                users_without_profile.append(user)
        
        missing_count = len(users_without_profile)
        
        if missing_count == 0:
            self.stdout.write(self.style.SUCCESS('✅ All users already have profiles!'))
            return
        
        self.stdout.write(f'Found {missing_count} users without profiles')
        
        # Create missing profiles
        created_count = 0
        for user in users_without_profile:
            try:
                profile = UserProfile.objects.create(user=user)
                # Add default 'sponsor' role
                profile.add_role('sponsor')
                created_count += 1
                self.stdout.write(f'  ✓ Created profile for user: {user.username}')
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f'  ✗ Error creating profile for {user.username}: {e}')
                )
        
        self.stdout.write(
            self.style.SUCCESS(f'\n✅ Successfully created {created_count} out of {missing_count} profiles')
        )
