import os, sys
import subprocess

subprocess.run([sys.executable, "-m", "pip", "install", "pipenv"])
subprocess.run([sys.executable, "-m", "pipenv", "install", "--dev"], cwd=os.path.dirname(os.path.abspath(__file__)))
subprocess.run([sys.executable, "-m", "pipenv", "shell"], cwd=os.path.dirname(os.path.abspath(__file__)))

print("Dependencies installed from Pipfile.")

from mysql.connector import errorcode
from dotenv import load_dotenv
import os
import mysql.connector

# Database configuration
# Load environment variables from .env.dev file
load_dotenv(dotenv_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env.dev'))

db_config = {
    'user': os.getenv('DB_USER'),
    'password': os.getenv('DB_PASSWORD'),
    'host': os.getenv('DB_HOST'),
    'database': os.getenv('DB_DATABASE_NAME')
}

# Create MySQL database
try:
    cnx = mysql.connector.connect(user=db_config['user'], password=db_config['password'], host=db_config['host'])
    cursor = cnx.cursor()
    cursor.execute(f"CREATE DATABASE {db_config['database']} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
    print(f"Database {db_config['database']} created successfully.")
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    else:
        print(err)
finally:
    cursor.close()
    cnx.close()


# migrate the django models to the database and run the fixtures files located in gardens/fixtures make migrations for usercontrol and gardens
subprocess.run([sys.executable, "manage.py", "makemigrations", "usercontrol"], cwd=os.path.dirname(os.path.abspath(__file__)))
subprocess.run([sys.executable, "manage.py", "makemigrations", "gardens"], cwd=os.path.dirname(os.path.abspath(__file__)))
subprocess.run([sys.executable, "manage.py", "migrate", "django_apscheduler"], cwd=os.path.dirname(os.path.abspath(__file__)))
subprocess.run([sys.executable, "manage.py", "migrate"], cwd=os.path.dirname(os.path.abspath(__file__)))

subprocess.run([sys.executable, "manage.py", "loaddata", "gardens/fixtures/defaultData.json"], cwd=os.path.dirname(os.path.abspath(__file__)))

# collect static
subprocess.run([sys.executable, "manage.py", "collectstatic"], cwd=os.path.dirname(os.path.abspath(__file__)))

# create superuser
subprocess.run([sys.executable, "manage.py", "createsuperuser"], cwd=os.path.dirname(os.path.abspath(__file__)))
