import { exec } from 'child_process';
import { promisify } from 'util';

const execPromise = promisify(exec);

/**
 * Get the proper PATH for executing shell commands in a packaged Electron app
 * Includes common locations where Homebrew and other tools install binaries
 */
export function getEnvWithPath(): NodeJS.ProcessEnv {
  const commonPaths = [
    '/opt/homebrew/bin',      // Apple Silicon Homebrew
    '/opt/homebrew/sbin',
    '/usr/local/bin',         // Intel Homebrew
    '/usr/local/sbin',
    '/usr/bin',
    '/bin',
    '/usr/sbin',
    '/sbin'
  ];

  const existingPath = process.env.PATH || '';
  const pathArray = existingPath.split(':').filter(Boolean);

  // Add common paths if they're not already present
  for (const path of commonPaths) {
    if (!pathArray.includes(path)) {
      pathArray.unshift(path);
    }
  }

  return {
    ...process.env,
    PATH: pathArray.join(':')
  };
}

/**
 * Promisified exec with proper PATH environment for packaged Electron apps
 */
export async function execAsync(
  command: string,
  options?: Parameters<typeof execPromise>[1]
): Promise<{ stdout: string; stderr: string }> {
  const result = await execPromise(command, {
    ...options,
    env: getEnvWithPath(),
    encoding: 'utf8'
  });

  return {
    stdout: result.stdout.toString(),
    stderr: result.stderr.toString()
  };
}
