"""Kill all processes on port 8900, then start uvicorn."""
import subprocess, os, signal, time, sys

PORT = 8900

def get_pids():
    result = subprocess.run(['netstat', '-ano'], capture_output=True, text=True, encoding='gbk', errors='replace')
    pids = set()
    for line in result.stdout.splitlines():
        if f':{PORT}' in line and 'LISTENING' in line:
            parts = line.split()
            pids.add(int(parts[-1]))
    return pids

# Kill loop
for attempt in range(5):
    pids = get_pids()
    if not pids:
        print(f"Port {PORT} is free.")
        break
    print(f"Attempt {attempt+1}: killing PIDs {pids}")
    for pid in pids:
        try:
            subprocess.run(['taskkill', '/PID', str(pid), '/F', '/T'],
                           capture_output=True, encoding='gbk', errors='replace')
        except Exception:
            pass
    time.sleep(2)
else:
    print(f"WARNING: port {PORT} still occupied after 5 attempts")
    sys.exit(1)

print("Starting uvicorn...")
os.chdir(os.path.dirname(os.path.abspath(__file__)))
os.execvp(sys.executable, [sys.executable, '-m', 'uvicorn', 'app.main:app',
                            '--reload', '--host', '0.0.0.0', '--port', str(PORT)])
