import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { Box, Text } from 'ink';
import React from 'react';
import { InfoField } from '../components/ui/info-field.js';
import { TitledBoxWithPreferences } from '../components/ui/titled-box.js';
import { CustomCommandLoader } from '../custom-commands/loader.js';
import { useTerminalWidth } from '../hooks/useTerminalWidth.js';
import { useTheme } from '../hooks/useTheme.js';
import { getCommandLoader } from '../message-handler.js';
import { generateKey } from '../session/key-generator.js';
import { infoMsg } from '../utils/message-factory.js';
/** Build the `/name <param> ...` invocation string. Used for the top row
 * of each command entry. Description and aliases now render on their own
 * indented secondary lines for visual consistency with `/agents`. */
function formatCommandHeader(cmd) {
    const parts = [`/${cmd.fullName}`];
    if (cmd.metadata.parameters && cmd.metadata.parameters.length > 0) {
        parts.push(cmd.metadata.parameters.map((p) => `<${p}>`).join(' '));
    }
    return parts.join(' ');
}
function aliasesLine(cmd) {
    if (!cmd.metadata.aliases || cmd.metadata.aliases.length === 0)
        return null;
    const names = cmd.metadata.aliases.map((a) => cmd.namespace ? `${cmd.namespace}:${a}` : a);
    return `aliases: ${names.join(', ')}`;
}
/** Single command entry. Matches the visual shape of `/agents` list rows:
 * bold `› /name` + secondary meta on the header line, then indented
 * description and any auxiliary lines (aliases, tags, token estimate). */
