#!/usr/bin/env node

/**
 * ls-plus - Enhanced ls command with modern features
 * 
 * This is the main entry point for the npm package.
 * The actual binary execution is handled by the bin/lsp script.
 */

const { runBinary } = require('./bin/lsp');
const { spawn } = require('child_process');
const path = require('path');

// Export the main function for programmatic use
module.exports = {
  runBinary,
  
  // Package information
  version: require('./package.json').version,
  description: require('./package.json').description,
  
  // Helper function to run ls-plus programmatically with Promise support
  run: function(args = []) {
    return new Promise((resolve, reject) => {
      const platform = process.platform;
      const binaryName = platform === 'win32' ? 'ls-plus.exe' : 'ls-plus';
      const binaryPath = path.join(__dirname, 'bin', binaryName);
      
      const child = spawn(binaryPath, ['lsp', ...args], {
        stdio: 'pipe'
      });
      
      let stdout = '';
      let stderr = '';
      
      child.stdout?.on('data', (data) => {
        stdout += data.toString();
      });
      
      child.stderr?.on('data', (data) => {
        stderr += data.toString();
      });
      
      child.on('error', reject);
      
      child.on('exit', (code) => {
        if (code === 0) {
          resolve({ stdout, stderr });
        } else {
          reject(new Error(`Process exited with code ${code}: ${stderr}`));
        }
      });
    });
  },
  
  // Sync version for backward compatibility
  runSync: function(args = []) {
    const originalArgv = process.argv;
    process.argv = ['node', 'lsp', ...args];
    
    try {
      runBinary();
    } finally {
      process.argv = originalArgv;
    }
  }
};

// If called directly, run the binary
if (require.main === module) {
  runBinary();
}