// kill-port-and-start.js

const { execSync, spawn } = require('child_process');
const os = require('os');

const PORT = 3000;

function killPort(port) {
  try {
    if (os.platform() === 'win32') {
      // Windows logic
      const output = execSync(`netstat -ano | findstr :${port}`).toString();
      const lines = output.trim().split('\n');
      const pids = new Set();

      lines.forEach(line => {
        const parts = line.trim().split(/\s+/);
        const pid = parts[parts.length - 1];
        pids.add(pid);
      });

      pids.forEach(pid => {
        execSync(`taskkill /PID ${pid} /F`);
        console.log(`✅ Killed port ${port}`);
      });
    } else {
      // macOS/Linux logic
      const pid = execSync(`lsof -ti tcp:${port}`).toString().trim();
      if (pid) {
        execSync(`kill -9 ${pid}`);
        console.log(`✅ Killed port ${port}`);
      }
    }
  } catch (error) {
    // console.log(`ℹ️ No process was using port ${port}`);
  }
}

function startNextApp() {
  // console.log(`🚀 Starting Next.js on port ${PORT}...\n`);
  const child = spawn('npx', ['next', 'start'], {
    stdio: 'inherit',
    shell: true,
  });

  child.on('close', code => {
    // console.log(`ℹ️ Next.js process exited with code ${code}`);
  });
}

killPort(PORT);
startNextApp();
