"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.registerTools = registerTools;
const db_1 = require("../../../lib/db");
const taskService = __importStar(require("../../../services/task"));
const escalationService = __importStar(require("../../../services/escalation"));
const configService = __importStar(require("../../../services/config"));
const sql_1 = require("../../../services/mcp/sql");
const schemas_1 = require("./schemas");
/**
 * Register all six read-only query tools on the given MCP server instance.
 */
function registerTools(instance) {
    // ── find_tasks ──────────────────────────────────────────────────
    instance.registerTool('find_tasks', {
        title: 'Find Tasks',
        description: 'Search tasks with optional filters. Returns task records with workflow_id, status, ' +
            'workflow_type, milestones, created/completed timestamps, and metadata.',
        inputSchema: schemas_1.findTasksSchema,
    }, async (args) => {
        const { tasks, total } = await taskService.listTasks({
            status: args.status,
            workflow_type: args.workflow_type,
            workflow_id: args.workflow_id,
            origin_id: args.origin_id,
            limit: args.limit,
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        total,
                        count: tasks.length,
                        tasks: tasks.map((t) => ({
                            id: t.id,
                            workflow_id: t.workflow_id,
                            workflow_type: t.workflow_type,
                            status: t.status,
                            priority: t.priority,
                            origin_id: t.origin_id,
                            created_at: t.created_at,
                            completed_at: t.completed_at,
                            error: t.error,
                            trace_id: t.trace_id,
                            span_id: t.span_id,
                        })),
                    }),
                }],
        };
    });
    // ── find_escalations ────────────────────────────────────────────
    instance.registerTool('find_escalations', {
        title: 'Find Escalations',
        description: 'Search escalations with optional filters. Returns escalation records with type, ' +
            'role, priority, status, description, and assignment info.',
        inputSchema: schemas_1.findEscalationsSchema,
    }, async (args) => {
        const { escalations, total } = await escalationService.listEscalations({
            status: args.status,
            role: args.role,
            type: args.type,
            priority: args.priority,
            limit: args.limit,
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        total,
                        count: escalations.length,
                        escalations: escalations.map((e) => ({
                            id: e.id,
                            type: e.type,
                            subtype: e.subtype,
                            role: e.role,
                            priority: e.priority,
                            status: e.status,
                            description: e.description,
                            workflow_type: e.workflow_type,
                            assigned_to: e.assigned_to,
                            created_at: e.created_at,
                        })),
                    }),
                }],
        };
    });
    // ── get_process_summary ─────────────────────────────────────────
    instance.registerTool('get_process_summary', {
        title: 'Get Process Summary',
        description: 'List business processes grouped by origin_id. Each process shows task count, ' +
            'completed/escalated counts, workflow types involved, and time range.',
        inputSchema: schemas_1.getProcessSummarySchema,
    }, async (args) => {
        const { processes, total } = await taskService.listProcesses({
            workflow_type: args.workflow_type,
            limit: args.limit,
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        total,
                        count: processes.length,
                        processes: processes.map((p) => ({
                            origin_id: p.origin_id,
                            task_count: p.task_count,
                            completed: p.completed,
                            escalated: p.escalated,
                            workflow_types: p.workflow_types,
                            started_at: p.started_at,
                            last_activity: p.last_activity,
                        })),
                    }),
                }],
        };
    });
    // ── get_escalation_stats ────────────────────────────────────────
    instance.registerTool('get_escalation_stats', {
        title: 'Get Escalation Stats',
        description: 'Real-time escalation statistics: pending/claimed counts, created/resolved in last ' +
            '1h and 24h, breakdown by role.',
        inputSchema: schemas_1.getEscalationStatsSchema,
    }, async (_args) => {
        const stats = await escalationService.getEscalationStats();
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify(stats),
                }],
        };
    });
    // ── get_workflow_types ──────────────────────────────────────────
    instance.registerTool('get_workflow_types', {
        title: 'Get Workflow Types',
        description: 'List all registered workflow configurations. Shows workflow type, whether it is ' +
            'an LT workflow or container, its task queue, roles, and description.',
        inputSchema: schemas_1.getWorkflowTypesSchema,
    }, async (_args) => {
        const configs = await configService.listWorkflowConfigs();
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        count: configs.length,
                        workflows: configs.map((c) => ({
                            workflow_type: c.workflow_type,
                            invocable: c.invocable,
                            task_queue: c.task_queue,
                            default_role: c.default_role,
                            description: c.description,
                            roles: c.roles,
                        })),
                    }),
                }],
        };
    });
    // ── get_system_health ──────────────────────────────────────────
    instance.registerTool('get_system_health', {
        title: 'Get System Health',
        description: 'Full system overview: durable workflow execution counts by type (active/completed), ' +
            'task counts by status, escalation counts by status, recent activity window, ' +
            'MCP servers (with tool counts and tags), compiled workflow totals, and workflow configurations.',
        inputSchema: schemas_1.getSystemHealthSchema,
    }, async (_args) => {
        const pool = (0, db_1.getPool)();
        const [taskCounts, escalationCounts, activeTypes, recentActivity, mcpServers, mcpServerList, compiledWorkflows, workflowConfigs, durableWorkflows,] = await Promise.all([
            pool.query(sql_1.HEALTH_TASK_COUNTS),
            pool.query(sql_1.HEALTH_ESCALATION_COUNTS),
            pool.query(sql_1.HEALTH_ACTIVE_WORKFLOW_TYPES),
            pool.query(sql_1.HEALTH_RECENT_ACTIVITY),
            pool.query(sql_1.HEALTH_MCP_SERVERS),
            pool.query(sql_1.HEALTH_MCP_SERVER_LIST),
            pool.query(sql_1.HEALTH_COMPILED_WORKFLOWS),
            pool.query(sql_1.HEALTH_WORKFLOW_CONFIGS),
            pool.query(sql_1.HEALTH_DURABLE_WORKFLOWS),
        ]);
        const tasksByStatus = {};
        for (const row of taskCounts.rows) {
            tasksByStatus[row.status] = row.count;
        }
        const escalationsByStatus = {};
        for (const row of escalationCounts.rows) {
            escalationsByStatus[row.status] = row.count;
        }
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        durable_workflows: durableWorkflows.rows,
                        tasks: tasksByStatus,
                        escalations: escalationsByStatus,
                        active_workflow_types: activeTypes.rows.map((r) => r.workflow_type),
                        recent_activity: recentActivity.rows[0],
                        mcp_servers: {
                            ...mcpServers.rows[0],
                            servers: mcpServerList.rows,
                        },
                        compiled_workflows: compiledWorkflows.rows[0],
                        workflow_configs: workflowConfigs.rows,
                    }),
                }],
        };
    });
}
