"use strict";
/**
 * Regenerate a Plan Build workflow from its original prompt + compilation feedback.
 *
 * Reuses the builder's LLM call and prompt structure without spawning a full
 * durable workflow. This is the fast path for "Recompile Pipeline" on Plan Build
 * workflows that don't have an execution trace.
 */
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.rebuildFromPrompt = rebuildFromPrompt;
const llm_1 = require("../llm");
const defaults_1 = require("../../modules/defaults");
const logger_1 = require("../../lib/logger");
const BUILDER_MAX_TOKENS = 8192;
/**
 * Rebuild a YAML workflow from a prompt with optional feedback on the prior attempt.
 */
async function rebuildFromPrompt(options) {
    // Load the builder's system prompt and tool inventory
    const { loadBuilderTools } = await Promise.resolve().then(() => __importStar(require('../../system/workflows/mcp-workflow-builder/activities')));
    const { BUILDER_SYSTEM_PROMPT, REFINE_PROMPT } = await Promise.resolve().then(() => __importStar(require('../../system/workflows/mcp-workflow-builder/prompts')));
    const raw = await loadBuilderTools();
    const serverSection = [
        raw.strategy ? `${raw.strategy}\n` : '',
        `## Available MCP Servers & Tools\n\n${raw.inventory}`,
    ].filter(Boolean).join('\n');
    const messages = [
        { role: 'system', content: BUILDER_SYSTEM_PROMPT(serverSection) },
    ];
    if (options.feedback && options.priorYaml) {
        messages.push({ role: 'user', content: `Build a workflow for: ${options.prompt}` });
        messages.push({
            role: 'assistant',
            content: `Here is the prior YAML that needs fixing:\n\`\`\`yaml\n${options.priorYaml.slice(0, 3000)}\n\`\`\``,
        });
        messages.push({
            role: 'user',
            content: `${REFINE_PROMPT}\n\nExecution feedback:\n${options.feedback}`,
        });
    }
    else {
        messages.push({ role: 'user', content: `Build a workflow for: ${options.prompt}` });
    }
    // Call LLM with retry
    for (let attempt = 0; attempt < 3; attempt++) {
        const t0 = Date.now();
        const response = await (0, llm_1.callLLM)({
            model: defaults_1.LLM_MODEL_PRIMARY,
            messages,
            temperature: 0,
            max_tokens: BUILDER_MAX_TOKENS,
        });
        logger_1.loggerRegistry.info(`[builder-regenerate] attempt=${attempt + 1} ${Date.now() - t0}ms | in=${response.usage?.prompt_tokens} out=${response.usage?.completion_tokens}`);
        const content = response.content || '';
        const cleaned = content.replace(/^```(?:json)?\s*/m, '').replace(/\s*```\s*$/m, '');
        try {
            const parsed = JSON.parse(cleaned);
            if (!parsed.yaml)
                throw new Error('Missing yaml in response');
            return {
                yaml: parsed.yaml,
                inputSchema: parsed.input_schema || {},
                outputSchema: parsed.output_schema || {},
                activityManifest: parsed.activity_manifest || [],
                tags: parsed.tags || [],
            };
        }
        catch (err) {
            logger_1.loggerRegistry.warn(`[builder-regenerate] parse failed (attempt ${attempt + 1}): ${err.message}`);
            messages.push({ role: 'assistant', content });
            messages.push({
                role: 'user',
                content: `Your response was not valid JSON. Return ONLY a JSON object with "yaml", "input_schema", "output_schema", "activity_manifest", and "tags" fields.`,
            });
        }
    }
    throw new Error('Failed to regenerate YAML after 3 attempts');
}
