#!/usr/bin/env npx tsx
import { spawn } from 'child_process';
import * as readline from 'readline';
import * as path from 'path';
import * as fs from 'fs';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function getDistPath(): string {
    // 1. Try to find dist/index.js by traversing up from the current directory
    let current = process.cwd();

    while (true) {
        const candidate = path.join(current, 'mcp-graphql-enhanced', 'dist', 'index.js');
        if (fs.existsSync(candidate)) {
            console.log(`[INFO] Found local project version: ${candidate}`);
            return candidate;
        }
        const parent = path.dirname(current);
        if (parent === current) break; // Reached filesystem root
        current = parent;
    }

    // 2. If not found locally, use the version installed in node_modules
    console.log(`[INFO] Local build not found, using installed version.`);
    return path.join(
        path.dirname(require.resolve('@letoribo/mcp-graphql-enhanced/package.json')),
        'dist/index.js'
    );
}

console.log('\n--- MCP GraphQL Enhanced CLI ---');
console.log('1. Terminal (HTTP GraphQL Gateway)');
console.log('2. MCP Inspector (stdio)');

rl.question('\nSelect mode (1 or 2): ', (answer) => {
  if (answer !== '1' && answer !== '2') {
    console.log('Invalid selection. Please enter 1 or 2.');
    rl.close();
    return;
  }

  const distPath = getDistPath();
  
  if (!fs.existsSync(distPath)) {
    console.error(`\n[ERROR] Build file not found at: ${distPath}`);
    console.error('Please ensure the project is compiled (npm run build).');
    rl.close();
    return;
  }

  if (answer === '1') {
    process.env.ENABLE_HTTP = 'true';
    console.log(`Launching...`);
    // Run with the current working directory to ensure config files are picked up
    spawn('node', [distPath], { stdio: 'inherit', cwd: process.cwd() });
  } else {
    console.log('Launching in Inspector mode...');
    spawn('npx', ['-y', '@modelcontextprotocol/inspector', 'node', distPath], { 
      stdio: 'inherit',
      cwd: process.cwd()
    });
  }

  rl.close();
});