#!/usr/bin/env node

const { execFileSync } = require("child_process");
const path = require("path");
const fs = require("fs");

const PLATFORMS = {
  "darwin-arm64": "@mentedb/mcp-darwin-arm64",
  "darwin-x64": "@mentedb/mcp-darwin-x64",
  "linux-arm64": "@mentedb/mcp-linux-arm64",
  "linux-x64": "@mentedb/mcp-linux-x64",
  "win32-x64": "@mentedb/mcp-win32-x64",
};

function getBinaryPath() {
  const platformKey = `${process.platform}-${process.arch}`;
  const pkg = PLATFORMS[platformKey];

  if (!pkg) {
    console.error(
      `Unsupported platform: ${process.platform}-${process.arch}\n` +
      `Supported: ${Object.keys(PLATFORMS).join(", ")}`
    );
    process.exit(1);
  }

  try {
    const pkgPath = require.resolve(`${pkg}/package.json`);
    const binDir = path.dirname(pkgPath);
    const binName = process.platform === "win32" ? "mentedb-mcp.exe" : "mentedb-mcp";
    const binPath = path.join(binDir, "bin", binName);

    if (fs.existsSync(binPath)) {
      return binPath;
    }
  } catch (_e) {
    // Package not installed
  }

  console.error(
    `Could not find the mentedb-mcp binary for ${platformKey}.\n` +
    `Try reinstalling: npm install -g mentedb-mcp`
  );
  process.exit(1);
}

const binPath = getBinaryPath();

try {
  execFileSync(binPath, process.argv.slice(2), {
    stdio: "inherit",
    env: process.env,
  });
} catch (e) {
  if (e.status !== undefined) {
    process.exit(e.status);
  }
  throw e;
}
