import { execSync } from 'node:child_process';
import { resolveDevApiPort } from './resolve-dev-api-target.mjs';

const port = process.argv[2] ?? resolveDevApiPort();

function killWindows(portNum) {
  let out = '';
  try {
    out = execSync(`netstat -ano | findstr :${portNum}`, { encoding: 'utf8' });
  } catch {
    return;
  }

  const pids = new Set();
  for (const line of out.split('\n')) {
    if (!line.includes('LISTENING')) continue;
    const pid = line.trim().split(/\s+/).at(-1);
    if (pid && pid !== '0') pids.add(pid);
  }

  for (const pid of pids) {
    try {
      console.log(`[ensure-port-free] freeing :${portNum} (PID ${pid})`);
      execSync(`taskkill /F /PID ${pid}`, { stdio: 'ignore' });
    } catch {
      // already gone
    }
  }
}

function killUnix(portNum) {
  try {
    execSync(`lsof -ti tcp:${portNum} | xargs -r kill -9`, { stdio: 'ignore' });
  } catch {
    // port already free
  }
}

if (process.platform === 'win32') killWindows(port);
else killUnix(port);
