
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model

User = get_user_model()

class Command(BaseCommand):
    help = 'Create a director/superuser account'

    def add_arguments(self, parser):
        parser.add_argument('username', type=str, help='Username for the director')
        parser.add_argument('email', type=str, help='Email for the director')
        parser.add_argument('--first-name', type=str, help='First name of the director')
        parser.add_argument('--last-name', type=str, help='Last name of the director')
        parser.add_argument('--password', type=str, help='Password (if not provided, will be prompted)')

    def handle(self, *args, **options):
        username = options['username']
        email = options['email']
        first_name = options.get('first_name', '')
        last_name = options.get('last_name', '')
        password = options.get('password')

        # Check if user already exists
        if User.objects.filter(username=username).exists():
            self.stdout.write(
                self.style.ERROR(f'User with username "{username}" already exists.')
            )
            return

        if User.objects.filter(email=email).exists():
            self.stdout.write(
                self.style.ERROR(f'User with email "{email}" already exists.')
            )
            return

        # Get password if not provided
        if not password:
            import getpass
            password = getpass.getpass('Password: ')
            confirm_password = getpass.getpass('Confirm password: ')
            
            if password != confirm_password:
                self.stdout.write(
                    self.style.ERROR('Passwords do not match.')
                )
                return

        # Create the superuser
        user = User.objects.create_user(
            username=username,
            email=email,
            password=password,
            first_name=first_name,
            last_name=last_name,
            is_superuser=True,
            is_staff=True,
            role='admin'
        )

        self.stdout.write(
            self.style.SUCCESS(f'Successfully created director account for {username}')
        )
        self.stdout.write(f'Username: {username}')
        self.stdout.write(f'Email: {email}')
        self.stdout.write(f'Login URL: /accounts/superuser-login/')
