'use strict';

const path = require('path');
const fs = require('fs');

function getRgPath() {
  const platform = process.platform;
  const arch = process.arch;

  // Normalize arch name
  const normalizedArch = arch === 'x64' ? 'x64' : arch;
  const platformKey = `${platform}-${normalizedArch}`;

  // Define binary names by platform
  const binaryName = platform === 'win32' ? 'rg.exe' : 'rg';

  // Try platform-specific binary first
  const platformSpecificPath = path.join(__dirname, `../bin/${platformKey}-${binaryName}`);
  if (fs.existsSync(platformSpecificPath)) {
    return platformSpecificPath;
  }

  // Fall back to standard binary name
  const standardPath = path.join(__dirname, `../bin/${binaryName}`);
  if (fs.existsSync(standardPath)) {
    return standardPath;
  }

  // List available binaries for better error message
  const binDir = path.join(__dirname, '../bin');
  let availableBinaries = [];
  if (fs.existsSync(binDir)) {
    availableBinaries = fs.readdirSync(binDir);
  }

  throw new Error(`Ripgrep binary not found for platform ${platform}-${arch}.
Available binaries: ${availableBinaries.join(', ')}
Looking for: ${platformKey}-${binaryName} or ${binaryName}
Please ensure the binary is available for your platform.`);
}

module.exports.rgPath = getRgPath();
