#!/usr/bin/env node

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

// Determine uvx command based on platform
const isWindows = os.platform() === 'win32';
const uvxCommand = isWindows ? 'uvx.exe' : 'uvx';

// Check if uv is installed
function checkUvInstalled() {
  try {
    execSync(isWindows ? 'where uvx' : 'which uvx', { stdio: 'ignore' });
    return true;
  } catch (error) {
    return false;
  }
}

if (!checkUvInstalled()) {
  console.error('Error: uv is not installed.');
  console.error('');
  console.error('CAST.AI MCP Server requires uv to be installed.');
  console.error('');
  console.error('Install uv:');
  console.error('  macOS/Linux: curl -LsSf https://astral.sh/uv/install.sh | sh');
  console.error('  Windows:     powershell -c "irm https://astral.sh/uv/install.ps1 | iex"');
  console.error('  Or visit:    https://docs.astral.sh/uv/getting-started/installation/');
  console.error('');
  process.exit(1);
}

// Run the Python package via uvx
const args = ['castai-mcp-server'];

// Forward all command line arguments
if (process.argv.length > 2) {
  args.push(...process.argv.slice(2));
}

const child = spawn(uvxCommand, args, {
  stdio: 'inherit',
  env: process.env,
  shell: isWindows
});

child.on('error', (error) => {
  console.error(`Failed to start castai-mcp-server: ${error.message}`);
  process.exit(1);
});

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