export function parseCommandArgs(argsString) {
    const args = [];
    let current = '';
    let inQuote = null;
    for (let index = 0; index < argsString.length; index += 1) {
        const char = argsString[index];
        if (inQuote) {
            if (char === inQuote) {
                inQuote = null;
            }
            else {
                current += char;
            }
            continue;
        }
        if (char === '"' || char === "'") {
            inQuote = char;
            continue;
        }
        if (char === ' ' || char === '\t') {
            if (current) {
                args.push(current);
                current = '';
            }
            continue;
        }
        current += char;
    }
    if (current) {
        args.push(current);
    }
    return args;
}
export function substituteArgs(content, args) {
    let result = content;
    // Resolve `$N` positional args first so a later wildcard expansion that
    // happens to contain `$1` text isn't recursively re-substituted.
    result = result.replace(/\$(\d+)/g, (_, num) => {
        const index = parseInt(num, 10) - 1;
        return args[index] ?? '';
    });
    // Bash-style `${@:start}` / `${@:start:length}` slice, before plain `$@`
    // so the longer pattern wins. User indices are 1-based.
    result = result.replace(/\$\{@:(\d+)(?::(\d+))?\}/g, (_, startStr, lengthStr) => {
        let start = parseInt(startStr, 10) - 1;
        if (start < 0)
            start = 0;
        if (lengthStr) {
            const length = parseInt(lengthStr, 10);
            return args.slice(start, start + length).join(' ');
        }
        return args.slice(start).join(' ');
    });
    const allArgs = args.join(' ');
    result = result.replace(/\$ARGUMENTS/g, allArgs);
    result = result.replace(/\$@/g, allArgs);
    return result;
}
export function expandPromptTemplate(text, templates) {
    if (!text.startsWith('/'))
        return text;
    const spaceIndex = text.indexOf(' ');
    const templateName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
    const argsString = spaceIndex === -1 ? '' : text.slice(spaceIndex + 1);
    const template = templates.find((candidate) => candidate.name === templateName);
    if (!template) {
        return text;
    }
    return substituteArgs(template.content, parseCommandArgs(argsString));
}
//# sourceMappingURL=prompt-template-expansion.js.map