function splitLines(raw) {
    return raw.replace(/\r\n/g, '\n').split('\n');
}
function parseList(lines, startIndex, stopHeaders = ['## ', '### ']) {
    const items = [];
    let index = startIndex;
    while (index < lines.length) {
        const line = lines[index].trim();
        if (!line) {
            index++;
            continue;
        }
        if (stopHeaders.some((header) => line.startsWith(header)))
            break;
        if (!line.startsWith('- ')) {
            throw new Error(`Expected list item, received: ${line}`);
        }
        items.push(line.slice(2).trim());
        index++;
    }
    return { items, nextIndex: index };
}
function parseProvenanceLine(line) {
    const parts = line
        .slice(2)
        .split('|')
        .map((part) => part.trim());
    const values = new Map();
    for (const part of parts) {
        const separatorIndex = part.indexOf('=');
        if (separatorIndex === -1) {
            throw new Error(`Invalid provenance field: ${part}`);
        }
        values.set(part.slice(0, separatorIndex).trim(), part.slice(separatorIndex + 1).trim());
    }
    const sessionId = values.get('session');
    const checkpoint = values.get('checkpoint');
    const timestamp = values.get('timestamp');
    if (!sessionId || !checkpoint || !timestamp) {
        throw new Error('Missing provenance fields');
    }
    return {
        sessionId,
        checkpoint,
        timestamp,
        traceRefs: values
            .get('traces')
            ?.split(',')
            .map((trace) => trace.trim())
            .filter(Boolean) ?? []
    };
}
export function slugifyTopicFileName(title) {
    const slug = title
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '');
    return `${slug || 'topic'}.md`;
}
export function slugifyEntryId(summary) {
    return (summary
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '_')
        .replace(/^_+|_+$/g, '')
        .slice(0, 64) || 'entry');
}
export function renderTopicDocument(topic) {
    const lines = [`# Topic: ${topic.title}`, '', '## When To Read'];
    lines.push(...topic.whenToRead.map((item) => `- ${item}`));
    lines.push('', '## Entries');
    for (const entry of topic.entries) {
        lines.push('', `### Entry: ${entry.id}`);
        lines.push(`Summary: ${entry.summary}`);
        lines.push('Details:');
        lines.push(...entry.details.map((detail) => `- ${detail}`));
        if (entry.provenance.length > 0) {
            lines.push('Provenance:');
            lines.push(...entry.provenance.map((item) => `- session=${item.sessionId} | checkpoint=${item.checkpoint} | timestamp=${item.timestamp} | traces=${item.traceRefs.join(', ')}`));
        }
    }
    return `${lines.join('\n').trim()}\n`;
}
export function parseTopicDocument(fileName, raw) {
    try {
        const lines = splitLines(raw);
        if (!lines[0]?.startsWith('# Topic: ')) {
            return null;
        }
        const title = lines[0].slice('# Topic: '.length).trim();
        let index = 1;
        while (index < lines.length && !lines[index].trim())
            index++;
        if (lines[index]?.trim() !== '## When To Read') {
            return null;
        }
        index++;
        const whenToReadSection = parseList(lines, index);
        index = whenToReadSection.nextIndex;
        while (index < lines.length && !lines[index].trim())
            index++;
        if (lines[index]?.trim() !== '## Entries') {
            return null;
        }
        index++;
        const entries = [];
        while (index < lines.length) {
            while (index < lines.length && !lines[index].trim())
                index++;
            if (index >= lines.length)
                break;
            if (!lines[index].startsWith('### Entry: ')) {
                return null;
            }
            const entryId = lines[index].slice('### Entry: '.length).trim();
            index++;
            if (!lines[index]?.startsWith('Summary: ')) {
                return null;
            }
            const summary = lines[index].slice('Summary: '.length).trim();
            index++;
            if (lines[index]?.trim() !== 'Details:') {
                return null;
            }
            index++;
            const detailsSection = parseList(lines, index, ['Provenance:', '## ', '### ']);
            index = detailsSection.nextIndex;
            let provenance = [];
            while (index < lines.length && !lines[index].trim())
                index++;
            if (lines[index]?.trim() === 'Provenance:') {
                index++;
                const provenanceSection = parseList(lines, index);
                index = provenanceSection.nextIndex;
                provenance = provenanceSection.items.map((item) => parseProvenanceLine(`- ${item}`));
            }
            entries.push({
                id: entryId,
                summary,
                details: detailsSection.items,
                provenance
            });
        }
        return {
            fileName,
            title,
            whenToRead: whenToReadSection.items,
            entries
        };
    }
    catch {
        return null;
    }
}
//# sourceMappingURL=topic-file.js.map