#!/usr/bin/env node

import { spawn } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { existsSync } from 'fs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Try to find the binary in different locations
const possiblePaths = [
  // From npm package (installed)
  join(__dirname, '..', 'target', 'release', 'mk3-tui'),
  join(__dirname, '..', 'target', 'release', 'mk3-tui.exe'),
  // From global npm install (in PATH)
  process.platform === 'win32' ? 'mk3-tui.exe' : 'mk3-tui',
  // Development build (local)
  join(__dirname, '..', '..', '..', 'apps', 'mk3-tui', 'target', 'release', 'mk3-tui'),
  join(__dirname, '..', '..', '..', 'apps', 'mk3-tui', 'target', 'release', 'mk3-tui.exe'),
];

let binaryPath = null;
for (const testPath of possiblePaths) {
  // Check if it's a PATH command (string without slashes)
  if (!testPath.includes('/') && !testPath.includes('\\')) {
    // Try to find in PATH
    try {
      const { execSync } = await import('child_process');
      const whichCmd = process.platform === 'win32' ? 'where' : 'which';
      execSync(`${whichCmd} ${testPath}`, { stdio: 'ignore' });
      binaryPath = testPath;
      break;
    } catch {
      continue;
    }
  } else if (existsSync(testPath)) {
    binaryPath = testPath;
    break;
  }
}

if (!binaryPath) {
  console.error('Error: mk3-tui binary not found.');
  console.error('Please run: cd apps/mk3-tui && cargo build --release');
  process.exit(1);
}

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

child.on('error', (err) => {
  console.error('Failed to start mk3-tui:', err);
  process.exit(1);
});

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

