"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.createEventsServer = createEventsServer;
exports.stopEventsServer = stopEventsServer;
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
const zod_1 = require("zod");
const logger_1 = require("../../lib/logger");
const events_1 = require("../../lib/events");
function registerTools(srv) {
    srv.registerTool('publish_event', {
        title: 'Publish Event',
        description: 'Publish a custom event to the event bus. Other agents can subscribe and react.',
        inputSchema: {
            topic: zod_1.z.string().describe('Event topic (e.g., app.epic.apis.createorder.error)'),
            data: zod_1.z.record(zod_1.z.any()).optional().describe('Event payload data'),
            source: zod_1.z.string().optional().describe('Source identifier'),
        },
    }, async (args) => {
        const topic = args.topic.startsWith('app.') ? args.topic : `app.${args.topic}`;
        const event = {
            type: topic,
            source: args.source || 'mcp-tool',
            workflowId: '',
            workflowName: '',
            taskQueue: '',
            data: args.data,
            timestamp: new Date().toISOString(),
        };
        await events_1.eventRegistry.publish(event);
        // Auto-register topic in catalog (learn-on-first-use)
        const { upsertTopicOnPublish } = await Promise.resolve().then(() => __importStar(require('../../services/topics')));
        await upsertTopicOnPublish(topic, args.data, args.source || 'mcp-tool').catch(() => { });
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ published: true, topic, timestamp: event.timestamp }),
                },
            ],
        };
    });
    srv.registerTool('list_subscriptions', {
        title: 'List Event Subscriptions',
        description: 'List all active agent event subscriptions.',
        inputSchema: {
            topic: zod_1.z.string().optional().describe('Optional topic pattern to filter'),
        },
    }, async (args) => {
        // Import lazily to avoid circular dependency at module load time
        const { listActiveSubscriptions } = await Promise.resolve().then(() => __importStar(require('../../services/agent/subscriptions')));
        const subs = await listActiveSubscriptions();
        const filtered = args.topic
            ? subs.filter((s) => s.topic.includes(args.topic))
            : subs;
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ subscriptions: filtered, total: filtered.length }),
                },
            ],
        };
    });
    srv.registerTool('list_topics', {
        title: 'List Topics',
        description: 'Browse the topic catalog to discover available event topics, their descriptions, payload schemas, and subscriber counts.',
        inputSchema: {
            category: zod_1.z.string().optional().describe('Filter by category (task, workflow, escalation, activity, knowledge, agent, app, milestone)'),
            search: zod_1.z.string().optional().describe('Search topics by name or description'),
            limit: zod_1.z.number().optional().describe('Max results (default 50)'),
        },
    }, async (args) => {
        const { listTopics } = await Promise.resolve().then(() => __importStar(require('../../services/topics')));
        const result = await listTopics({
            category: args.category,
            search: args.search,
            limit: args.limit ?? 50,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify(result),
                },
            ],
        };
    });
    srv.registerTool('register_topic', {
        title: 'Register Topic',
        description: 'Declare a topic in the catalog with its description and payload schema before first publish.',
        inputSchema: {
            topic: zod_1.z.string().describe('Topic name (e.g., app.vendor.orders.created)'),
            description: zod_1.z.string().optional().describe('Human-readable description'),
            category: zod_1.z.string().optional().describe('Category (defaults to first segment or "app")'),
            payload_schema: zod_1.z.record(zod_1.z.any()).optional().describe('JSON Schema for event.data'),
            tags: zod_1.z.array(zod_1.z.string()).optional().describe('Tags for filtering'),
        },
    }, async (args) => {
        const { createTopic } = await Promise.resolve().then(() => __importStar(require('../../services/topics')));
        const category = args.category || (args.topic.startsWith('app.') ? 'app' : args.topic.split('.')[0]);
        try {
            const entry = await createTopic({
                topic: args.topic,
                description: args.description,
                category,
                payload_schema: args.payload_schema,
                source: 'mcp-tool',
                tags: args.tags,
            });
            return {
                content: [
                    {
                        type: 'text',
                        text: JSON.stringify({ registered: true, topic: entry }),
                    },
                ],
            };
        }
        catch (err) {
            if (err.code === '23505') {
                return {
                    content: [
                        {
                            type: 'text',
                            text: JSON.stringify({ registered: false, error: `Topic "${args.topic}" already exists` }),
                        },
                    ],
                };
            }
            throw err;
        }
    });
}
async function createEventsServer(options) {
    const name = options?.name || 'long-tail-events';
    const instance = new mcp_js_1.McpServer({ name, version: '1.0.0' });
    registerTools(instance);
    logger_1.loggerRegistry.info(`[lt-mcp:events] ${name} ready (4 tools)`);
    return instance;
}
async function stopEventsServer() {
    logger_1.loggerRegistry.info('[lt-mcp:events] stopped');
}
