import http from 'node:http';
import { spawn, execSync } from 'node:child_process';

export async function isChromeDebugReachable(port = 9222) {
  return new Promise((resolve) => {
    const req = http.get(`http://localhost:${port}/json/version`, (res) => {
      resolve(res.statusCode === 200);
      res.resume();
    });
    req.on('error', () => resolve(false));
    req.setTimeout(1000, () => { req.destroy(); resolve(false); });
  });
}

export async function launchChromeDebug(port = 9222, headless = false) {
  const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  const USER_DATA = `/tmp/chrome-sdd-debug${port !== 9222 ? '-' + port : ''}`;
  const DEBUG_ARGS = [
    `--remote-debugging-port=${port}`, '--no-first-run', `--user-data-dir=${USER_DATA}`,
    ...(headless ? ['--headless=new', '--disable-gpu', '--no-sandbox', '--disable-dev-shm-usage'] : []),
  ];
  const portFlag = `"remote-debugging-port=${port}"`;
  try {
    if (process.platform === 'darwin') {
      try { execSync(`pkill -f ${portFlag}`, { stdio: 'ignore', timeout: 3000 }); } catch {}
      await sleep(1500);
      const bin = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
      spawn(bin, DEBUG_ARGS, { detached: true, stdio: 'ignore' }).unref();
    } else if (process.platform === 'win32') {
      try { execSync(`taskkill /F /FI "COMMANDLINE eq *remote-debugging-port=${port}*"`, { stdio: 'ignore', timeout: 3000 }); } catch {}
      await sleep(1000);
      const bin = 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';
      spawn(bin, DEBUG_ARGS, { detached: true, stdio: 'ignore' }).unref();
    } else {
      try { execSync(`pkill -f ${portFlag}`, { stdio: 'ignore', timeout: 3000 }); } catch {}
      await sleep(1000);
      spawn('google-chrome', DEBUG_ARGS, { detached: true, stdio: 'ignore' }).unref();
    }
  } catch {}
}

export function cdpHttpGet(cdpPath, port = 9222) {
  return new Promise((resolve) => {
    const req = http.get(`http://localhost:${port}${cdpPath}`, (res) => {
      const chunks = [];
      res.on('data', c => chunks.push(c));
      res.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString())); } catch { resolve(null); } });
    });
    req.on('error', () => resolve(null));
    req.setTimeout(3000, () => { req.destroy(); resolve(null); });
  });
}
