import subprocess
import os

def run_command(command):
    process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate(input=b"y\n")
    if process.returncode != 0:
        print(f"Error running command: {' '.join(command)}")
        print(f"stdout: {stdout.decode()}")
        print(f"stderr: {stderr.decode()}")
    return process.returncode

test_mode = os.getenv('TEST_MODE', 'False') == 'True'

commands = [
    ["python", "manage.py", "collectstatic", "--noinput"],
    ["python", "manage.py", "flush", "--noinput"],
    ["python", "manage.py", "makemigrations", "Common", "--noinput"],
    ["python", "manage.py", "makemigrations", "Establishment", "--noinput"],
    ["python", "manage.py", "makemigrations", "Settings", "--noinput"],
    ["python", "manage.py", "makemigrations", "Subscriptions", "--noinput"],
    ["python", "manage.py", "makemigrations", "Planning", "--noinput"],
    ["python", "manage.py", "makemigrations", "GestionNotification", "--noinput"],
    ["python", "manage.py", "makemigrations", "GestionEmail", "--noinput"],
    ["python", "manage.py", "makemigrations", "GestionMessagerie", "--noinput"],
    ["python", "manage.py", "makemigrations", "Auth", "--noinput"],
    ["python", "manage.py", "makemigrations", "School", "--noinput"],
    ["python", "manage.py", "migrate", "--noinput"]
]

test_commands = [
    ["python", "manage.py", "init_mock_datas"]
]

for command in commands:
    if run_command(command) != 0:
        exit(1)

#if test_mode:
#    for test_command in test_commands:
#        if run_command(test_command) != 0:
#            exit(1)

# Lancer les processus en parallèle

processes = [
    subprocess.Popen(["daphne", "-b", "0.0.0.0", "-p", "8080", "N3wtSchool.asgi:application"]),
    subprocess.Popen(["celery", "-A", "N3wtSchool", "worker", "--loglevel=info"]),
    subprocess.Popen(["celery", "-A", "N3wtSchool", "beat", "--loglevel=info", "--scheduler", "django_celery_beat.schedulers:DatabaseScheduler"])
]

# Attendre la fin des processus
for process in processes:
    process.wait()