#!/usr/bin/env python3
"""Kill existing backend process on port 8010 and restart."""
import os
import sys
import signal
import subprocess
import time

# Find and kill existing process on port 8010
try:
    import psutil
except ImportError:
    # Use subprocess to find process
    result = subprocess.run(
        ["lsof", "-i", ":8010", "-t"],
        capture_output=True, text=True
    )
    pids = result.stdout.strip().split("\n")
    for pid in pids:
        if pid:
            pid = int(pid.strip())
            print(f"Killing PID {pid} on port 8010")
            os.kill(pid, signal.SIGTERM)
            time.sleep(1)
except Exception as e:
    print(f"Could not kill existing process: {e}")

# Restart
os.chdir("/root/cma-management/backend")
cmd = "nohup uvicorn app.main:app --host 0.0.0.0 --port 8010 > /var/log/cma-backend.log 2>&1 &"
print(f"Restarting: {cmd}")
subprocess.run(cmd, shell=True)
time.sleep(3)
print("Done. Checking process...")
subprocess.run(["lsof", "-i", ":8010"])
