#!/usr/bin/env node

/**
 * NPM wrapper for Onebox binary
 */

import { spawn } from 'child_process';
import { platform, arch } from 'os';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Detect platform and architecture
const platformMap = {
  'linux': 'linux',
  'darwin': 'macos',
  'win32': 'windows',
};

const archMap = {
  'x64': 'x64',
  'arm64': 'arm64',
};

const currentPlatform = platformMap[platform()];
const currentArch = archMap[arch()];

if (!currentPlatform || !currentArch) {
  console.error(`Unsupported platform: ${platform()} ${arch()}`);
  process.exit(1);
}

// Build binary name
const binaryName = `onebox-${currentPlatform}-${currentArch}${currentPlatform === 'windows' ? '.exe' : ''}`;
const binaryPath = join(__dirname, '..', 'dist', 'binaries', binaryName);

// Spawn the binary
const child = spawn(binaryPath, process.argv.slice(2), {
  stdio: 'inherit',
  windowsHide: true,
});

// Forward signals
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
signals.forEach(signal => {
  process.on(signal, () => {
    if (!child.killed) {
      child.kill(signal);
    }
  });
});

// Forward exit code
child.on('exit', (code, signal) => {
  if (signal) {
    process.kill(process.pid, signal);
  } else {
    process.exit(code || 0);
  }
});

child.on('error', (error) => {
  console.error(`Failed to start onebox: ${error.message}`);
  console.error(`Binary path: ${binaryPath}`);
  console.error('Make sure the binary was downloaded correctly.');
  console.error('Try running: npm install -g @serve.zone/onebox');
  process.exit(1);
});
