#!/usr/bin/env node

/**
 * npm wrapper that launches the Python ai4gh MCP server via stdio.
 * Usage: npx @ai4gh/mcp
 *
 * Tries `uvx ai4gh mcp serve` first (recommended),
 * then falls back to `python3 -m ai4gh.cli.main mcp serve`.
 */

import { spawn, type ChildProcess } from "child_process";

function trySpawn(cmd: string, args: string[]): Promise<ChildProcess> {
  return new Promise((resolve, reject) => {
    const child = spawn(cmd, args, { stdio: "inherit" });

    // If the command doesn't exist, we get an 'error' event before 'exit'
    child.on("error", (err: NodeJS.ErrnoException) => {
      if (err.code === "ENOENT") {
        reject(new Error(`Command not found: ${cmd}`));
      } else {
        reject(err);
      }
    });

    // Give a brief moment for ENOENT to fire before considering it started
    setTimeout(() => resolve(child), 100);
  });
}

async function main(): Promise<void> {
  let child: ChildProcess;

  try {
    child = await trySpawn("uvx", ["ai4gh", "mcp", "serve"]);
  } catch {
    try {
      child = await trySpawn("python3", [
        "-m",
        "ai4gh.cli.main",
        "mcp",
        "serve",
      ]);
    } catch {
      console.error(
        "Error: Python not found. Install Python 3.10+ and ai4gh, or use: pip install ai4gh"
      );
      process.exit(1);
    }
  }

  child.on("exit", (code: number | null) => {
    process.exit(code ?? 1);
  });
}

main().catch((err: Error) => {
  console.error(err.message);
  process.exit(1);
});
