import path from 'node:path';
function parseScalar(raw) {
    const trimmed = raw.trim();
    if (!trimmed) {
        return undefined;
    }
    if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
        return trimmed.slice(1, -1).trim();
    }
    return trimmed;
}
function parseList(raw) {
    const trimmed = raw.trim();
    if (!trimmed) {
        return [];
    }
    const withoutBrackets = trimmed.startsWith('[') && trimmed.endsWith(']') ? trimmed.slice(1, -1) : trimmed;
    return withoutBrackets
        .split(',')
        .map((item) => parseScalar(item) ?? '')
        .filter(Boolean);
}
function fallbackCommandName(sourcePath) {
    return path.basename(sourcePath, path.extname(sourcePath)).trim();
}
function parseFrontmatter(rawFrontmatter) {
    const parsed = {};
    for (const line of rawFrontmatter.split(/\r?\n/)) {
        const match = line.match(/^\s*([A-Za-z][A-Za-z0-9_-]*)\s*:\s*(.*)$/);
        if (!match) {
            continue;
        }
        const key = match[1];
        const value = match[2] ?? '';
        if (key === 'name') {
            parsed.name = parseScalar(value);
        }
        if (key === 'description') {
            parsed.description = parseScalar(value);
        }
        if (key === 'allowedTools' || key === 'allowed-tools') {
            parsed.allowedTools = parseList(value);
        }
        if (key === 'argumentHint' || key === 'argument-hint') {
            parsed.argumentHint = parseScalar(value);
        }
    }
    return parsed;
}
/**
 * 解析 Markdown slash command。
 * 主流程：读取可选 YAML frontmatter -> 使用正文作为 prompt 模板 -> 缺省命令名取文件名。
 */
export function parseAcodeCommandMarkdown(sourcePath, rawMarkdown) {
    const normalized = rawMarkdown.replace(/^\uFEFF/, '');
    let body = normalized;
    let metadata = {};
    if (normalized.startsWith('---')) {
        const end = normalized.indexOf('\n---', 3);
        if (end >= 0) {
            metadata = parseFrontmatter(normalized.slice(3, end));
            body = normalized.slice(end + '\n---'.length).replace(/^\r?\n/, '');
        }
    }
    const name = (metadata.name || fallbackCommandName(sourcePath)).replace(/^\/+/, '').trim();
    if (!name) {
        throw new Error(`ACode command name is empty: ${sourcePath}`);
    }
    return {
        name,
        description: metadata.description,
        allowedTools: metadata.allowedTools,
        argumentHint: metadata.argumentHint,
        body: body.trim(),
        sourcePath,
    };
}
