/**
 * Locates pre-compiled sidecar binaries shipped inside the npm package.
 * Returns null when running from a git checkout without compiled binaries.
 */

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

const PKG_DIR = path.resolve(__dirname, '..');

function platformKey() {
  const p = process.platform;
  const a = process.arch;
  if (p === 'linux') return a === 'arm64' ? 'linux-arm64' : 'linux-x64';
  if (p === 'darwin') return 'darwin-arm64'; // arm64 binary runs via Rosetta on Intel
  if (p === 'win32') return 'win-x64';
  return null;
}

function ensureExecutable(filePath) {
  if (process.platform === 'win32') return;
  try {
    fs.chmodSync(filePath, 0o755);
  } catch {}
}

function getBinary(name) {
  // Test override: lets the test suite stand up a stub binary anywhere.
  // Only honored for the cielara-code sidecar; other names are unaffected.
  if (name === 'cielara-code' && process.env.CIELARA_CODE_BIN) {
    const override = process.env.CIELARA_CODE_BIN;
    if (fs.existsSync(override)) {
      ensureExecutable(override);
      return override;
    }
  }
  const key = platformKey();
  if (!key) return null;
  const ext = process.platform === 'win32' ? '.exe' : '';
  const bin = path.join(PKG_DIR, 'cielara', key, `${name}${ext}`);
  if (!fs.existsSync(bin)) return null;
  ensureExecutable(bin);
  // Also fix sibling binaries (e.g. leiden_helper) that npm strips +x from.
  const dir = path.dirname(bin);
  try {
    for (const f of fs.readdirSync(dir)) {
      ensureExecutable(path.join(dir, f));
    }
  } catch {}
  return bin;
}

module.exports = { getBinary };
