"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.registerYamlWorkflowTools = registerYamlWorkflowTools;
const yamlDb = __importStar(require("../../../services/yaml-workflow/db"));
const yamlGenerator = __importStar(require("../../../services/yaml-workflow/generator"));
const yamlDeployer = __importStar(require("../../../services/yaml-workflow/deployer"));
const yamlWorkers = __importStar(require("../../../services/yaml-workflow/workers"));
const task_1 = require("../../../services/task");
const schemas_1 = require("./schemas");
function registerYamlWorkflowTools(server) {
    // mirrors GET /api/yaml-workflows
    server.registerTool('list_yaml_workflows', {
        title: 'List Pipeline Workflows',
        description: 'List compiled YAML workflows with optional filters by status, ' +
            'namespace, or search term. Returns name, status, source, and activity count.',
        inputSchema: schemas_1.listYamlWorkflowsSchema,
    }, async (args) => {
        const { workflows, total } = await yamlDb.listYamlWorkflows({
            status: args.status,
            app_id: args.app_id,
            search: args.search,
            source_workflow_id: args.source_workflow_id,
            limit: args.limit,
            offset: args.offset,
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        total,
                        count: workflows.length,
                        workflows: workflows.map((w) => ({
                            id: w.id,
                            name: w.name,
                            app_id: w.app_id,
                            status: w.status,
                            source_workflow_type: w.source_workflow_type,
                            graph_topic: w.graph_topic,
                            activity_count: w.activity_manifest?.filter((a) => a.type === 'worker').length ?? 0,
                            tags: w.tags,
                            created_at: w.created_at,
                        })),
                    }),
                }],
        };
    });
    // mirrors GET /api/yaml-workflows/:id
    server.registerTool('get_yaml_workflow', {
        title: 'Get Pipeline Workflow',
        description: 'Inspect a compiled workflow by ID. Returns the activity manifest, ' +
            'input/output schemas, YAML content, and provenance.',
        inputSchema: schemas_1.getYamlWorkflowSchema,
    }, async (args) => {
        const wf = await yamlDb.getYamlWorkflow(args.id);
        if (!wf) {
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: 'YAML workflow not found' }) }],
                isError: true,
            };
        }
        return {
            content: [{ type: 'text', text: JSON.stringify(wf) }],
        };
    });
    // mirrors POST /api/yaml-workflows
    server.registerTool('create_yaml_workflow', {
        title: 'Compile Execution to Pipeline',
        description: 'Generate a deterministic YAML workflow from a completed execution. ' +
            'Extracts the tool call sequence and replaces LLM reasoning with ' +
            'direct tool-to-tool data piping. Stored as a draft.',
        inputSchema: schemas_1.createYamlWorkflowSchema,
    }, async (args) => {
        // Reject incomplete executions (same check as route)
        const task = await (0, task_1.getTaskByWorkflowId)(args.workflow_id);
        if (task) {
            const milestones = task.milestones ?? [];
            if (milestones.some((m) => m.name === 'rounds_exhausted')) {
                return {
                    content: [{
                            type: 'text',
                            text: JSON.stringify({
                                error: 'Cannot compile: source execution exhausted its tool rounds without completing.',
                            }),
                        }],
                    isError: true,
                };
            }
        }
        const result = await yamlGenerator.generateYamlFromExecution({
            workflowId: args.workflow_id,
            taskQueue: args.task_queue,
            workflowName: args.workflow_name,
            name: args.name,
            description: args.description,
            compilationFeedback: args.compilation_feedback,
        });
        const mergedTags = [...new Set([
                ...(result.tags || []),
                ...(args.tags || []),
            ])];
        const record = await yamlDb.createYamlWorkflow({
            name: args.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: mergedTags,
            source_workflow_id: args.workflow_id,
            source_workflow_type: args.workflow_name,
            original_prompt: result.originalPrompt || undefined,
            category: result.category || undefined,
            metadata: {
                input_field_meta: result.inputFieldMeta,
                ...(result.validationIssues?.length ? { validation_warnings: result.validationIssues } : {}),
            },
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        id: record.id,
                        name: record.name,
                        app_id: record.app_id,
                        status: record.status,
                        activity_count: record.activity_manifest?.filter((a) => a.type === 'worker').length ?? 0,
                    }),
                }],
        };
    });
    // mirrors POST /api/yaml-workflows/:id/deploy
    server.registerTool('deploy_yaml_workflow', {
        title: 'Deploy Pipeline Workflow',
        description: 'Deploy a compiled YAML workflow to HotMesh, activate it, and ' +
            'register workers. All sibling workflows sharing the same app_id ' +
            'are deployed together.',
        inputSchema: schemas_1.deployYamlWorkflowSchema,
    }, async (args) => {
        const wf = await yamlDb.getYamlWorkflow(args.id);
        if (!wf) {
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: 'YAML workflow not found' }) }],
                isError: true,
            };
        }
        const deployVersion = wf.app_version || '1';
        const siblings = await yamlDb.listYamlWorkflowsByAppId(wf.app_id);
        await yamlDeployer.deployAppId(wf.app_id, deployVersion);
        for (const sibling of siblings) {
            await yamlDb.updateYamlWorkflowVersion(sibling.id, deployVersion);
            await yamlWorkers.registerWorkersForWorkflow(sibling);
            if (sibling.status === 'draft' || sibling.status === 'deployed') {
                await yamlDb.updateYamlWorkflowStatus(sibling.id, 'active');
            }
        }
        await yamlDb.markAppIdContentDeployed(wf.app_id);
        const updated = await yamlDb.getYamlWorkflow(args.id);
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        deployed: true,
                        id: updated?.id,
                        name: updated?.name,
                        status: updated?.status,
                        app_id: updated?.app_id,
                    }),
                }],
        };
    });
    // mirrors POST /api/yaml-workflows/:id/invoke
    server.registerTool('invoke_yaml_workflow', {
        title: 'Invoke Pipeline Workflow',
        description: 'Run a compiled YAML workflow. Deterministic — no LLM reasoning, ' +
            'just direct tool-to-tool data piping. Set sync=true to wait for result.',
        inputSchema: schemas_1.invokeYamlWorkflowSchema,
    }, async (args) => {
        const wf = await yamlDb.getYamlWorkflow(args.id);
        if (!wf) {
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: 'YAML workflow not found' }) }],
                isError: true,
            };
        }
        if (wf.status !== 'active') {
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: 'Workflow must be active to invoke' }) }],
                isError: true,
            };
        }
        if (args.sync) {
            const { job_id, result } = await yamlDeployer.invokeYamlWorkflowSync(wf.app_id, wf.graph_topic, args.data, args.timeout, wf.graph_topic);
            return {
                content: [{ type: 'text', text: JSON.stringify({ job_id, result }) }],
            };
        }
        const jobId = await yamlDeployer.invokeYamlWorkflow(wf.app_id, wf.graph_topic, args.data, wf.graph_topic);
        return {
            content: [{ type: 'text', text: JSON.stringify({ job_id: jobId }) }],
        };
    });
}
