#!/usr/bin/env node

const { spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const os = require('os');

const platformMap = {
  darwin: 'darwin',
  linux: 'linux',
  win32: 'windows'
};

const archMap = {
  x64: 'amd64',
  arm64: 'arm64',
  ia32: '386'
};

const platform = platformMap[os.platform()] || os.platform();
const arch = archMap[os.arch()] || os.arch();
const ext = platform === 'windows' ? '.exe' : '';

// Binary name in prebuilds
const binaryName = `sk-${platform}-${arch}${ext}`;

const scriptPath = fs.realpathSync(__filename);
const scriptDir = path.dirname(scriptPath);

// Look for binary in prebuilds folder (sibling to bin folder)
const prebuildsDir = path.join(scriptDir, '..', 'prebuilds');
const binaryPath = path.join(prebuildsDir, binaryName);

// Fallback: try without arch suffix for backwards compatibility
const fallbackBinary = path.join(prebuildsDir, `sk-${platform}-x64${ext}`);

let actualBinary = binaryPath;
if (!fs.existsSync(binaryPath) && fs.existsSync(fallbackBinary)) {
  actualBinary = fallbackBinary;
}

if (!fs.existsSync(actualBinary)) {
  console.error(`Could not find sk binary: ${binaryName}`);
  console.error('Please reinstall: npm install -g @hiu_yan_chong/sk-cli');
  process.exit(1);
}

// Run the binary with all arguments
const result = spawnSync(actualBinary, process.argv.slice(2), {
  stdio: 'inherit',
  shell: false,
  windowsHide: true
});

process.exit(result.status || 0);
