import { z } from "zod";
import { registerMcpTool, getToolRegistry, toolRegistry, unregisterMcpTool } from "./tool-registry.js";
import {
  applyToolOverrideMap,
  composeToolOverrideMap
} from "./ai-overrides.js";
import { ToolSearchService } from "./tool-search.js";
function isModuleAiTool(value) {
  if (!value || typeof value !== "object") return false;
  const candidate = value;
  return typeof candidate.name === "string" && typeof candidate.description === "string" && candidate.inputSchema !== void 0 && typeof candidate.handler === "function";
}
const contextWhoamiTool = {
  name: "context_whoami",
  description: "Get the current authentication context including tenant ID, organization ID, user ID, and available features. Use this to understand your current scope before performing operations.",
  inputSchema: z.object({}),
  requiredFeatures: [],
  // No specific feature required - available to all authenticated users
  handler: async (_input, ctx) => {
    return {
      tenantId: ctx.tenantId,
      organizationId: ctx.organizationId,
      userId: ctx.userId,
      isSuperAdmin: ctx.isSuperAdmin,
      features: ctx.userFeatures,
      featureCount: ctx.userFeatures.length
    };
  }
};
function loadModuleTools(moduleId, tools) {
  for (const tool of tools) {
    registerMcpTool(tool, { moduleId });
  }
}
function registerGeneratedAiToolEntries(entries) {
  let registered = 0;
  for (const entry of entries) {
    if (!entry || typeof entry.moduleId !== "string") continue;
    if (!Array.isArray(entry.tools) || entry.tools.length === 0) continue;
    for (const candidate of entry.tools) {
      if (!isModuleAiTool(candidate)) {
        console.warn(
          `[MCP Tools] Skipping malformed AI tool in module "${entry.moduleId}"`
        );
        continue;
      }
      registerMcpTool(candidate, { moduleId: entry.moduleId });
      registered += 1;
    }
  }
  return registered;
}
function applyAiToolOverrideEntries(entries) {
  const overrideMap = composeToolOverrideMap(entries);
  if (Object.keys(overrideMap).length === 0) return;
  const baseTools = toolRegistry.getTools();
  const overridden = applyToolOverrideMap(baseTools, overrideMap);
  for (const [name, value] of Object.entries(overrideMap)) {
    if (value === null) {
      unregisterMcpTool(name);
      console.info(`[AI Overrides] Tool "${name}" disabled by override.`);
      continue;
    }
    const next = overridden.get(name);
    if (!next) continue;
    registerMcpTool(next, { moduleId: "ai_overrides" });
    console.info(`[AI Overrides] Tool "${name}" replaced by override.`);
  }
}
async function loadGeneratedAiToolOverrides() {
  let entries = [];
  try {
    const mod = await import("@/.mercato/generated/ai-tools.generated");
    entries = Array.isArray(mod.aiToolOverrideEntries) ? mod.aiToolOverrideEntries : [];
  } catch {
  }
  applyAiToolOverrideEntries(entries);
}
async function loadGeneratedModuleAiTools() {
  try {
    const mod = await import("@/.mercato/generated/ai-tools.generated");
    const entries = Array.isArray(mod.aiToolConfigEntries) ? mod.aiToolConfigEntries : [];
    const count = registerGeneratedAiToolEntries(entries);
    try {
      await loadGeneratedAiToolOverrides();
    } catch (error) {
      console.error("[AI Overrides] Failed to apply tool overrides:", error);
    }
    return count;
  } catch (error) {
    console.error(
      "[MCP Tools] Could not load ai-tools.generated.ts (module tools unavailable):",
      error
    );
    return 0;
  }
}
async function loadAllModuleTools() {
  registerMcpTool(contextWhoamiTool, { moduleId: "context" });
  console.error("[MCP Tools] Registered built-in context_whoami tool");
  try {
    const { loadCodeModeTools } = await import("./codemode-tools.js");
    const toolCount = await loadCodeModeTools();
    console.error(`[MCP Tools] Registered ${toolCount} Code Mode tools`);
  } catch (error) {
    console.error("[MCP Tools] Could not load Code Mode tools:", error);
  }
  try {
    const moduleToolCount = await loadGeneratedModuleAiTools();
    console.error(
      `[MCP Tools] Registered ${moduleToolCount} module-contributed AI tools from ai-tools.generated.ts`
    );
  } catch (error) {
    console.error("[MCP Tools] Could not load module AI tools:", error);
  }
}
async function indexToolsForSearch(searchService, force = false) {
  const registry = getToolRegistry();
  const toolSearchService = new ToolSearchService(searchService, registry);
  try {
    const result = await toolSearchService.indexTools(force);
    console.error(`[MCP Tools] Indexed ${result.indexed} tools for search`);
    console.error(`[MCP Tools] Search strategies available: ${result.strategies.join(", ")}`);
    if (result.skipped > 0) {
      console.error(`[MCP Tools] Skipped ${result.skipped} tools (unchanged)`);
    }
    return result;
  } catch (error) {
    console.error("[MCP Tools] Failed to index tools for search:", error);
    throw error;
  }
}
function createToolSearchService(searchService) {
  const registry = getToolRegistry();
  return new ToolSearchService(searchService, registry);
}
export {
  applyAiToolOverrideEntries,
  createToolSearchService,
  indexToolsForSearch,
  loadAllModuleTools,
  loadGeneratedAiToolOverrides,
  loadGeneratedModuleAiTools,
  loadModuleTools,
  registerGeneratedAiToolEntries
};
//# sourceMappingURL=tool-loader.js.map
