import fs from 'node:fs';
import path from 'node:path';
import { configDir } from '../config.js';
function commandsInDir(dir) {
    let files;
    try {
        files = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
    }
    catch {
        return [];
    }
    const out = [];
    for (const f of files) {
        let text;
        try {
            text = fs.readFileSync(path.join(dir, f), 'utf8');
        }
        catch {
            continue;
        }
        let description = '';
        const fm = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
        if (fm) {
            const d = fm[1].match(/^description:\s*(.*)$/m);
            if (d)
                description = d[1].trim().replace(/^["']|["']$/g, '');
            text = text.slice(fm[0].length);
        }
        out.push({ name: f.replace(/\.md$/, ''), description, template: text.trim() });
    }
    return out;
}
/** Project commands (.cheapcode/commands/*.md) override global (~/.config/cheapcode/commands/*.md). */
export function discoverCommands(cwd) {
    const byName = new Map();
    for (const dir of [path.join(cwd, '.cheapcode', 'commands'), path.join(configDir(), 'commands')]) {
        for (const cmd of commandsInDir(dir)) {
            if (!byName.has(cmd.name))
                byName.set(cmd.name, cmd);
        }
    }
    return [...byName.values()];
}
export function expandCommand(cmd, args) {
    return cmd.template.includes('$ARGUMENTS')
        ? cmd.template.replaceAll('$ARGUMENTS', args)
        : args
            ? `${cmd.template}\n\n${args}`
            : cmd.template;
}
