#!/usr/bin/env node

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

// Platform detection
const platform = `${process.platform}-${process.arch}`;

// Binary mapping for supported platforms
const binaryMap = {
  'win32-x64': 'win-x64/mcpd.exe',
  'linux-x64': 'linux-x64/mcpd',
  'darwin-x64': 'darwin-x64/mcpd',
  'darwin-arm64': 'darwin-arm64/mcpd'
};

// Check if platform is supported
const binary = binaryMap[platform];
if (!binary) {
  console.error(`Error: Unsupported platform: ${platform}`);
  console.error('');
  console.error('Supported platforms:');
  console.error('  - Windows x64');
  console.error('  - Linux x64 (coming soon)');
  console.error('  - macOS x64 (coming soon)');
  console.error('  - macOS ARM64 (coming soon)');
  process.exit(1);
}

// Get binary path
const binaryPath = path.join(__dirname, binary);

// Check if binary exists
if (!fs.existsSync(binaryPath)) {
  console.error(`Error: Binary not found for platform ${platform}`);
  console.error(`Expected path: ${binaryPath}`);
  console.error('');
  console.error('This platform is not yet supported. Please check for updates:');
  console.error('  npm update -g mcpd');
  process.exit(1);
}

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

// Handle spawn errors
child.on('error', (err) => {
  console.error(`Error: Failed to execute binary: ${err.message}`);
  console.error('');
  console.error('This might be due to:');
  console.error('  - Insufficient permissions');
  console.error('  - Corrupted binary file');
  console.error('  - Missing dependencies');
  process.exit(1);
});

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

// Forward termination signals
process.on('SIGINT', () => {
  child.kill('SIGINT');
});

process.on('SIGTERM', () => {
  child.kill('SIGTERM');
});
