/**
 * Commands detector — mirrors the command dispatch in versions.ts. Inspects the version home,
 * returns command names. Honors the commands-as-skills marker for skills-only
 * agents (Kimi, Codex >= 0.117.0, …), treats the native file as authoritative
 * for dual-write targets (the skill copy is deliberately absent on a name
 * collision), and scans `{agentDir}/<commandsSubdir>/` for native-only targets.
 */
import * as fs from 'fs';
import * as path from 'path';
import { AGENTS, MANAGED_AGENT_IDS, agentConfigDirName } from '../../agents.js';
import { listCommandSkillsInVersion, shouldInstallCommandAsSkill, } from '../../command-skills.js';
import { lazyAgentMap } from '../writers/lazy-map.js';
function buildCommandsDetector(agent) {
    return {
        kind: 'commands',
        agent,
        list({ version, versionHome }) {
            const agentConfig = AGENTS[agent];
            const agentDir = path.join(versionHome, agentConfigDirName(agent));
            if (shouldInstallCommandAsSkill(agent, version)) {
                return listCommandSkillsInVersion(agentDir);
            }
            const commandsDir = path.join(agentDir, agentConfig.commandsSubdir);
            if (!fs.existsSync(commandsDir))
                return [];
            const ext = agentConfig.format === 'toml' ? '.toml' : '.md';
            const nativeCommands = fs.readdirSync(commandsDir)
                .filter(f => f.endsWith(ext))
                .map(f => f.replace(new RegExp(`\\${ext}$`), ''));
            // For a dual-write target the native file is the authoritative record that
            // the command synced. The skill copy is derived, and
            // installCommandSkillToVersion deliberately writes none when a real skill
            // source already owns the name -- requiring both copies reported those
            // commands missing forever and drove an `agents refresh` loop no sync could
            // clear. This also matches `agents doctor`/`prune`, which read the
            // unfiltered listCommandsInVersionHome.
            return nativeCommands;
        },
    };
}
// Detector registration mirrors writers/commands.ts — skills-capable agents
// with no native command-file dir convert commands to skills by default; only
// agents with their own slash-command runtime (nativeCommandRuntime) opt out.
export const commandsDetectors = lazyAgentMap(() => {
    const m = {};
    for (const id of MANAGED_AGENT_IDS) {
        const cfg = AGENTS[id];
        if (cfg.capabilities.commands === false && (!cfg.commandsSubdir || cfg.commandsSubdir === '') && cfg.nativeCommandRuntime)
            continue;
        const hasCommands = cfg.capabilities.commands !== false;
        const hasSkills = cfg.capabilities.skills !== false;
        if (hasCommands || hasSkills)
            m[id] = buildCommandsDetector(id);
    }
    return m;
});
