"use strict";
/**
 * LLM compilation call and server tool inventory gathering.
 *
 * Calls the LLM with summarized execution steps and parses the
 * response into an EnhancedCompilationPlan.
 */
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.callCompilationLLM = callCompilationLLM;
const llm_1 = require("../../../llm");
const defaults_1 = require("../../../../modules/defaults");
const prompts_1 = require("../prompts");
const summarize_1 = require("./summarize");
const parse_plan_1 = require("./parse-plan");
/**
 * Gather the full tool inventory and compile hints for MCP servers used in the execution trace.
 * Returns both the tool inventory (for substitution) and per-server compile hints (for context).
 */
async function gatherServerToolInventory(steps) {
    const serverIds = new Set();
    for (const step of steps) {
        if (step.mcpServerId)
            serverIds.add(step.mcpServerId);
    }
    if (serverIds.size === 0)
        return { inventory: '', compileHints: '' };
    try {
        const mcpDbService = await Promise.resolve().then(() => __importStar(require('../../../mcp/db')));
        const { servers } = await mcpDbService.listMcpServers({ limit: 100 });
        const relevant = servers.filter((s) => serverIds.has(s.name));
        const inventoryLines = [];
        const hintLines = [];
        for (const server of relevant) {
            const tools = (server.tool_manifest || []).map((t) => {
                const params = t.inputSchema?.properties
                    ? Object.entries(t.inputSchema.properties)
                        .map(([k, v]) => `${k}: ${v.type || '?'}`)
                        .join(', ')
                    : '';
                return `    - ${t.name}(${params}): ${(t.description || '').slice(0, 120)}`;
            });
            inventoryLines.push(`  ${server.name}:`);
            inventoryLines.push(...tools);
            if (server.compile_hints) {
                hintLines.push(`  **${server.name}**: ${server.compile_hints}`);
            }
        }
        return {
            inventory: inventoryLines.join('\n'),
            compileHints: hintLines.join('\n'),
        };
    }
    catch {
        return { inventory: '', compileHints: '' };
    }
}
/**
 * Call the LLM to produce an EnhancedCompilationPlan.
 * Returns null if the LLM is unavailable or the call fails.
 */
async function callCompilationLLM(steps, originalPrompt, naiveInputs, patternAnnotations, retryHint) {
    if (!(0, llm_1.hasLLMApiKey)(defaults_1.LLM_MODEL_PRIMARY))
        return null;
    const summaries = (0, summarize_1.summarizeSteps)(steps);
    const { inventory: toolInventory, compileHints } = await gatherServerToolInventory(steps);
    const naiveClassification = naiveInputs.map(f => ({
        key: f.key,
        type: f.type,
        classification: f.classification,
        description: f.description,
        source_tool: f.source_tool,
        ...(f.default !== undefined ? { default_preview: (0, summarize_1.truncateValue)(f.default) } : {}),
    }));
    const userMessage = [
        `## Original Prompt`,
        `"${originalPrompt}"`,
        ``,
        `## Execution Steps`,
        JSON.stringify(summaries, null, 2),
        ``,
        ...(patternAnnotations.length > 0 ? [
            `## Pattern Annotations (pre-detected by static analysis)`,
            JSON.stringify(patternAnnotations, null, 2),
            ``,
        ] : []),
        `## Naive Input Classification`,
        JSON.stringify(naiveClassification, null, 2),
        ``,
        ...(compileHints ? [
            `## Tool-Specific Compilation Hints`,
            `These hints come from the MCP server definitions and describe tool-specific constraints you MUST follow:`,
            compileHints,
            ``,
        ] : []),
        ...(toolInventory ? [
            `## Available Tools (full inventory from servers used in this execution)`,
            `Use these to substitute simpler tools for iterations when the executed tool is too complex.`,
            toolInventory,
        ] : []),
        ...(retryHint ? [retryHint] : []),
    ].join('\n');
    try {
        const response = await (0, llm_1.callLLM)({
            model: defaults_1.LLM_MODEL_PRIMARY,
            max_tokens: 4000,
            temperature: 0,
            messages: [
                { role: 'system', content: prompts_1.COMPILATION_PROMPT },
                { role: 'user', content: userMessage },
            ],
        });
        const raw = response.content || '';
        return (0, parse_plan_1.parsePlan)(raw, steps.length);
    }
    catch (err) {
        const { loggerRegistry } = await Promise.resolve().then(() => __importStar(require('../../../../lib/logger')));
        loggerRegistry.warn(`[yaml-workflow] LLM compilation failed, using mechanical fallback: ${err}`);
        return null;
    }
}
