import os
import sys

# Ensure this script is run from project root
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
import django
django.setup()

from django.contrib.auth.models import User

username = os.environ.get('JM_USERNAME')
email = os.environ.get('JM_EMAIL', '')
password = os.environ.get('JM_PASSWORD')
is_super = os.environ.get('JM_SUPER', '0') == '1'

if not username or not password:
    print('JM_USERNAME and JM_PASSWORD environment variables are required')
    sys.exit(2)

if User.objects.filter(username=username).exists():
    print(f"User '{username}' already exists")
    sys.exit(0)

if is_super:
    User.objects.create_superuser(username=username, email=email, password=password)
    print(f"Superuser '{username}' created")
else:
    User.objects.create_user(username=username, email=email, password=password)
    print(f"User '{username}' created")

sys.exit(0)
