import os
import sys
import subprocess

# Activate the virtual environment 
activate_script = "/home/admondwo/virtualenv/pg.sweetvilla.in/3.12/bin/activate_this.py"
with open(activate_script) as f:
    exec(f.read(), {'__file__': activate_script})
    
# Now the virtual environment is activated
print("Virtual environment activated successfully!")


# Change to the application directory
app_dir = "/home/admondwo/pg.sweetvilla.in"
os.chdir(app_dir)

# Debug: Print the current working directory
print(f"Current directory: {os.getcwd()}")

# Install dependencies from requirements.txt
try:
    print("Installing dependencies from requirements.txt...")
    subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"], check=True)
    print("Dependencies installed successfully!")
except subprocess.CalledProcessError as e:
    print(f"Error installing dependencies: {e}")
except FileNotFoundError:
    print("Error: requirements.txt file not found in the application directory.")

# migration happens after the installation

from django.core.management import call_command
from django.core.management.base import CommandError
import django
from django.contrib.auth import get_user_model

# Set the DJANGO_SETTINGS_MODULE environment variable
os.environ['DJANGO_SETTINGS_MODULE'] = 'sweetvilla.settings'  # Replace with your project name

# Initialize Django
django.setup()


# Run migrate
try:
    print("Running migrations...")
    call_command("migrate")
    print("Migrations completed successfully!")
except CommandError as e:
    print(f"Error running migrations: {e}")

# Run collectstatic
try:
    print("Running collectstatic...")
    call_command("collectstatic", "--noinput")  # --noinput avoids prompting for confirmation
    print("Static files collected successfully!")
except CommandError as e:
    print(f"Error running collectstatic: {e}")

# Create superuser only if it doesn't exist
try:
    print("Checking if superuser exists...")
    User = get_user_model()
    if not User.objects.filter(username="admin").exists():  # Replace 'admin' with the desired username
        print("Superuser does not exist. Creating superuser...")
        os.environ["DJANGO_SUPERUSER_USERNAME"] = "admin"  # Replace with your desired username
        os.environ["DJANGO_SUPERUSER_EMAIL"] = "amar.softication@gmail.com"  # Replace with your desired email
        os.environ["DJANGO_SUPERUSER_PASSWORD"] = "Admin@123"  # Replace with your desired password
        call_command("createsuperuser", "--noinput")  # --noinput avoids prompting for input
        print("Superuser created successfully!")
    else:
        print("Superuser already exists.")
except CommandError as e:
    print(f"Error checking/creating superuser: {e}")