import { classifyRisk } from "./debloat-nlp.js";
function emitEvent(type, payload) {
    return { type: type, timestamp: new Date().toISOString(), data: payload };
}
function isSlashCommand(text) {
    return text.trimStart().startsWith("/");
}
function extractSlashCommand(text) {
    const match = text.trimStart().match(/^\/([a-zA-Z0-9_-]+)/);
    return match?.[1]?.toLowerCase() ?? "";
}
function resolveRisk(intent, raw) {
    if (intent === "chat")
        return classifyRisk("chat", raw);
    return classifyRisk(intent, raw);
}
export function createCommandBus() {
    const handlers = new Map();
    const dispatch = async (envelope) => {
        const events = [];
        const text = envelope.rawText;
        events.push(emitEvent("command:received", { text: text.slice(0, 120) }));
        if (isSlashCommand(text)) {
            const command = extractSlashCommand(text);
            events.push(emitEvent("command:identified", { command, type: "slash" }));
            const handler = handlers.get(command);
            if (handler) {
                events.push(emitEvent("command:dispatching", { command }));
                const result = await handler(envelope);
                return {
                    ...result,
                    events: [...events, ...result.events],
                };
            }
            events.push(emitEvent("command:unhandled", { command }));
            return {
                handled: false,
                events,
                output: `Unknown command: /${command}. Use /help for available commands.`,
            };
        }
        const risk = resolveRisk("chat", text);
        events.push(emitEvent("command:fallback", { risk, intent: "chat" }));
        return {
            handled: false,
            events,
            output: "",
        };
    };
    const registerHandler = (command, handler) => {
        handlers.set(command.toLowerCase(), handler);
    };
    const listCommands = () => {
        return [...handlers.keys()];
    };
    return { dispatch, registerHandler, listCommands };
}
