const VALID_TAGS = ['pending', 'decision', 'idea', 'bug', 'blocker'];
/** Parse YAML frontmatter from a markdown string. Returns parsed fields and body. */
export function extractFrontmatter(raw) {
    const match = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(raw);
    if (!match) {
        return { meta: {}, body: raw };
    }
    /* v8 ignore next 2 */
    const yamlBlock = match[1] ?? '';
    const body = match[2] ?? '';
    const meta = {};
    for (const line of yamlBlock.split('\n')) {
        const colon = line.indexOf(':');
        if (colon === -1) {
            continue;
        }
        const key = line.slice(0, colon).trim();
        const val = line.slice(colon + 1).trim();
        if (!key) {
            continue;
        }
        // Parse arrays: [a, b, c]
        if (val.startsWith('[') && val.endsWith(']')) {
            meta[key] = val
                .slice(1, -1)
                .split(',')
                .map((s) => s.trim().replace(/^['"]|['"]$/g, ''))
                .filter(Boolean);
        }
        else if (val === 'null' || val === '') {
            meta[key] = null;
        }
        else {
            meta[key] = val.replace(/^['"]|['"]$/g, '');
        }
    }
    return { meta, body };
}
/** Build a YAML frontmatter block from a metadata object. */
export function buildFrontmatter(meta) {
    const lines = ['---'];
    for (const [key, val] of Object.entries(meta)) {
        if (val === null || val === undefined) {
            continue;
        }
        if (Array.isArray(val)) {
            lines.push(`${key}: [${val.join(', ')}]`);
        }
        else if (typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean') {
            lines.push(`${key}: ${val}`);
        }
    }
    lines.push('---');
    return lines.join('\n') + '\n';
}
/** Strip frontmatter from content, returning only the body. */
export function stripFrontmatter(content) {
    const { body } = extractFrontmatter(content);
    return body;
}
/** Parse NoteTag[] from raw frontmatter tags array. Validates tags. */
export function parseTagsFromMeta(rawTags) {
    if (!Array.isArray(rawTags)) {
        return [];
    }
    return rawTags.filter((t) => VALID_TAGS.includes(t));
}
/** Build the complete .md content string with frontmatter. */
export function buildNoteContent(body, meta) {
    const frontmatterFields = {
        key: meta.key,
        tags: meta.tags.length > 0 ? meta.tags : [],
        createdAt: meta.createdAt,
    };
    if (meta.specId) {
        frontmatterFields.specId = meta.specId;
    }
    if (meta.expiresAt) {
        frontmatterFields.expiresAt = meta.expiresAt;
    }
    return buildFrontmatter(frontmatterFields) + body;
}
//# sourceMappingURL=tags.js.map