import subprocess
import time
import requests




# Lista de portas que queremos derrubar
ports = [8504, 8505, 8506, 8507]

def kill_process_on_port(port):
    try:
        # Encontra o PID do processo que está usando a porta
        result = subprocess.run(
            ["lsof", "-ti", f":{port}"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        pids = result.stdout.strip().splitlines()

        if not pids:
            print(f"[INFO] Nenhum processo encontrado na porta {port}")
            return

        for pid in pids:
            subprocess.run(["kill", "-9", pid])
            print(f"[OK] Processo {pid} na porta {port} foi encerrado.")
    except Exception as e:
        print(f"[ERRO] Falha ao encerrar processo na porta {port}: {e}")

# Executa para todas as portas
for port in ports:
    kill_process_on_port(port)

# Comandos para iniciar os apps Streamlit
commands = [
	["pkill","traefik","-f"],
    ["python3.12", "-m", "streamlit", "run", "app.py", "--server.port=8504", "--server.fileWatcherType=none", "--","runscheduleanyway"],
    ["python3.12", "-m", "streamlit", "run", "app.py", "--server.port=8505", "--server.fileWatcherType=none"],
    ["python3.12", "-m", "streamlit", "run", "app.py", "--server.port=8506", "--server.fileWatcherType=none"],
    ["python3.12", "-m", "streamlit", "run", "app.py", "--server.port=8507", "--server.fileWatcherType=none"],
    ["traefik","--configfile=/etc/traefik/traefik.yml"],
]
#["python3.12", "-m", "streamlit", "run", "app.py", "--server.port", "8503", "--", "runapianyway"]

# Inicializa os processos em background
processes = []
for cmd in commands:
    print(f"Iniciando: {' '.join(cmd)}")
    p = subprocess.Popen(cmd)
    processes.append(p)
    time.sleep(5)

# Aguarda alguns segundos para os servidores subirem
time.sleep(5)

# URLs para verificação
urls = [
    "http://localhost:8504",
]
#"http://localhost:8503"

# Testa os endpoints
for url in urls:
    try:
        response = requests.get(url)
        print(f"{url} → Status: {response.status_code}")
    except requests.ConnectionError:
        print(f"{url} → Não foi possível conectar.")

# Aviso final
print("Todos os processos foram iniciados.")
