#!/usr/bin/env node
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/index.ts
var src_exports = {};
__export(src_exports, {
  program: () => program
});
module.exports = __toCommonJS(src_exports);
var import_commander = require("commander");
var fs = __toESM(require("fs/promises"));
var path = __toESM(require("path"));
var import_child_process = require("child_process");
var readline = __toESM(require("readline"));
var program = new import_commander.Command();
var promptUser = (question) => {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  return new Promise((resolve2) => {
    rl.question(question, (answer) => {
      rl.close();
      resolve2(answer.trim());
    });
  });
};
program.version("0.1.0").description("A CLI for scaffolding and managing BEEP MCP servers");
program.command("hello").description("Prints a greeting to verify CLI installation").action(() => {
  console.log("Hello, from the BEEP CLI!");
});
program.command("init-mcp").description("Scaffolds a new BEEP MCP server with payment tools").requiredOption("--mode <https|stdio>", "Communication protocol: https (web agents) or stdio (desktop clients)").option("--path <directory>", "Target directory (defaults to current directory)").action(async (options) => {
  const targetPath = options.path ? path.resolve(options.path) : process.cwd();
  const templatePath = path.resolve(__dirname, "../templates");
  console.log(`Scaffolding new BEEP MCP server at: ${targetPath}`);
  try {
    const ensureDir = async (dir) => {
      await fs.mkdir(dir, { recursive: true });
    };
    const mergePackageJson = async (srcPkgPath, destPkgPath) => {
      const srcRaw = await fs.readFile(srcPkgPath, "utf-8");
      const src = JSON.parse(srcRaw);
      let dest = {};
      try {
        const destRaw = await fs.readFile(destPkgPath, "utf-8");
        dest = JSON.parse(destRaw);
      } catch (e) {
        await fs.writeFile(destPkgPath, JSON.stringify(src, null, 2) + "\n");
        console.log("  - Created package.json");
        return;
      }
      const merged = { ...dest };
      const mergeField = (field) => {
        const srcField = src[field] || {};
        const destField = dest[field] || {};
        const out = { ...destField };
        for (const [k, v] of Object.entries(srcField)) {
          if (!(k in out)) {
            out[k] = v;
          }
        }
        if (Object.keys(out).length > 0) merged[field] = out;
      };
      mergeField("dependencies");
      mergeField("devDependencies");
      mergeField("scripts");
      await fs.writeFile(destPkgPath, JSON.stringify(merged, null, 2) + "\n");
      console.log("  - Updated package.json (merged dependencies, devDependencies, scripts)");
    };
    const copyTemplates = async (srcDir, destDir) => {
      await ensureDir(destDir);
      const entries = await fs.readdir(srcDir, { withFileTypes: true });
      for (const entry of entries) {
        const srcPath = path.join(srcDir, entry.name);
        const destPath = path.join(destDir, entry.name);
        if (entry.isDirectory()) {
          await copyTemplates(srcPath, destPath);
        } else if (entry.isFile()) {
          if (entry.name === "package.json") {
            await mergePackageJson(srcPath, path.join(destDir, "package.json"));
            continue;
          }
          if (entry.name === "server.ts") {
            console.log("  - Skipped template server.ts (replaced by mcp-server.ts)");
            continue;
          }
          try {
            await fs.access(destPath);
            console.log(`  - Skipped existing ${path.relative(destDir, destPath)}`);
            continue;
          } catch (_) {
          }
          const fileData = await fs.readFile(srcPath);
          await ensureDir(path.dirname(destPath));
          await fs.writeFile(destPath, fileData);
          console.log(`  - Added ${path.relative(destDir, destPath)}`);
        }
      }
    };
    await copyTemplates(templatePath, targetPath);
    console.log("\n\u{1F4E6} Installing dependencies...");
    try {
      (0, import_child_process.execSync)("npm install", {
        cwd: targetPath,
        stdio: "inherit"
      });
      console.log("\u2705 Dependencies installed successfully");
    } catch (error) {
      console.log('\u26A0\uFE0F  Failed to install dependencies automatically. Please run "npm install" manually.');
    }
    console.log("\n\u{1F511} Setting up your environment...");
    const apiKey = await promptUser("Enter your BEEP API key (or press Enter to skip): ");
    const envExamplePath = path.join(targetPath, ".env.example");
    const envPath = path.join(targetPath, ".env");
    let envContent = await fs.readFile(envExamplePath, "utf-8");
    envContent = envContent.replace(
      /^COMMUNICATION_MODE=.*/m,
      `COMMUNICATION_MODE=${options.mode}`
    );
    if (apiKey) {
      envContent = envContent.replace(
        /^BEEP_API_KEY=.*/m,
        `BEEP_API_KEY=${apiKey}`
      );
    }
    try {
      const existingEnv = await fs.readFile(envPath, "utf-8");
      let updatedEnv = existingEnv;
      let hasUpdates = false;
      if (!existingEnv.includes("COMMUNICATION_MODE=")) {
        updatedEnv += `
# BEEP MCP Server configuration
COMMUNICATION_MODE=${options.mode}
`;
        hasUpdates = true;
      }
      if (apiKey && !existingEnv.includes("BEEP_API_KEY=")) {
        updatedEnv += `BEEP_API_KEY=${apiKey}
`;
        hasUpdates = true;
      }
      if (hasUpdates) {
        await fs.writeFile(envPath, updatedEnv);
        console.log("  - Updated existing .env with BEEP configuration");
      } else {
        console.log("  - .env already contains BEEP configuration, leaving unchanged");
      }
    } catch (_) {
      await fs.writeFile(envPath, envContent);
      console.log("  - Created .env with your configuration");
    }
    try {
      await fs.unlink(envExamplePath);
    } catch (_) {
    }
    console.log(`
\u2705 BEEP MCP server created at: ${targetPath}`);
    console.log("\nNext steps:");
    console.log(`
1. Navigate to your new server:`);
    console.log(`   cd ${options.path || path.basename(targetPath)}`);
    if (!apiKey) {
      console.log(`
2. Configure your API key:`);
      console.log(`   Add your BEEP_API_KEY to the .env file.`);
      console.log(`
3. Build and run the server:`);
    } else {
      console.log(`
2. Build and run the server:`);
    }
    console.log(`   npm run build && npm start`);
  } catch (error) {
    console.error("\n\u274C An error occurred during scaffolding:", error);
  }
});
if (require.main === module) {
  program.command("integrate <path>").description("Add BEEP payment tools to an existing MCP project").action(async (targetPath) => {
    const fullTargetPath = path.resolve(targetPath);
    console.log(`
Integrating BEEP files into: ${fullTargetPath}`);
    try {
      const templatesDir = path.resolve(__dirname, "../templates");
      const toolTemplateDir = path.resolve(templatesDir, "src/tools");
      const targetToolsDir = path.resolve(fullTargetPath, "tools");
      await fs.mkdir(targetToolsDir, { recursive: true });
      const toolFile = "checkBeepApi.ts";
      await fs.copyFile(
        path.join(toolTemplateDir, toolFile),
        path.join(targetToolsDir, toolFile)
      );
      const sdkTarball = "beep-sdk-core-0.1.0.tgz";
      await fs.copyFile(
        path.join(templatesDir, sdkTarball),
        path.join(fullTargetPath, sdkTarball)
      );
      console.log("\n\u2705 BEEP integration files created!");
      console.log("\nNext steps:");
      console.log("\n1. Add the BEEP SDK dependency to your project.");
      console.log("   In your package.json, add the following to your 'dependencies':");
      console.log("   '@beep-it/sdk-core': 'file:beep-sdk-core-0.1.0.tgz'");
      console.log("\n2. Run 'npm install' or 'pnpm install' to install the new dependency.");
      console.log("\n3. Integrate the BEEP tool into your server file:");
      console.log("   import { checkBeepApi } from './tools/checkBeepApi'; // Adjust path if needed");
      console.log("   // Add the tool to your MCP's tool registry.");
    } catch (error) {
      console.error("\n\u274C Failed to integrate BEEP files:", error);
    }
  });
  program.parse(process.argv);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  program
});
