#!/usr/bin/env node
'use strict';

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

const isWindows = process.platform === 'win32';
const key = `${process.platform}-${process.arch}`;
const targetMap = {
  'darwin-arm64': 'skill-cli-darwin-arm64',
  'darwin-x64': 'skill-cli-darwin-x64',
  'linux-arm64': 'skill-cli-linux-arm64',
  'linux-x64': 'skill-cli-linux-x64',
  'win32-x64': 'skill-cli-win32-x64.exe',
};

const bundledName = targetMap[key];
const bundledPath = bundledName ? path.join(__dirname, 'targets', bundledName) : null;
const fallbackName = isWindows ? 'skill-cli.exe' : 'skill-cli';
const fallbackPath = path.join(__dirname, fallbackName);

const binPath = bundledPath && fs.existsSync(bundledPath) ? bundledPath : fallbackPath;

if (!fs.existsSync(binPath)) {
  console.error(
    'skill-cli: binary not found for ' + key + '. ' +
    'Expected bundled binary: ' + (bundledName || 'unsupported-platform') + '.'
  );
  process.exit(1);
}

if (!isWindows) {
  try {
    fs.chmodSync(binPath, 0o755);
  } catch (_) {
    // ignore chmod failures on readonly installs
  }
}

const child = spawn(binPath, process.argv.slice(2), {
  stdio: 'inherit',
  shell: false,
});

child.on('close', (code) => {
  process.exit(code != null ? code : 0);
});

child.on('error', (err) => {
  console.error('skill-cli:', err.message);
  process.exit(1);
});
