#!/usr/bin/env node

/**
 * NPM wrapper for ticket command
 * 
 * This script delegates to the Python ticket CLI
 */

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

// Check for Python
function checkPython() {
  const pythonCommands = ['python3', 'python'];
  
  for (const cmd of pythonCommands) {
    try {
      const pythonPath = which.sync(cmd);
      // Check version
      const result = spawn.sync(cmd, ['--version']);
      const version = result.stdout ? result.stdout.toString() : result.stderr.toString();
      
      if (version.includes('Python 3.') && parseInt(version.match(/3\.(\d+)/)[1]) >= 8) {
        return cmd;
      }
    } catch (e) {
      // Try next
    }
  }
  
  return null;
}

// Main execution
function main() {
  // Check Python
  const pythonCmd = checkPython();
  if (!pythonCmd) {
    console.error('Error: Python 3.8 or higher is required but not found.');
    console.error('Please install Python from https://python.org');
    process.exit(1);
  }
  
  // Run ticket command
  const args = ['-m', 'claude_mpm.scripts.ticket', ...process.argv.slice(2)];
  const result = spawn(pythonCmd, args, { stdio: 'inherit' });
  
  result.on('exit', (code) => {
    process.exit(code || 0);
  });
}

// Handle errors
process.on('uncaughtException', (err) => {
  console.error('Error:', err.message);
  process.exit(1);
});

main();