#!/usr/bin/env node
/**
 * Wrapper for @azure-devops/mcp that fetches an ADO token via the shared
 * az-first provider chain and sets AZURE_DEVOPS_EXT_PAT before launching the
 * MCP server.
 *
 * P-b3f8e1a5: @azure-devops/mcp is pinned in package.json and resolved from
 * local node_modules. We spawn process.execPath against the resolved bin file
 * instead of going through npx/npx.cmd. This (a) eliminates the per-cold-start
 * network fetch that ran with AZURE_DEVOPS_EXT_PAT in env, and (b) avoids the
 * Windows .cmd shim chain that crashes the runtime under spawn.
 */
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const { acquireAdoTokenSync } = require('./ado-token');

const PKG_NAME = '@azure-devops/mcp';
const BIN_NAME = 'mcp-server-azuredevops';

function resolveMcpBin() {
  const pkgJsonPath = require.resolve(`${PKG_NAME}/package.json`);
  const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
  const binField = pkgJson.bin;
  const relBin = typeof binField === 'string' ? binField : binField && binField[BIN_NAME];
  if (!relBin) {
    throw new Error(`${PKG_NAME} package.json is missing bin entry "${BIN_NAME}"`);
  }
  return path.resolve(path.dirname(pkgJsonPath), relBin);
}

let token;
try {
  token = acquireAdoTokenSync().token;
} catch (e) {
  process.stderr.write('ado-mcp-wrapper: ADO auth failed: ' + e.message + '\n');
  process.stderr.write('ado-mcp-wrapper: Run "az login" or refresh azureauth manually, then retry\n');
  process.exit(1);
}

let binPath;
try {
  binPath = resolveMcpBin();
} catch (e) {
  process.stderr.write('ado-mcp-wrapper: failed to resolve ' + PKG_NAME + ': ' + e.message + '\n');
  process.stderr.write('ado-mcp-wrapper: run "npm install" in the minions checkout to restore the pinned dependency\n');
  process.exit(1);
}

const args = process.argv.slice(2);
const child = spawn(process.execPath, [binPath, ...args], {
  stdio: 'inherit',
  env: { ...process.env, AZURE_DEVOPS_EXT_PAT: token, AZURE_DEVOPS_EXT_AZURE_RM_PAT: token },
  windowsHide: true,
  shell: false,
});

child.on('exit', (code) => process.exit(code || 0));
child.on('error', (err) => {
  process.stderr.write('ado-mcp-wrapper: ' + err.message + '\n');
  process.exit(1);
});

