#!/usr/bin/env node

/**
 * NPM wrapper script for GitCart CLI
 * Automatically selects the correct binary based on platform
 */

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

// Determine the correct binary
let binaryName;
if (process.platform === 'win32') {
  binaryName = 'gitcart-win.exe';
} else if (process.platform === 'darwin') {
  binaryName = 'gitcart-macos';
} else if (process.platform === 'linux') {
  binaryName = 'gitcart-linux';
} else {
  console.error(`Unsupported platform: ${process.platform}`);
  console.error('GitCart CLI supports Windows, macOS, and Linux');
  process.exit(1);
}

// Find the binary - try different locations for global vs local install
let binaryPath = path.join(__dirname, binaryName);

// If not found, try relative to this script (for global installs)
if (!fs.existsSync(binaryPath)) {
  // For global npm installs, __dirname might be in node_modules/.../gitcart-cli/
  binaryPath = path.join(__dirname, '..', 'gitcart-cli', binaryName);
}

// Still not found? Try looking in the package root
if (!fs.existsSync(binaryPath)) {
  // Find package.json to determine package root
  let currentDir = __dirname;
  while (currentDir !== path.dirname(currentDir)) {
    const pkgPath = path.join(currentDir, 'package.json');
    if (fs.existsSync(pkgPath)) {
      try {
        const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
        if (pkg.name === 'gitcart-cli') {
          binaryPath = path.join(currentDir, binaryName);
          break;
        }
      } catch (error) {
        // Ignore and continue searching
      }
    }
    currentDir = path.dirname(currentDir);
  }
}

// Check if binary exists
if (!fs.existsSync(binaryPath)) {
  console.error(`Binary not found: ${binaryPath}`);
  console.error(`Expected binary for ${process.platform}: ${binaryName}`);
  console.error('Please reinstall gitcart-cli');
  process.exit(1);
}

// Make sure binary is executable (Unix-like systems)
if (process.platform !== 'win32') {
  try {
    fs.chmodSync(binaryPath, '755');
  } catch (error) {
    // Ignore permission errors
  }
}

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

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

// Handle errors
child.on('error', (err) => {
  console.error('Failed to start GitCart CLI:', err.message);
  process.exit(1);
});