"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.createWorkflowCompilerServer = createWorkflowCompilerServer;
exports.getWorkflowCompilerServer = getWorkflowCompilerServer;
exports.stopWorkflowCompilerServer = stopWorkflowCompilerServer;
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
const zod_1 = require("zod");
const logger_1 = require("../../lib/logger");
const yamlGenerator = __importStar(require("../../services/yaml-workflow/generator"));
const durable_compiler_1 = require("../../services/yaml-workflow/durable-compiler");
const yamlDb = __importStar(require("../../services/yaml-workflow/db"));
const yamlDeployer = __importStar(require("../../services/yaml-workflow/deployer"));
const yamlWorkers = __importStar(require("../../services/yaml-workflow/workers"));
let server = null;
// ── Schemas (extracted to break TS2589 deep-instantiation in registerTool generics) ──
const convertSchema = zod_1.z.object({
    workflow_id: zod_1.z.string().describe('The workflow execution ID to analyze'),
    task_queue: zod_1.z.string().describe('HotMesh task queue (e.g., "long-tail-examples")'),
    workflow_name: zod_1.z.string().describe('Workflow name (e.g., "reviewContent")'),
    yaml_name: zod_1.z.string().describe('Name for the generated YAML workflow'),
    description: zod_1.z.string().optional().describe('Optional description'),
});
const deploySchema = zod_1.z.object({
    yaml_workflow_id: zod_1.z.string().describe('UUID of the stored YAML workflow'),
    activate: zod_1.z.boolean().optional().default(false)
        .describe('Whether to activate immediately after deployment'),
});
const listSchema = zod_1.z.object({
    status: zod_1.z.enum(['draft', 'deployed', 'active', 'archived']).optional()
        .describe('Filter by status'),
    limit: zod_1.z.number().int().min(1).max(100).optional().default(25)
        .describe('Maximum number of results'),
    offset: zod_1.z.number().int().min(0).optional().default(0)
        .describe('Pagination offset'),
});
const compileDurableSchema = zod_1.z.object({
    source: zod_1.z.string().describe('TypeScript source code of the durable workflow function (inline source, not a file path)'),
    workflow_name: zod_1.z.string().describe('Name of the exported workflow function to compile (e.g., "assemblyLine", "basicSignal")'),
    yaml_name: zod_1.z.string().describe('Name for the generated YAML workflow (becomes graph topic)'),
    description: zod_1.z.string().optional().describe('Optional description of what the workflow does'),
    app_id: zod_1.z.string().optional().describe('Target namespace (defaults to "longtail")'),
});
/**
 * Create the Workflow Compiler MCP server.
 *
 * Provides tools for converting MCP tool call sequences into
 * deterministic HotMesh YAML workflows:
 * - convert_execution_to_yaml — analyze execution and generate YAML
 * - deploy_yaml_workflow — deploy and optionally activate
 * - list_yaml_workflows — list stored YAML workflows
 */
