"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.mcpQueryRouter = mcpQueryRouter;
const hotmesh_1 = require("@hotmeshio/hotmesh");
const orchestrator_1 = require("../../../services/orchestrator");
const activities = __importStar(require("./activities"));
const { findCompiledWorkflows, evaluateWorkflowMatch, extractWorkflowInputs, } = hotmesh_1.Durable.workflow.proxyActivities({
    activities,
    retry: {
        maximumAttempts: 3,
        backoffCoefficient: 2,
        maximumInterval: '10 seconds',
    },
});
/**
 * MCP Query Router (orchestrator/container).
 *
 * Entry point for all MCP queries. Determines whether a compiled
 * deterministic YAML workflow can handle the request or whether
 * dynamic MCP orchestration is needed.
 *
 * Phase 1: FTS + tag discovery of compiled workflows
 * Phase 2: LLM-as-judge matching + input extraction
 * Route: mcpDeterministic (compiled match) OR mcpQuery (dynamic)
 */
async function mcpQueryRouter(envelope) {
    const prompt = (envelope.data?.prompt || envelope.data?.question);
    const tags = envelope.data?.tags;
    if (!prompt) {
        return {
            type: 'return',
            data: {
                title: 'No prompt provided',
                summary: 'Please provide a prompt describing what you want to accomplish.',
                result: null,
                tool_calls_made: 0,
            },
        };
    }
    // Phase 1: Ranked discovery of compiled YAML workflows
    const compiled = await findCompiledWorkflows(prompt);
    // Phase 2: LLM-as-judge — does a compiled workflow match?
    if (compiled.candidates.length > 0) {
        const match = await evaluateWorkflowMatch(prompt, compiled.candidates);
        if (match.matched && match.workflowName) {
            // Phase 2b: Extract structured inputs from the prompt
            const candidate = compiled.candidates.find((c) => c.name === match.workflowName);
            const inputSchema = candidate?.input_schema || { type: 'object', properties: {} };
            const extraction = await extractWorkflowInputs(prompt, inputSchema, match.workflowName);
            if (extraction.extracted && extraction.inputs) {
                // Route to mcpDeterministic — compiled workflow handles this
                return await (0, orchestrator_1.executeLT)({
                    workflowName: 'mcpDeterministic',
                    args: [{
                            data: {
                                workflowName: match.workflowName,
                                inputs: extraction.inputs,
                                confidence: match.confidence,
                            },
                            metadata: envelope.metadata,
                        }],
                    taskQueue: 'long-tail-system',
                });
            }
            // Input extraction failed — fall through to dynamic
        }
    }
    // No compiled match — route to mcpQuery for dynamic MCP orchestration
    return await (0, orchestrator_1.executeLT)({
        workflowName: 'mcpQuery',
        args: [{ data: { prompt, tags }, metadata: envelope.metadata }],
        taskQueue: 'long-tail-system',
    });
}
