#!/usr/bin/env node
import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const require = createRequire(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url));

function resolvePackageJson(packageName) {
  try {
    return require.resolve(packageName + '/package.json');
  } catch {
    return undefined;
  }
}

function findInstallRoot(packageJsonPath) {
  let dir = path.dirname(packageJsonPath);
  while (dir !== path.parse(dir).root) {
    const parent = path.dirname(dir);
    if (path.basename(parent) === 'node_modules') {
      return path.dirname(parent);
    }
    dir = parent;
  }
  return undefined;
}

const chromeDevtoolsMcpPackageJson = resolvePackageJson('chrome-devtools-mcp');
if (chromeDevtoolsMcpPackageJson) {
  const installRoot = findInstallRoot(chromeDevtoolsMcpPackageJson);
  const patchDir = path.join(__dirname, 'patches');
  if (!installRoot || !existsSync(patchDir)) {
    process.exit(0);
  }
  const relativePatchDir = path.relative(installRoot, patchDir) || '.';
  const patchPackageBin = require.resolve('patch-package/index.js');
  const result = spawnSync(
    process.execPath,
    [patchPackageBin, '--patch-dir', relativePatchDir, '--error-on-fail'],
    { cwd: installRoot, stdio: 'inherit' },
  );
  if (result.signal) {
    process.kill(process.pid, result.signal);
  } else {
    process.exit(result.status ?? 1);
  }
}
