from django.core.management.base import BaseCommand
from django.contrib.auth.hashers import make_password
from apps.accounts.models import User, Profile
import os

class Command(BaseCommand):
    help = 'Create a superuser for the application'

    def add_arguments(self, parser):
        parser.add_argument(
            '--email',
            type=str,
            help='Superuser email address'
        )
        parser.add_argument(
            '--username',
            type=str,
            help='Superuser username'
        )
        parser.add_argument(
            '--password',
            type=str,
            help='Superuser password'
        )
        parser.add_argument(
            '--first_name',
            type=str,
            help='Superuser first name'
        )
        parser.add_argument(
            '--last_name',
            type=str,
            help='Superuser last name'
        )
        parser.add_argument(
            '--noinput',
            action='store_true',
            help='Don\'t prompt for input, use environment variables or defaults'
        )

    def handle(self, *args, **options):
        # Get values from arguments, environment variables, or defaults
        if options['noinput']:
            email = (
                options.get('email') or 
                os.environ.get('DJANGO_SUPERUSER_EMAIL') or 
                'admin@adtlas.com'
            )
            username = (
                options.get('username') or 
                os.environ.get('DJANGO_SUPERUSER_USERNAME') or 
                'admin'
            )
            password = (
                options.get('password') or 
                os.environ.get('DJANGO_SUPERUSER_PASSWORD') or 
                'admin123'
            )
            first_name = (
                options.get('first_name') or 
                os.environ.get('DJANGO_SUPERUSER_FIRST_NAME') or 
                'Admin'
            )
            last_name = (
                options.get('last_name') or 
                os.environ.get('DJANGO_SUPERUSER_LAST_NAME') or 
                'User'
            )
        else:
            # Interactive mode - prompt for input
            email = options.get('email') or input('Email address: ')
            username = options.get('username') or input('Username: ')
            password = options.get('password') or input('Password: ')
            first_name = options.get('first_name') or input('First name: ')
            last_name = options.get('last_name') or input('Last name: ')

        # Validate required fields
        if not all([email, username, password, first_name, last_name]):
            self.stdout.write(
                self.style.ERROR('❌ All fields (email, username, password, first_name, last_name) are required')
            )
            return

        try:
            # Check if superuser already exists by email or username
            existing_user = None
            try:
                existing_user = User.objects.get(email=email)
            except User.DoesNotExist:
                try:
                    existing_user = User.objects.get(username=username)
                except User.DoesNotExist:
                    pass

            if existing_user:
                # Update existing user to be superuser
                existing_user.email = email
                existing_user.username = username
                existing_user.first_name = first_name
                existing_user.last_name = last_name
                existing_user.set_password(password)
                existing_user.is_active = True
                existing_user.is_staff = True
                existing_user.is_superuser = True
                existing_user.is_verified = getattr(existing_user, 'is_verified', True)
                existing_user.save()

                # Update or create profile
                profile, created = Profile.objects.get_or_create(
                    user=existing_user,
                    defaults={
                        'job_title': 'System Administrator',
                        'company': 'Adtlas'
                    }
                )
                if not created:
                    profile.job_title = 'System Administrator'
                    profile.company = 'Adtlas'
                    profile.save()

                self.stdout.write(
                    self.style.SUCCESS(f'✅ Updated existing user to superuser: {email}')
                )
            else:
                # Create new superuser
                user = User.objects.create_superuser(
                    email=email,
                    username=username,
                    first_name=first_name,
                    last_name=last_name, 
                    password=password
                ) 

                # Create profile
                profile, created = Profile.objects.get_or_create(
                    user=user,
                    defaults={
                        'job_title': 'System Administrator',
                        'company': 'Adtlas'
                    }
                )

                self.stdout.write(
                    self.style.SUCCESS(f'✅ Created new superuser: {email}')
                )

            # Display success information
            self.stdout.write('')
            self.stdout.write(self.style.SUCCESS('🎯 Superuser Details:'))
            self.stdout.write(f'   Email: {email}')
            self.stdout.write(f'   Username: {username}')
            self.stdout.write(f'   Name: {first_name} {last_name}')
            self.stdout.write('')
            
            if not options['noinput']:
                self.stdout.write(self.style.WARNING('⚠️  Please keep these credentials secure!'))
            else:
                self.stdout.write(self.style.WARNING('⚠️  Default credentials used - change password after first login!'))

        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'❌ Error creating superuser: {str(e)}')
            )
            
            # Debug information
            self.stdout.write('')
            self.stdout.write(self.style.WARNING('🔍 Debug Information:'))
            self.stdout.write(f'   User model: {User.__name__}')
            self.stdout.write('   Required fields:')
            
            for field in User._meta.fields:
                required = not field.null and not field.blank and not hasattr(field, 'default')
                self.stdout.write(f'     - {field.name} (required: {required})')
            
            raise