async function createWorkflowCompilerServer(options) {
    if (server)
        return server;
    const name = options?.name || 'workflow-compiler';
    server = new mcp_js_1.McpServer({ name, version: '1.0.0' });
    // ── convert_execution_to_yaml ─────────────────────────────────────
    server.registerTool('convert_execution_to_yaml', {
        title: 'Convert Execution to YAML',
        description: 'Analyze a completed workflow execution and convert its tool call sequence ' +
            'into a deterministic HotMesh YAML workflow. Extracts callLLM→callDbTool pairs ' +
            'and mcp_* activities, replacing LLM reasoning with direct tool-to-tool data piping. ' +
            'The generated YAML is stored as a draft that can be deployed and activated.',
        inputSchema: convertSchema,
    }, async (args) => {
        const result = await yamlGenerator.generateYamlFromExecution({
            workflowId: args.workflow_id,
            taskQueue: args.task_queue,
            workflowName: args.workflow_name,
            name: args.yaml_name,
            description: args.description,
        });
        const record = await yamlDb.createYamlWorkflow({
            name: args.yaml_name,
            description: args.description,
            app_id: result.appId,
            yaml_content: result.yaml,
            graph_topic: result.graphTopic,
            input_schema: result.inputSchema,
            output_schema: result.outputSchema,
            activity_manifest: result.activityManifest,
            input_field_meta: result.inputFieldMeta,
            original_prompt: result.originalPrompt,
            category: result.category,
            tags: result.tags,
            source_workflow_id: args.workflow_id,
            source_workflow_type: args.workflow_name,
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        yaml_workflow_id: record.id,
                        app_id: record.app_id,
                        activity_count: result.activityManifest.filter((a) => a.type === 'worker').length,
                        input_schema: result.inputSchema,
                        input_field_meta: result.inputFieldMeta,
                        yaml_preview: result.yaml.slice(0, 500),
                        ...(result.compilationPlan ? {
                            compilation: {
                                intent: result.compilationPlan.intent,
                                core_steps: result.compilationPlan.coreStepIndices.length,
                                has_iteration: result.compilationPlan.hasIteration,
                                llm_refined: true,
                            },
                        } : { compilation: { llm_refined: false } }),
                    }),
                }],
        };
    });
    // ── deploy_yaml_workflow ──────────────────────────────────────────
    server.registerTool('deploy_yaml_workflow', {
        title: 'Deploy YAML Workflow',
        description: 'Deploy a stored YAML workflow to HotMesh. Optionally activate it immediately ' +
            'and register workers so it can receive invocations.',
        inputSchema: deploySchema,
    }, async (args) => {
        const wf = await yamlDb.getYamlWorkflow(args.yaml_workflow_id);
        if (!wf)
            throw new Error('YAML workflow not found');
        try {
            await yamlDeployer.deployYamlWorkflow(wf.app_id, wf.yaml_content);
            await yamlDb.updateYamlWorkflowStatus(wf.id, 'deployed');
            let status = 'deployed';
            if (args.activate) {
                await yamlDeployer.activateYamlWorkflow(wf.app_id, wf.app_version);
                await yamlWorkers.registerWorkersForWorkflow(wf);
                await yamlDb.updateYamlWorkflowStatus(wf.id, 'active');
                status = 'active';
            }
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            status,
                            app_id: wf.app_id,
                            graph_topic: wf.graph_topic,
                        }),
                    }],
            };
        }
        catch (err) {
            // Mark workflow as failed so it doesn't block future deploys
            await yamlDb.updateYamlWorkflowStatus(wf.id, 'error');
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            error: err.message,
                            status: 'error',
                            app_id: wf.app_id,
                            graph_topic: wf.graph_topic,
                            hint: err.message.includes('Duplicate activity id')
                                ? 'Two workflows have colliding activity IDs. Archive or rename one before redeploying.'
                                : 'Check server logs for the full YAML that failed validation.',
                        }),
                    }],
                isError: true,
            };
        }
    });
    // ── list_yaml_workflows ───────────────────────────────────────────
    server.registerTool('list_yaml_workflows', {
        title: 'List YAML Workflows',
        description: 'List stored YAML workflows with optional status filter. ' +
            'Returns workflow metadata including name, status, source, and activity count.',
        inputSchema: listSchema,
    }, async (args) => {
        const { workflows, total } = await yamlDb.listYamlWorkflows({
            status: args.status,
            limit: args.limit,
            offset: args.offset,
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        total,
                        count: workflows.length,
                        workflows: workflows.map((wf) => ({
                            id: wf.id,
                            name: wf.name,
                            app_id: wf.app_id,
                            status: wf.status,
                            source_workflow_type: wf.source_workflow_type,
                            activity_count: wf.activity_manifest.filter((a) => a.type === 'worker').length,
                            graph_topic: wf.graph_topic,
                            created_at: wf.created_at,
                        })),
                    }),
                }],
        };
    });
    // ── compile_durable_to_yaml ────────────────────────────────────────
    server.registerTool('compile_durable_to_yaml', {
        title: 'Compile Durable Workflow to YAML',
        description: 'Convert a procedural durable TypeScript workflow (Temporal-like API) into an equivalent ' +
            'HotMesh YAML DAG. The generated YAML runs without replay overhead and achieves the same ' +
            'orchestration behavior. Handles proxyActivities, sleep, condition/signal, escalation, ' +
            'startChild composition, parallel execution, and loop patterns.',
        inputSchema: compileDurableSchema,
    }, async (args) => {
        const result = await (0, durable_compiler_1.compileDurableToYaml)({
            source: args.source,
            isFilePath: false,
            workflowName: args.workflow_name,
            name: args.yaml_name,
            description: args.description,
            appId: args.app_id,
        });
        const record = await yamlDb.createYamlWorkflow({
            name: args.yaml_name,
            description: args.description,
            app_id: result.appId,
            yaml_content: result.yaml,
            graph_topic: result.graphTopic,
            input_schema: result.inputSchema,
            output_schema: result.outputSchema,
            activity_manifest: result.activityManifest,
            tags: result.tags,
            source_workflow_type: 'durable',
            original_prompt: args.description,
            category: result.category,
            metadata: { durable_source: args.source },
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        yaml_workflow_id: record.id,
                        app_id: record.app_id,
                        graph_topic: result.graphTopic,
                        activity_count: result.activityManifest.filter((a) => a.type === 'worker').length,
                        input_schema: result.inputSchema,
                        yaml_preview: result.yaml.slice(0, 500),
                    }),
                }],
        };
    });
    logger_1.loggerRegistry.info(`[lt-mcp] workflow compiler server created: ${name}`);
    return server;
}
function getWorkflowCompilerServer() {
    return server;
}
async function stopWorkflowCompilerServer() {
    if (server) {
        await server.close?.();
        server = null;
    }
}
