import os
import sys
import django
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.hashers import make_password, check_password

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

User = get_user_model()

def verify_or_create_admin():
    email = 'admin@branchbusinessadvance.com'
    password = 'admin123'
    
    print(f"\nChecking for admin user with email: {email}")
    
    try:
        # Try to get the user
        user = User.objects.get(email=email)
        print(f"Found existing user: {user.email}")
        
        # Verify the password
        if check_password(password, user.password):
            print("✓ Password is correct")
        else:
            print("✗ Password is incorrect - updating password...")
            user.password = make_password(password)
            user.save()
            print("✓ Password has been updated")
            
        # Ensure user is staff and superuser
        if not user.is_staff or not user.is_superuser:
            print("Updating user permissions...")
            user.is_staff = True
            user.is_superuser = True
            user.save()
            print("✓ User permissions updated")
            
        print("\nAdmin user is ready to use:")
        print(f"Email: {email}")
        print(f"Password: {password}")
        
    except ObjectDoesNotExist:
        print(f"No user found with email {email}")
        print("Creating new admin user...")
        
        # Create new superuser
        user = User.objects.create_superuser(
            email=email,
            password=password,
            is_staff=True,
            is_superuser=True
        )
        
        print("\n✓ Admin user created successfully:")
        print(f"Email: {email}")
        print(f"Password: {password}")

if __name__ == '__main__':
    try:
        verify_or_create_admin()
        print("\nScript completed successfully!")
    except Exception as e:
        print(f"\nError: {str(e)}")
        sys.exit(1) 