import subprocess
import sys
import os
import signal

def cleanup_port(port=5001):
    print(f"Cleaning up port {port}...")
    try:
        cmd = f"lsof -ti:{port}"
        pids = subprocess.check_output(cmd, shell=True).decode().split()
        for pid in pids:
            print(f"Terminating zombie process: {pid}")
            os.kill(int(pid), signal.SIGKILL)
    except:
        pass

def check_dependencies():
    print("Skipping dependency check for already installed packages.")
    pass

def run_app():
    cleanup_port(5001)
    print("Starting DREAMER_ENGINE...")
    os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
    try:
        subprocess.run(["npm", "start"], check=True)
    except KeyboardInterrupt:
        print("\nStopping Dreamer.")
    except Exception as e:
        print(f"Error starting Electron: {e}")

if __name__ == "__main__":
    check_dependencies()
    run_app()
