"use strict";
/**
 * Validate stage: optional LLM review of generated YAML against intent.
 *
 * Checks for missing data flow connections, broken iteration sources,
 * and session handles that get lost mid-pipeline. Records issues as
 * informational warnings — does NOT modify the YAML.
 */
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.validate = validate;
const llm_1 = require("../../llm");
const defaults_1 = require("../../../modules/defaults");
const prompts_1 = require("./prompts");
/**
 * Validate pipeline stage: optional LLM review.
 */
async function validate(ctx) {
    ctx.validationIssues = [];
    // Skip if no API key or no plan (no point validating mechanical output)
    if (!(0, llm_1.hasLLMApiKey)(defaults_1.LLM_MODEL_SECONDARY) || !ctx.compilationPlan)
        return ctx;
    // Skip if explicitly disabled
    if (process.env.LT_SKIP_YAML_VALIDATION === '1')
        return ctx;
    try {
        // Truncate YAML if very long
        const yamlPreview = ctx.yaml.length > 4000
            ? ctx.yaml.slice(0, 4000) + '\n... (truncated)'
            : ctx.yaml;
        // Include activity manifest for cross-referencing tool requirements
        const manifestSummary = ctx.activityManifest
            .filter(a => a.type === 'worker')
            .map(a => ({
            id: a.activity_id,
            tool: a.mcp_tool_name || a.title,
            server: a.mcp_server_id,
            inputs: Object.keys(a.input_mappings).filter(k => k !== 'workflowName' && k !== '_scope'),
            outputs: a.output_fields,
        }));
        const userMessage = [
            `## Intent`,
            ctx.compilationPlan.intent,
            ``,
            `## Activity Manifest`,
            JSON.stringify(manifestSummary, null, 2),
            ``,
            `## Generated YAML`,
            '```yaml',
            yamlPreview,
            '```',
        ].join('\n');
        const response = await (0, llm_1.callLLM)({
            model: defaults_1.LLM_MODEL_SECONDARY,
            max_tokens: 500,
            temperature: 0,
            messages: [
                { role: 'system', content: prompts_1.VALIDATION_PROMPT },
                { role: 'user', content: userMessage },
            ],
        });
        const raw = response.content || '';
        const cleaned = raw
            .replace(/^```(?:json)?\s*/m, '')
            .replace(/\s*```$/m, '')
            .trim();
        const parsed = JSON.parse(cleaned);
        if (Array.isArray(parsed.issues) && parsed.issues.length > 0) {
            ctx.validationIssues = parsed.issues;
            const { loggerRegistry } = await Promise.resolve().then(() => __importStar(require('../../../lib/logger')));
            loggerRegistry.warn(`[yaml-workflow] Validation issues found: ${parsed.issues.join('; ')}`);
        }
    }
    catch (err) {
        const { loggerRegistry } = await Promise.resolve().then(() => __importStar(require('../../../lib/logger')));
        loggerRegistry.info(`[yaml-workflow] Validation skipped: ${err}`);
    }
    return ctx;
}
