"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadToolsFromServers = loadToolsFromServers;
const logger_1 = require("../../../lib/logger");
const mcpDbService = __importStar(require("../../../services/mcp/db"));
const strategy_advisors_1 = require("./strategy-advisors");
/**
 * Discover MCP servers, cache tool definitions, and return a lightweight
 * summary for the durable pipe.
 *
 * Callers pass their own module-level caches so each pipeline keeps
 * isolated cache instances. Optional `baseTags` are merged before querying.
 */
async function loadToolsFromServers(tags, caches, opts) {
    const prefix = opts?.logPrefix || 'shared';
    let servers;
    if (tags?.length || opts?.baseTags?.length) {
        const combinedTags = [...new Set([...(opts?.baseTags || []), ...(tags || [])])];
        servers = await mcpDbService.findServersByTags(combinedTags, 'any');
    }
    else {
        const result = await mcpDbService.listMcpServers({ limit: 100 });
        servers = result.servers;
    }
    const toolIds = [];
    const inventoryLines = [];
    const serverInfos = [];
    for (const server of servers) {
        const manifest = server.tool_manifest || [];
        const slug = server.name.replace(/[^a-zA-Z0-9]/g, '_');
        const serverTags = server.tags?.length ? server.tags.join(', ') : 'general';
        const toolNames = [];
        for (const t of manifest) {
            const qualifiedName = `${slug}__${t.name}`;
            caches.toolServerMap.set(qualifiedName, server.name);
            caches.toolDefCache.set(qualifiedName, {
                type: 'function',
                function: {
                    name: qualifiedName,
                    description: `[${server.name}] ${t.description || ''}`,
                    parameters: (t.inputSchema || { type: 'object', properties: {} }),
                },
            });
            toolIds.push(qualifiedName);
            toolNames.push(t.name);
        }
        inventoryLines.push(`• ${server.name} [${serverTags}] (${manifest.length} tools): ${toolNames.join(', ')}`);
        if (server.compile_hints) {
            inventoryLines.push(`  Hints: ${server.compile_hints}`);
        }
        serverInfos.push({
            name: server.name,
            description: server.description || null,
            tags: server.tags || [],
            metadata: server.metadata || null,
            toolNames,
            toolCount: manifest.length,
            slug,
        });
    }
    const strategy = (0, strategy_advisors_1.generateStrategySection)(serverInfos);
    logger_1.loggerRegistry.info(`[${prefix}:loadTools] ${servers.length} servers, ${toolIds.length} tools loaded`);
    return { toolIds, inventory: inventoryLines.join('\n'), strategy };
}
