"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.registerWorkflowTools = registerWorkflowTools;
const configService = __importStar(require("../../../services/config"));
const registry_1 = require("../../../services/workers/registry");
const workflow_invocation_1 = require("../../../services/workflow-invocation");
const workers_1 = require("../../../workers");
const schemas_1 = require("./schemas");
function registerWorkflowTools(server) {
    // mirrors GET /api/workflows/discovered
    server.registerTool('list_discovered_workflows', {
        title: 'List Discovered Workflows',
        description: 'Unified list of all known workflows: active workers, historical ' +
            'entities, and registered configs merged together. Shows which are ' +
            'certified (registered), active, invocable, and their roles.',
        inputSchema: schemas_1.listDiscoveredWorkflowsSchema,
    }, async (args) => {
        const activeWorkers = (0, registry_1.getRegisteredWorkers)();
        const configs = await configService.listWorkflowConfigs();
        const configMap = new Map(configs.map((c) => [c.workflow_type, c]));
        const allTypes = new Set();
        for (const [name] of activeWorkers)
            allTypes.add(name);
        for (const c of configs)
            allTypes.add(c.workflow_type);
        const workflows = [...allTypes]
            .filter((t) => args.include_system || !registry_1.SYSTEM_WORKFLOWS.has(t))
            .sort()
            .map((wt) => {
            const config = configMap.get(wt);
            const worker = activeWorkers.get(wt);
            const hasCertification = !!(config &&
                ((config.roles?.length ?? 0) > 0 ||
                    (config.consumes?.length ?? 0) > 0));
            const tier = !config ? 'durable' : hasCertification ? 'certified' : 'configured';
            return {
                workflow_type: wt,
                task_queue: config?.task_queue ?? worker?.taskQueue ?? null,
                tier,
                registered: !!config,
                active: !!worker,
                invocable: config?.invocable ?? false,
                description: config?.description ?? null,
                roles: config?.roles ?? [],
            };
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({ count: workflows.length, workflows }),
                }],
        };
    });
    // mirrors POST /api/workflows/:type/invoke
    server.registerTool('invoke_workflow', {
        title: 'Invoke Workflow',
        description: 'Start a certified workflow by type. The workflow must have invocable=true ' +
            'in its config. Returns the workflow ID immediately; the workflow runs ' +
            'durably in the background.',
        inputSchema: schemas_1.invokeWorkflowSchema,
    }, async (args) => {
        const result = await (0, workflow_invocation_1.invokeWorkflow)({
            workflowType: args.workflow_type,
            data: args.data,
            metadata: args.metadata,
            executeAs: args.execute_as,
            auth: { userId: 'lt-system', role: 'superadmin' },
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({ workflow_id: result.workflowId, message: 'Workflow started' }),
                }],
        };
    });
    // mirrors GET /api/workflows/:workflowId/status + /result
    server.registerTool('get_workflow_status', {
        title: 'Get Workflow Status',
        description: 'Check the status and result of a workflow execution. Returns ' +
            'status (0=complete, positive=running) and the result if complete.',
        inputSchema: schemas_1.getWorkflowStatusSchema,
    }, async (args) => {
        const { getTaskByWorkflowId } = await Promise.resolve().then(() => __importStar(require('../../../services/task')));
        const task = await getTaskByWorkflowId(args.workflow_id);
        if (!task) {
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: 'Workflow not found' }) }],
                isError: true,
            };
        }
        const client = (0, workers_1.createClient)();
        const handle = await client.workflow.getHandle(task.task_queue || 'long-tail-system', task.workflow_type, args.workflow_id);
        const status = await handle.status();
        if (status !== 0) {
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({ workflow_id: args.workflow_id, status: 'running' }),
                    }],
            };
        }
        const result = await handle.result();
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({ workflow_id: args.workflow_id, status: 'complete', result }),
                }],
        };
    });
}
