"""Find and kill process on port 8900."""
import subprocess, sys, os, signal

# Find PID listening on port 8900
result = subprocess.run(
    ['netstat', '-ano'],
    capture_output=True, text=True, encoding='gbk', errors='replace'
)
pids = set()
for line in result.stdout.splitlines():
    if ':8900' in line and 'LISTENING' in line:
        parts = line.split()
        pid = int(parts[-1])
        pids.add(pid)
        print(f"Found LISTENING on :8900 -> PID {pid}")

for pid in pids:
    print(f"Killing PID {pid}...")
    try:
        os.kill(pid, signal.SIGTERM)
        print(f"  SIGTERM sent to {pid}")
    except ProcessLookupError:
        print(f"  PID {pid} already gone")
    except PermissionError:
        # Try taskkill
        subprocess.run(['taskkill', '/PID', str(pid), '/F'], encoding='gbk', errors='replace')

import time
time.sleep(2)

# Verify
result2 = subprocess.run(
    ['netstat', '-ano'],
    capture_output=True, text=True, encoding='gbk', errors='replace'
)
still_listening = False
for line in result2.stdout.splitlines():
    if ':8900' in line and 'LISTENING' in line:
        still_listening = True
        print(f"Still listening: {line.strip()}")

if not still_listening:
    print("Port 8900 is now free!")
