"""Management command to create a superuser non-interactively.

This command allows creating a superuser from the command line
without interactive prompts, useful for automation and deployment scripts.
"""

import os
import sys
import getpass
from django.db import IntegrityError
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError

User = get_user_model()


class Command(BaseCommand):
    """Management command to create a superuser non-interactively."""
    
    help = 'Create a superuser non-interactively'
    
    def add_arguments(self, parser):
        """Add command arguments."""
        parser.add_argument(
            '--username',
            dest='username',
            default=None,
            help='Specifies the username for the superuser.'
        )
        
        parser.add_argument(
            '--email',
            dest='email',
            default=None,
            help='Specifies the email for the superuser.'
        )
        
        parser.add_argument(
            '--password',
            dest='password',
            default=None,
            help='Specifies the password for the superuser.'
        )
        
        parser.add_argument(
            '--noinput',
            '--no-input',
            action='store_true',
            dest='noinput',
            help='Create superuser non-interactively. '
                 'All values must be provided via command arguments.'
        )
        
        parser.add_argument(
            '--preserve',
            action='store_true',
            dest='preserve',
            help='Exit without error if the user already exists.'
        )
        
        parser.add_argument(
            '--update',
            action='store_true',
            dest='update',
            help='Update the existing user if it exists.'
        )
    
    def handle(self, *args, **options):
        """Handle the command execution."""
        username = options['username']
        email = options['email']
        password = options['password']
        noinput = options['noinput']
        preserve = options['preserve']
        update = options['update']
        
        # Check for environment variables if not provided as arguments
        if not username:
            username = os.environ.get('DJANGO_SUPERUSER_USERNAME')
        
        if not email:
            email = os.environ.get('DJANGO_SUPERUSER_EMAIL')
        
        if not password:
            password = os.environ.get('DJANGO_SUPERUSER_PASSWORD')
        
        # Interactive mode if not noinput
        if not noinput:
            # Get username
            if not username:
                username = input('Username: ')
            
            # Get email
            if not email:
                email = input('Email address: ')
            
            # Get password
            if not password:
                password = getpass.getpass('Password: ')
                password2 = getpass.getpass('Password (again): ')
                
                if password != password2:
                    self.stderr.write('Error: Passwords do not match')
                    sys.exit(1)
        
        # Validate inputs
        if not username:
            raise CommandError('Username is required')
        
        if not email:
            raise CommandError('Email is required')
        
        if not password:
            raise CommandError('Password is required')
        
        # Check if user exists
        user_exists = User.objects.filter(username=username).exists()
        
        if user_exists:
            if preserve:
                self.stdout.write(
                    self.style.SUCCESS(
                        f'User {username} already exists. Skipping creation.'
                    )
                )
                return
            
            if update:
                try:
                    user = User.objects.get(username=username)
                    user.email = email
                    user.set_password(password)
                    user.is_staff = True
                    user.is_superuser = True
                    user.save()
                    
                    self.stdout.write(
                        self.style.SUCCESS(
                            f'Superuser {username} updated successfully.'
                        )
                    )
                    return
                except Exception as e:
                    raise CommandError(f'Error updating user: {str(e)}')
            
            raise CommandError(f'User {username} already exists')
        
        # Create superuser
        try:
            User.objects.create_superuser(
                username=username,
                email=email,
                password=password
            )
            
            self.stdout.write(
                self.style.SUCCESS(
                    f'Superuser {username} created successfully.'
                )
            )
            
        except IntegrityError:
            raise CommandError(
                f'Error creating superuser. '
                f'User with username or email may already exist.'
            )
        except Exception as e:
            raise CommandError(f'Error creating superuser: {str(e)}')