import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
async function ensureBootstrap() {
  try {
    const { getDiRegistrars } = await import("@open-mercato/shared/lib/di/container");
    getDiRegistrars();
    return;
  } catch {
  }
  try {
    const { bootstrapFromAppRoot } = await import("@open-mercato/shared/lib/bootstrap/dynamicLoader");
    await bootstrapFromAppRoot();
  } catch (error) {
    console.error("[MCP] Bootstrap failed:", error instanceof Error ? error.message : error);
  }
}
function parseArgs(rest) {
  const args = {};
  for (let i = 0; i < rest.length; i++) {
    const arg = rest[i];
    if (!arg?.startsWith("--")) continue;
    const [key, value] = arg.replace(/^--/, "").split("=");
    if (value !== void 0) {
      args[key] = value;
    } else if (rest[i + 1] && !rest[i + 1].startsWith("--")) {
      args[key] = rest[i + 1];
      i++;
    } else {
      args[key] = true;
    }
  }
  return args;
}
const mcpServe = {
  command: "mcp:serve",
  async run(rest) {
    const args = parseArgs(rest);
    const apiKey = String(args["api-key"] ?? args.apiKey ?? "") || null;
    const tenantId = String(args.tenant ?? args.tenantId ?? "") || null;
    const organizationId = String(args.org ?? args.organizationId ?? "") || null;
    const userId = String(args.user ?? args.userId ?? "") || null;
    const debug = args.debug === true || args.debug === "true";
    if (!apiKey && !tenantId) {
      console.error("Usage: mercato ai_assistant mcp:serve [options]");
      console.error("");
      console.error("Authentication (choose one):");
      console.error("  --api-key <secret>   API key secret for authentication (recommended)");
      console.error("  --tenant <id>        Tenant ID (for manual context)");
      console.error("");
      console.error("Options (with --tenant):");
      console.error("  --org <id>           Organization ID (optional)");
      console.error("  --user <id>          User ID for ACL (optional, uses superadmin if not set)");
      console.error("");
      console.error("Common options:");
      console.error("  --debug              Enable debug logging");
      console.error("");
      console.error("Examples:");
      console.error("  mercato ai_assistant mcp:serve --api-key omk_xxxx.yyyy...");
      console.error("  mercato ai_assistant mcp:serve --tenant 123e4567-e89b-12d3-a456-426614174000");
      return;
    }
    await ensureBootstrap();
    const container = await createRequestContainer();
    const { runMcpServer } = await import("./lib/mcp-server.js");
    if (apiKey) {
      await runMcpServer({
        config: {
          name: "open-mercato-mcp",
          version: "0.1.0",
          debug
        },
        container,
        apiKeySecret: apiKey
      });
    } else {
      await runMcpServer({
        config: {
          name: "open-mercato-mcp",
          version: "0.1.0",
          debug
        },
        container,
        context: {
          tenantId,
          organizationId,
          userId
        }
      });
    }
  }
};
const MCP_DEFAULT_PORT = 3001;
const mcpServeHttp = {
  command: "mcp:serve-http",
  async run(rest) {
    const args = parseArgs(rest);
    const portArg = parseInt(String(args.port ?? ""), 10);
    const port = !portArg || isNaN(portArg) ? MCP_DEFAULT_PORT : portArg;
    const debug = args.debug === true || args.debug === "true";
    await ensureBootstrap();
    const container = await createRequestContainer();
    const { runMcpHttpServer } = await import("./lib/http-server.js");
    await runMcpHttpServer({
      config: {
        name: "open-mercato-mcp",
        version: "0.1.0",
        debug
      },
      container,
      port
    });
  }
};
const mcpDev = {
  command: "mcp:dev",
  async run() {
    await ensureBootstrap();
    const { runMcpDevServer } = await import("./lib/mcp-dev-server.js");
    await runMcpDevServer();
  }
};
const listTools = {
  command: "mcp:list-tools",
  async run(rest) {
    const args = parseArgs(rest);
    const verbose = args.verbose === true || args.verbose === "true";
    await ensureBootstrap();
    const { loadAllModuleTools } = await import("./lib/tool-loader.js");
    await loadAllModuleTools();
    const { getToolRegistry } = await import("./lib/tool-registry.js");
    const registry = getToolRegistry();
    const toolNames = registry.listToolNames();
    if (toolNames.length === 0) {
      console.log("\nNo MCP tools registered.");
      console.log("Tools can be registered by modules using registerMcpTool().\n");
      return;
    }
    console.log(`
Registered MCP Tools (${toolNames.length}):
`);
    const byModule = /* @__PURE__ */ new Map();
    for (const name of toolNames) {
      const [module] = name.split(".");
      const list = byModule.get(module) ?? [];
      list.push(name);
      byModule.set(module, list);
    }
    const sortedModules = Array.from(byModule.keys()).sort();
    for (const module of sortedModules) {
      const tools = byModule.get(module);
      console.log(`${module} (${tools.length} tools):`);
      for (const name of tools.sort()) {
        const tool = registry.getTool(name);
        if (!tool) continue;
        if (verbose) {
          console.log(`  ${name}`);
          console.log(`    ${tool.description}`);
          if (tool.requiredFeatures?.length) {
            console.log(`    Requires: ${tool.requiredFeatures.join(", ")}`);
          }
        } else {
          console.log(`  - ${name}`);
        }
      }
      console.log("");
    }
  }
};
const entityGraph = {
  command: "entity-graph",
  async run(rest) {
    const args = parseArgs(rest);
    const format = String(args.format ?? "triples");
    const entity = args.entity ? String(args.entity) : void 0;
    const module = args.module ? String(args.module) : void 0;
    await ensureBootstrap();
    const { getOrm } = await import("@open-mercato/shared/lib/db/mikro");
    const { extractEntityGraph, formatGraphAsTriples, filterGraphByEntity, filterGraphByModule } = await import("./lib/entity-graph.js");
    console.log("[Entity Graph] Extracting from MikroORM metadata...");
    const orm = await getOrm();
    const graph = await extractEntityGraph(orm);
    let edges = graph.edges;
    if (entity) {
      edges = filterGraphByEntity(graph, entity);
      console.log(`[Entity Graph] Filtered by entity: ${entity}`);
    }
    if (module) {
      const filteredGraph2 = { ...graph, edges };
      edges = filterGraphByModule(filteredGraph2, module);
      console.log(`[Entity Graph] Filtered by module: ${module}`);
    }
    const filteredGraph = { ...graph, edges };
    if (format === "json") {
      console.log(JSON.stringify(filteredGraph, null, 2));
    } else {
      const triples = formatGraphAsTriples(filteredGraph);
      console.log("");
      for (const triple of triples) {
        console.log(triple);
      }
    }
    console.log(`
[Entity Graph] ${graph.nodes.length} entities, ${edges.length} relationships`);
  }
};
const runPendingActionCleanup = {
  command: "run-pending-action-cleanup",
  async run() {
    await ensureBootstrap();
    const container = await createRequestContainer();
    const { runPendingActionCleanup: runCleanup } = await import("./workers/ai-pending-action-cleanup.js");
    const em = container.resolve("em");
    const summary = await runCleanup({ em });
    console.log("[ai-pending-action-cleanup] Sweep complete:", summary);
  }
};
const testTools = {
  command: "test-tools",
  async run(rest) {
    const args = parseArgs(rest);
    const json = args.json === true || args.json === "true";
    const moduleFilter = typeof args.module === "string" && args.module.length > 0 ? args.module : null;
    const includeMutations = args["no-mutations"] !== true && args["no-mutations"] !== "true";
    const tenantId = typeof args.tenant === "string" && args.tenant.length > 0 ? args.tenant : null;
    const organizationId = typeof args.org === "string" && args.org.length > 0 ? args.org : null;
    await ensureBootstrap();
    const { runToolTests } = await import("./lib/tool-test-runner.js");
    const report = await runToolTests({
      tenantId,
      organizationId,
      moduleFilter,
      includeMutations
    });
    if (json) {
      console.log("---TOOL_TEST_REPORT_BEGIN---");
      console.log(JSON.stringify(report));
      console.log("---TOOL_TEST_REPORT_END---");
    } else {
      console.log("");
      console.log(
        `AI tool test report \u2014 tenant=${report.tenantId ?? "<none>"} org=${report.organizationId ?? "<none>"}`
      );
      console.log(
        `total=${report.total} pass=${report.passed} fail=${report.failed} skip=${report.skipped}`
      );
      const byModule = /* @__PURE__ */ new Map();
      for (const record of report.records) {
        const list = byModule.get(record.module) ?? [];
        list.push(record);
        byModule.set(record.module, list);
      }
      const sortedModules = Array.from(byModule.keys()).sort();
      for (const moduleId of sortedModules) {
        const list = byModule.get(moduleId);
        console.log("");
        console.log(`${moduleId} (${list.length}):`);
        for (const record of list) {
          const marker = record.status === "pass" ? "\u2713" : record.status === "fail" ? "\u2717" : "\xB7";
          const reason = record.reason ? ` \u2014 ${record.reason}` : "";
          const mutation = record.isMutation ? " [mutation]" : "";
          console.log(
            `  ${marker} ${record.tool}${mutation} (${record.durationMs}ms)${reason}`
          );
        }
      }
      console.log("");
    }
    if (report.failed > 0) {
      process.exitCode = 1;
    }
  }
};
const runTokenUsagePrune = {
  command: "run-token-usage-prune",
  async run() {
    await ensureBootstrap();
    const container = await createRequestContainer();
    const { runTokenUsagePrune: runPrune } = await import("./workers/ai-token-usage-prune.js");
    const em = container.resolve("em");
    const summary = await runPrune({ em });
    console.log("[ai-token-usage-prune] Prune complete:", summary);
  }
};
var cli_default = [
  mcpServe,
  mcpServeHttp,
  mcpDev,
  listTools,
  entityGraph,
  runPendingActionCleanup,
  runTokenUsagePrune,
  testTools
];
export {
  cli_default as default
};
//# sourceMappingURL=cli.js.map
