#!/usr/bin/env node

/**
 * SwarmHack CLI Wrapper
 * Executes the native binary with all arguments passed through
 */

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

// Determine binary path based on platform
function getBinaryPath() {
  const platform = os.platform();
  const arch = os.arch();

  let binaryName = 'swarmhack';
  if (platform === 'win32') {
    binaryName = 'swarmhack.exe';
  }

  // Check multiple locations
  const locations = [
    // Installed in package
    path.join(__dirname, '..', 'native', `${platform}-${arch}`, binaryName),
    // Fallback to generic
    path.join(__dirname, '..', 'native', binaryName),
    // Development: in release folder
    path.join(__dirname, '..', '..', binaryName),
  ];

  for (const loc of locations) {
    if (fs.existsSync(loc)) {
      return loc;
    }
  }

  // Not found - show helpful error
  console.error(`
SwarmHack binary not found for ${platform}-${arch}

This could mean:
  1. The postinstall script failed to download the binary
  2. Your platform is not supported yet

Supported platforms:
  - linux-x64
  - linux-arm64
  - darwin-x64 (macOS Intel)
  - darwin-arm64 (macOS Apple Silicon)
  - win32-x64 (Windows)

To manually install:
  1. Download binary from: https://github.com/prancer-io/swarmhack/releases
  2. Place in: ${path.join(__dirname, '..', 'native', `${platform}-${arch}`)}
  3. Make executable: chmod +x swarmhack

Or use Docker instead:
  docker run --rm prancer/swarmhack:0.1.0 --help
`);
  process.exit(1);
}

// Get binary path
const binaryPath = getBinaryPath();

// Get config path - bundled with npm package
function getConfigPath() {
  // Check if user already specified --config
  const args = process.argv.slice(2);
  if (args.includes('--config') || args.includes('-c')) {
    return null; // User specified their own config
  }

  // Check for local config first (user's project)
  const localConfig = path.join(process.cwd(), 'config', 'swarmhack.yaml');
  if (fs.existsSync(localConfig)) {
    return localConfig;
  }

  // Use bundled config from npm package
  const bundledConfig = path.join(__dirname, '..', 'config', 'swarmhack.yaml');
  if (fs.existsSync(bundledConfig)) {
    return bundledConfig;
  }

  return null;
}

// Spawn the binary with all arguments
const args = process.argv.slice(2);
const configPath = getConfigPath();

// Add config flag if we have a bundled config and user didn't specify one
const finalArgs = configPath ? ['--config', configPath, ...args] : args;

const child = spawn(binaryPath, finalArgs, {
  stdio: 'inherit',
  env: {
    ...process.env,
    // Ensure proper terminal handling
    TERM: process.env.TERM || 'xterm-256color',
  },
});

// Forward exit code
child.on('close', (code) => {
  process.exit(code || 0);
});

child.on('error', (err) => {
  if (err.code === 'ENOENT') {
    console.error(`Error: Binary not found at ${binaryPath}`);
  } else if (err.code === 'EACCES') {
    console.error(`Error: Binary not executable. Run: chmod +x ${binaryPath}`);
  } else {
    console.error(`Error executing SwarmHack: ${err.message}`);
  }
  process.exit(1);
});
