#!/usr/bin/env python3
"""
Django Management Command: ensure_admin_user

This command ensures that a default admin superuser (admin@adtlas.com) exists
in the system. It's designed to be run automatically after migrations to
ensure there's always an admin user available.

Usage:
    python manage.py ensure_admin_user
    
Environment Variables:
    ADMIN_PASSWORD: Password for the admin user (defaults to 'admin123' if not set)
"""

import os
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db import transaction

User = get_user_model()


class Command(BaseCommand):
    """Management command to ensure admin@adtlas.com superuser exists."""
    
    help = 'Ensure admin@adtlas.com superuser exists in the system'
    
    def add_arguments(self, parser):
        """Add command arguments."""
        parser.add_argument(
            '--password',
            dest='password',
            default=None,
            help='Specifies the password for the admin user (overrides environment variable)'
        )
        
        parser.add_argument(
            '--update-password',
            action='store_true',
            dest='update_password',
            help='Update the password if the user already exists'
        )
        
        parser.add_argument(
            '--quiet',
            action='store_true',
            dest='quiet',
            help='Suppress output messages'
        )
    
    def handle(self, *args, **options):
        """Handle the command execution."""
        admin_email = 'admin@adtlas.com'
        admin_username = 'admin'
        
        # Get password from options, environment, or use default
        password = (
            options['password'] or 
            os.environ.get('ADMIN_PASSWORD') or 
            'admin123'
        )
        
        update_password = options['update_password']
        quiet = options['quiet']
        
        try:
            with transaction.atomic():
                # Check if user exists by email or username
                user = None
                user_exists = False
                
                # Try to find user by email first
                try:
                    user = User.objects.get(email=admin_email)
                    user_exists = True
                    if not quiet:
                        self.stdout.write(
                            f'Found existing user with email: {admin_email}'
                        )
                except User.DoesNotExist:
                    pass
                
                # If not found by email, try by username
                if not user_exists:
                    try:
                        user = User.objects.get(username=admin_username)
                        user_exists = True
                        if not quiet:
                            self.stdout.write(
                                f'Found existing user with username: {admin_username}'
                            )
                    except User.DoesNotExist:
                        pass
                
                if user_exists:
                    # User exists, update if requested
                    if update_password:
                        user.set_password(password)
                        user.is_staff = True
                        user.is_superuser = True
                        user.is_active = True
                        
                        # Update email and username if needed
                        if user.email != admin_email:
                            user.email = admin_email
                        if user.username != admin_username:
                            user.username = admin_username
                            
                        user.save()
                        
                        if not quiet:
                            self.stdout.write(
                                self.style.SUCCESS(
                                    f'Admin user updated: {admin_email}'
                                )
                            )
                    else:
                        # Just ensure the user has admin privileges
                        updated = False
                        if not user.is_staff:
                            user.is_staff = True
                            updated = True
                        if not user.is_superuser:
                            user.is_superuser = True
                            updated = True
                        if not user.is_active:
                            user.is_active = True
                            updated = True
                            
                        if updated:
                            user.save()
                            if not quiet:
                                self.stdout.write(
                                    self.style.SUCCESS(
                                        f'Admin privileges updated for: {admin_email}'
                                    )
                                )
                        elif not quiet:
                            self.stdout.write(
                                self.style.SUCCESS(
                                    f'Admin user already exists and is properly configured: {admin_email}'
                                )
                            )
                else:
                    # Create new admin user
                    user = User.objects.create_superuser(
                        username=admin_username,
                        email=admin_email,
                        password=password
                    )
                    
                    if not quiet:
                        self.stdout.write(
                            self.style.SUCCESS(
                                f'Admin superuser created successfully: {admin_email}'
                            )
                        )
                        self.stdout.write(
                            self.style.WARNING(
                                f'Default password is being used. Please change it after first login.'
                            )
                        )
                
        except Exception as e:
            self.stderr.write(
                self.style.ERROR(
                    f'Error ensuring admin user: {str(e)}'
                )
            )
            raise