import { writeFileSync, readFileSync, existsSync } from "fs";
import { join } from "path";
import { getPluginsForDirectory, pluginToSlashCommands } from "./plugins.js";
import { customSkillsService } from "./custom-skills-service.js";
import { DATA_DIR, ensureDataDir } from "../utils/paths.js";
const SLASH_COMMANDS_FILE = join(DATA_DIR, "slash-commands.json");
/**
 * Load slash commands data from JSON file
 */
function loadSlashCommandsData() {
    ensureDataDir();
    if (!existsSync(SLASH_COMMANDS_FILE)) {
        return {};
    }
    try {
        const data = readFileSync(SLASH_COMMANDS_FILE, "utf-8");
        return JSON.parse(data);
    }
    catch (error) {
        console.warn("Failed to load slash commands data:", error);
        return {};
    }
}
/**
 * Save slash commands data to JSON file
 */
function saveSlashCommandsData(data) {
    ensureDataDir();
    try {
        writeFileSync(SLASH_COMMANDS_FILE, JSON.stringify(data, null, 2));
    }
    catch (error) {
        console.error("Failed to save slash commands data:", error);
        throw error;
    }
}
/**
 * Get slash commands for a specific directory
 */
export function getSlashCommandsForDirectory(directory) {
    const data = loadSlashCommandsData();
    return data[directory] || [];
}
/**
 * Set slash commands for a specific directory
 */
export function setSlashCommandsForDirectory(directory, commands) {
    const data = loadSlashCommandsData();
    data[directory] = commands;
    saveSlashCommandsData(data);
}
/**
 * Get both slash commands and plugins for a directory.
 * Callboard custom skills are appended as `callboard:<name>` entries (deduped
 * against CLI-reported commands) so they show up in autocomplete immediately,
 * before any session has run in the directory.
 */
export function getCommandsAndPluginsForDirectory(directory) {
    const slashCommands = new Set(getSlashCommandsForDirectory(directory));
    const plugins = getPluginsForDirectory(directory);
    try {
        for (const cmd of customSkillsService.listSlashCommands()) {
            slashCommands.add(cmd);
        }
    }
    catch (error) {
        console.warn("Failed to append custom skill commands:", error);
    }
    return {
        slashCommands: Array.from(slashCommands),
        plugins,
    };
}
/**
 * Get all available commands for a directory including plugin commands (for compatibility)
 */
export function getAllCommandsForDirectory(directory, activePluginIds = []) {
    const { slashCommands, plugins } = getCommandsAndPluginsForDirectory(directory);
    // Start with regular slash commands, using a Set to avoid duplicates
    const allCommands = new Set(slashCommands);
    // Add commands from active plugins
    for (const plugin of plugins) {
        if (activePluginIds.includes(plugin.id)) {
            for (const cmd of pluginToSlashCommands(plugin)) {
                allCommands.add(cmd);
            }
        }
    }
    return Array.from(allCommands);
}
