import requests
import sys
from time import sleep
import subprocess


def check_connection(ip):
    try:
        response = requests.post(f"http://{ip}/check_connection")
        if response.status_code == 200:
            print(f"Connetion established with {ip}. The script will run in 15 seconds.")
            sleep(15)
            execute_python_file(main_script, *new_args)
    except:
        sleep(5)
        check_connection(ip)


def execute_python_file(main_script, *args):
    cmd = ['python', main_script] + list(args)
    try:
        subprocess.run(cmd, check=True)
    except subprocess.CalledProcessError as e:
        print(f"Error running the script: {e}")


if __name__ == "__main__":
    ip = sys.argv[1] #ip with port to check, for the clients, check the DMLO
    main_script = sys.argv[2]
    new_args = sys.argv[3:]
    check_connection(ip)
