"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.callTool = callTool;
const context_1 = require("../../../services/iam/context");
const ephemeral_1 = require("../../../services/iam/ephemeral");
const mcpClient = __importStar(require("../../../services/mcp/client"));
const mcpDbService = __importStar(require("../../../services/mcp/db"));
const yamlDb = __importStar(require("../../../services/yaml-workflow/db"));
const yamlDeployer = __importStar(require("../../../services/yaml-workflow/deployer"));
/**
 * Call any tool by its qualified name — handles both YAML workflows
 * (yaml__* prefix) and raw MCP tools (server_slug__tool_name).
 *
 * Callers pass their own module-level caches so each pipeline
 * (mcpQuery, mcpTriage) keeps its own isolated cache instances.
 */
async function callTool(qualifiedName, args, caches) {
    // Check if this is a compiled YAML workflow
    const yamlWorkflowName = caches.yamlWorkflowMap.get(qualifiedName);
    if (yamlWorkflowName) {
        try {
            const wf = await yamlDb.getYamlWorkflowByName(yamlWorkflowName);
            if (!wf || wf.status !== 'active') {
                return { error: `Compiled workflow "${yamlWorkflowName}" is not active` };
            }
            const toolCtx = (0, context_1.getToolContext)();
            const scopedArgs = toolCtx?.principal.id
                ? {
                    ...args,
                    _scope: {
                        principal: toolCtx.principal,
                        ...(toolCtx.initiatingPrincipal ? { initiatingPrincipal: toolCtx.initiatingPrincipal } : {}),
                        scopes: toolCtx.credentials.scopes,
                    },
                }
                : args;
            const { job_id, result } = await yamlDeployer.invokeYamlWorkflowSync(wf.app_id, wf.graph_topic, scopedArgs, undefined, wf.graph_topic);
            return { job_id, workflow: yamlWorkflowName, status: 'completed', result };
        }
        catch (err) {
            return { error: err.message, tool: qualifiedName, args };
        }
    }
    // Exchange ephemeral credential tokens right before the MCP call
    args = await (0, ephemeral_1.exchangeTokensInArgs)(args);
    // Standard MCP tool routing
    const serverName = caches.toolServerMap.get(qualifiedName);
    const separatorIdx = qualifiedName.indexOf('__');
    const toolName = separatorIdx >= 0
        ? qualifiedName.slice(separatorIdx + 2)
        : qualifiedName;
    const toolCtx = (0, context_1.getToolContext)();
    const authContext = toolCtx?.principal.id
        ? { userId: toolCtx.principal.id, delegationToken: toolCtx.credentials.delegationToken }
        : undefined;
    if (serverName) {
        try {
            return await mcpClient.callServerTool(serverName, toolName, args, authContext);
        }
        catch (err) {
            return { error: err.message, tool: qualifiedName, args };
        }
    }
    // Fallback: scan all connected servers
    const { servers } = await mcpDbService.listMcpServers({ limit: 100 });
    for (const server of servers) {
        const manifest = server.tool_manifest || [];
        if (manifest.some((t) => t.name === toolName)) {
            try {
                return await mcpClient.callServerTool(server.name, toolName, args, authContext);
            }
            catch (err) {
                return { error: err.message, tool: qualifiedName, args };
            }
        }
    }
    return { error: `Unknown tool: ${qualifiedName} (no server found)`, tool: qualifiedName };
}
