import { SlashCommandParser } from './parser.js';
/**
 * Registers slash-command modules and dispatches parsed command input.
 */
export class SlashCommandRegistry {
    commandList;
    hintList;
    constructor(modules) {
        this.commandList = SlashCommandRegistry.flattenModules(modules);
        this.hintList = SlashCommandRegistry.flattenModuleHints(modules);
        SlashCommandRegistry.validate(modules, this.commandList);
    }
    commands() {
        return [...this.commandList];
    }
    hints() {
        return [...this.hintList];
    }
    find(input) {
        const parsed = typeof input === 'string' ? SlashCommandParser.parse(input) : input;
        if (!parsed) {
            return undefined;
        }
        const command = this.commandList.find((candidate) => candidate.match(parsed));
        return command ? { command, input: parsed } : undefined;
    }
    async run(context, input) {
        const matched = this.find(input);
        return matched ? await matched.command.run(context, matched.input) : undefined;
    }
    static flattenModuleHints(modules) {
        return modules.flatMap((module) => module.hints ?? module.commands.map((command) => ({
            command: command.syntax,
            description: command.description,
        })));
    }
    static flattenModules(modules) {
        return modules.flatMap((module) => module.commands);
    }
    static validate(modules, commands) {
        SlashCommandRegistry.assertUnique('slash command module id', modules.map((module) => module.id));
        SlashCommandRegistry.assertUnique('slash command id', commands.map((command) => command.id));
        SlashCommandRegistry.assertUnique('slash command syntax', commands.flatMap((command) => [command.syntax, ...(command.aliases ?? [])]));
    }
    static assertUnique(label, values) {
        const seen = new Set();
        for (const value of values) {
            if (seen.has(value)) {
                throw new Error(`Duplicate ${label}: ${value}`);
            }
            seen.add(value);
        }
    }
}
//# sourceMappingURL=registry.js.map