function CommandEntry({ cmd, isLast }) {
    const { colors } = useTheme();
    const aliases = aliasesLine(cmd);
    const tokenEst = cmd.metadata.estimatedTokens
        ? `~${cmd.metadata.estimatedTokens} tokens`
        : null;
    const tags = cmd.metadata.tags?.length
        ? `tags: ${cmd.metadata.tags.map((t) => `\`${t}\``).join(', ')}`
        : null;
    return (_jsxs(Box, { flexDirection: "column", marginBottom: isLast ? 0 : 1, children: [_jsxs(Box, { children: [_jsxs(Text, { color: colors.text, bold: true, children: ["\u203A ", formatCommandHeader(cmd)] }), tokenEst && _jsxs(Text, { color: colors.secondary, children: [" \u00B7 ", tokenEst] })] }), cmd.metadata.description && (_jsx(Box, { marginLeft: 4, children: _jsx(Text, { color: colors.secondary, children: cmd.metadata.description }) })), aliases && (_jsx(Box, { marginLeft: 4, children: _jsx(Text, { color: colors.secondary, children: aliases }) })), tags && (_jsx(Box, { marginLeft: 4, children: _jsx(Text, { color: colors.secondary, children: tags }) }))] }));
}
function CustomCommands({ commands }) {
    const { colors } = useTheme();
    // Sort commands alphabetically by full name
    const sortedCommands = [...commands].sort((a, b) => a.fullName.localeCompare(b.fullName));
    // Separate auto-injectable commands (with triggers/tags) from manual-only
    const autoInjectable = sortedCommands.filter(cmd => cmd.metadata.triggers?.length || cmd.metadata.tags?.length);
    const manualOnly = sortedCommands.filter(cmd => !cmd.metadata.triggers?.length && !cmd.metadata.tags?.length);
    return (_jsx(TitledBoxWithPreferences, { title: "Custom Commands", width: 75, borderColor: colors.primary, paddingX: 2, paddingY: 1, flexDirection: "column", marginBottom: 1, children: commands.length === 0 ? (_jsxs(_Fragment, { children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: colors.text, bold: true, children: "No custom commands found" }) }), _jsx(Text, { color: colors.text, children: "To create custom commands:" }), _jsxs(Text, { color: colors.secondary, children: ["1. Create a ", _jsx(Text, { color: colors.primary, children: ".nanocoder/commands" }), ' ', "directory in your project"] }), _jsxs(Text, { color: colors.secondary, children: ["2. Add ", _jsx(Text, { color: colors.primary, children: ".md" }), " files with command prompts"] }), _jsx(Text, { color: colors.secondary, children: "3. Optionally add frontmatter for metadata:" }), _jsx(Box, { marginTop: 1, marginBottom: 1, children: _jsxs(Text, { color: colors.secondary, children: [`---\n`, `description: Generate unit tests\n`, `aliases: [test, unittest]\n`, `parameters: [filename]\n`, `tags: [testing, quality]\n`, `triggers: [write tests, unit test]\n`, `---\n`, `Generate comprehensive unit tests for {{filename}}...`] }) })] })) : (_jsxs(_Fragment, { children: [manualOnly.length > 0 && (_jsxs(_Fragment, { children: [_jsx(Box, { marginBottom: 1, children: _jsxs(Text, { color: colors.primary, bold: true, children: ["Manual (", manualOnly.length, ")"] }) }), manualOnly.map((cmd, i) => (_jsx(CommandEntry, { cmd: cmd, isLast: i === manualOnly.length - 1 }, cmd.fullName)))] })), autoInjectable.length > 0 && (_jsxs(_Fragment, { children: [manualOnly.length > 0 && _jsx(Box, { marginTop: 1 }), _jsx(Box, { marginBottom: 1, children: _jsxs(Text, { color: colors.primary, bold: true, children: ["Auto-injectable (", autoInjectable.length, ")"] }) }), autoInjectable.map((cmd, i) => (_jsx(CommandEntry, { cmd: cmd, isLast: i === autoInjectable.length - 1 }, cmd.fullName)))] }))] })) }));
}
function CommandDetail({ command }) {
    const boxWidth = useTerminalWidth();
    const { colors } = useTheme();
    const sourceLabel = command.path
        ? `${command.source ?? 'project'} (${command.path})`
        : (command.source ?? 'project');
    const fields = [
        { label: 'Source', value: sourceLabel },
        ...(command.metadata.category
            ? [{ label: 'Category', value: command.metadata.category }]
            : []),
        ...(command.metadata.version
            ? [{ label: 'Version', value: command.metadata.version }]
            : []),
        ...(command.metadata.author
            ? [{ label: 'Author', value: command.metadata.author }]
            : []),
        ...(command.metadata.references?.length
            ? [
                {
                    label: 'References',
                    value: command.metadata.references.join(', '),
                },
            ]
            : []),
        ...(command.lastModified
            ? [
                {
                    label: 'Last modified',
                    value: command.lastModified.toLocaleDateString(),
                },
            ]
            : []),
    ];
    return (_jsxs(TitledBoxWithPreferences, { title: `Command: /${command.fullName}`, width: boxWidth, borderColor: colors.primary, paddingX: 2, paddingY: 1, flexDirection: "column", marginBottom: 1, children: [command.metadata.description && (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { children: command.metadata.description }) })), fields.map(f => (_jsx(InfoField, { label: f.label, value: f.value }, f.label))), command.metadata.examples?.length ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: colors.primary, bold: true, children: "Examples" }), command.metadata.examples.map((ex, i) => (_jsxs(Text, { color: colors.secondary, children: ["\u203A ", ex] }, i)))] })) : null, command.loadedResources?.length ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: colors.primary, bold: true, children: "Resources" }), command.loadedResources.map((r, i) => (_jsxs(Text, { color: colors.secondary, children: ["\u203A ", r.name, " (", r.type, ")", r.executable ? ' [executable]' : ''] }, i)))] })) : null] }));
}
export const commandsCommand = {
    name: 'custom-commands',
    description: 'List custom commands. Subcommands: show <name>, create <name>',
    handler: (args) => {
        // Prefer the app's shared loader so bundle-registered commands are
        // visible. Fall back to a fresh disk-scan instance only if no app
        // loader is registered (e.g. ad-hoc invocations from tests).
        const shared = getCommandLoader();
        const loader = shared ?? new CustomCommandLoader();
        if (!shared)
            loader.loadCommands();
        const sub = args[0];
        if (sub === 'show') {
            const name = args[1] ?? '';
            if (!name) {
                return Promise.resolve(infoMsg('Usage: /commands show <command-name>', 'commands'));
            }
            const command = loader.getCommand(name);
            if (!command) {
                return Promise.resolve(infoMsg(`Command "${name}" not found. Use /commands to list available commands.`, 'commands'));
            }
            return Promise.resolve(React.createElement(CommandDetail, {
                key: generateKey('commands-show'),
                command,
            }));
        }
        if (sub === 'create') {
            return Promise.resolve(infoMsg('Usage: /commands create <name>\nExample: /commands create review-code\n\nThis creates a new command file and starts an AI-assisted session to write its content.', 'commands'));
        }
        const commands = loader.getAllCommands() || [];
        return Promise.resolve(React.createElement(CustomCommands, {
            key: generateKey('custom-commands'),
            commands: commands,
        }));
    },
};
//# sourceMappingURL=custom-commands.js.map